无法编译程序:CMach-O 64位格式不支持32位绝对地址

Unable to compile program:CMach-O 64-bit format does not support 32-bit absolute addresses

我想在我的 macOS Monterey 12.1 上学习 NASM x86 汇编语言。

我的代码如下:

SECTION .data
msg     db      'Hello World!', 0Ah     ; assign msg variable with your message string
 
SECTION .text
global  _start
 
_start:
 
    mov     edx, 13     ; number of bytes to write - one for each letter plus 0Ah (line feed character)
    mov     ecx, msg    ; move the memory address of our message string into ecx
    mov     ebx, 1      ; write to the STDOUT file
    mov     eax, 4      ; invoke SYS_WRITE (kernel opcode 4)
    int     80h

我输入指令后:

nasm -f macho64 -o helloworld.o helloworld.asm

我会得到:

helloworld.asm:15: error: Mach-O 64-bit format does not support 32-bit absolute addresses

有什么办法可以解决吗?

用于macho64的寻址space是x86-64,因此寄存器的大小不同,可以处理64位寻址。例如 ECX 是 32 位的,你试图用 64 位地址加载它,导致错误。

这是 x86-64 的 Hello World 代码的样子:

global _main

SECTION .data
msg     db      'Hello World!', 0x0A ; assign msg variable
 
SECTION .text
 
_main:
 
    mov     rdx, 13          ; number of bytes to write - one for each letter plus LF char.
    lea     rsi, [rel msg]   ; move the memory address of our message string into rsi
    mov     rdi, 1           ; write to the STDOUT file
    mov     rax, 0x2000004   ; invoke SYS_WRITE (kernel opcode 4)
    syscall
    
    mov     rax, 0x2000001   ; exit
    mov     rdi, 0
    syscall

编译、链接、执行:

% nasm -f macho64 -o helloworld.o helloworld.asm
% ld helloworld.o -o hello -lSystem -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib
% ./hello
Hello World!