1、编写hellowrold.asm
SECTION .data
msg: db "hello world", 0x0a
len: equ $ - msg
SECTION .text
global _main
kernel:
syscall
ret
_main:
mov rax,0x2000004
mov rdi,1
mov rsi,msg
mov rdx,len
call kernel
mov rax,0x2000001
mov rdi,0
call kernel
PS: 此汇编代码来源自网络,本人刚接触汇编
2、汇编helloworld
在asm文件同级目录的终端下输入:
nasm -f macho64 -o helloworld.o helloworld.asm
3、链接动态库
如果只输入:
ld -o helloworld -e _main helloworld.o
此时会报如下错误:
ld: dynamic main executables must link with libSystem.dylib for architecture x86_64
百度后原来需要链接动态库
ld -macosx_version_min 11.0.1 -o helloworld -e _main helloworld.o -lSystem
但是出现了新的错误
ld: library not found for -lSystem
后来又查了很多资料,原来是升级到Big Sur后的坑
苹果官方的介绍中有如下说明:
New in macOS Big Sur 11.0.1, the system ships with a built-in dynamic linker cache of all system-provided libraries. As part of this change, copies of dynamic libraries are no longer present on the filesystem. Code that attempts to check for dynamic library presence by looking for a file at a path or enumerating a directory will fail. Instead, check for library presence by attempting to
dlopen()
the path, which will correctly check for the library in the cache. (62986286)
所以我们的链接动态库命令应该改成下边这样:
ld -o helloworld -e _main helloworld.o -macosx_version_min 11.0.1 -L /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lSystem
4、运行
./helloworld