环境说明
系统-macOS Big Sur, 11.5.2
端终-iterm2(于Rosetta方式打开)
nasm-系统自带
NASM version 2.15.05 compiled on Nov 14 2020
nasm demo-来自网络的一个hello world示例
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
汇编代码到目标代码
即*.as - > *.o
//新创一个目录,而CD到当前目录,新建一个hello.asm文件,内容为上面示例代码
nasm -f macho64 -o hello.o hello.asm
上述命令ok后,hello.asm文件同一目录下就出现了hello.o文件
$ tree -L 1
.
├── hello.asm
└── hello.o
目标代码到可执行文件
使用ld把目标代码链接成平台相关的可执行文件
$ ld -o hello -e _main hello.o -macosx_version_min 11.0 -lSyste
ld: library not found for -lSyste
提示库没有找到,指定统库路径
ld -o hello -e _main hello.o -macosx_version_min 11.0 -L /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lSystem
ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not allowed in code signed PIE, but used in _main from hello.o. To fix this warning, don't compile with -mdynamic-no-pic or link with -Wl,-no_pie
加 -no_pie选项关闭PIE模式
$ ld -no_pie -o hello -e _main hello.o -macosx_version_min 11.0 -L /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lSystem
最终当前目录下有
$ tree -L 1
.
├── hello
├── hello.asm
└── hello.o
0 directories, 3 files
执行可执行文件
$ ./hello
Hello World!