使用 NASM 为 x86_64 环境编译 32 位程序集

Use NASM to compile 32-bit assembly for x86_64 environment

我正在阅读一本书,其中所有汇编代码示例都是为 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

它根本不会那样工作。获取 VM 并在 VM 中安装 32 位 linux。问题不在于 x64 上的 运行 x86_32 代码。问题是在 MAC 上尝试 Linux 系统调用门。没有理由相信这会奏效。