使用NASM编译32位x86_64环境的汇编代码

3
我正在阅读一本书,其中所有的汇编代码示例都是针对32位Linux环境编写的,而我使用的是64位Mac。我将_start更改为start后,成功地使用NASM编译了以下程序。然而,当我运行可执行文件时,它没有像我预期的那样打印出hello world。有没有什么选项可以传递给NASM以便以在64位Mac上运行的方式编译这个程序?
我尝试过:
nasm -f macho32 helloworld.asm

并且。
nasm -f macho helloworld.asm

接着:

ld helloworld.o -o helloworld

我的代码是:

section .data       ; data segment
msg     db      "Hello, world!", 0x0a   ; the string and newline char

section .text       ; text segment
global start       ; Default entry point for ELF linking

start:
  ; SYSCALL: write(1, msg, 14) 
  mov eax, 4        ; put 4 into eax, since write is syscall #4
  mov ebx, 1        ; put 1 into ebx, since stdout is 1
  mov ecx, msg      ; put the address of the string into ecx
  mov edx, 14       ; put 14 into edx, since our string is 14 bytes
  int 0x80          ; Call the kernel to make the system call happen

  ; SYSCALL: exit(0)
  mov eax, 1        ; put 1 into eax, since exit is syscall #1
  mov ebx, 0        ; exit with success
  int 0x80          ; do the syscall

1
在OS/X上,int 0x80与Linux上的不同(系统调用不同)。使用Linux代码作为起点是不明智的。你真的需要一个32位Mac OS/X汇编语言教程。一个合理的起点在这里:https://filippo.io/making-system-calls-from-assembly-in-mac-os-x/ - Michael Petch
1
32位的OS/X代码可以在64位的OS/X上运行。如果你想创建真正的64位OS/X代码,那么你需要放弃int 0x80并开始使用syscall指令。这与int 0x80不同。调用约定不同,并且系统调用号与32位OS/X代码不匹配。你需要找到一个针对64位OS/X代码的教程。你还需要在NASM中使用-f macho64 - Michael Petch
1个回答

2

这样做是行不通的。你需要获取一个虚拟机,并在虚拟机中安装32位Linux系统。问题不在于在x64架构上运行x86_32代码,而是尝试在MAC上使用Linux系统调用门。没有理由相信这样会起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接