在OS X中的汇编语言

7

我通过逐步学习汇编语言来学习Linux上的汇编语言编程。最近,我购买了一台Mac,在其中int 0x80似乎无法正常工作(非法指令)。

所以我想知道是否有一个好的参考资料(书籍/网页),可以介绍标准Unix汇编和Darwin汇编之间的区别。

3个回答

4

为了实际应用,本答案展示了在OSX上使用nasm编译“hello world”应用程序的方法。

这段代码可以直接编译成适用于Linux的格式,但是编译命令可能会有所不同:

section .text

global mystart                ; make the main function externally visible

mystart:

; 1 print "hello, world"

    ; 1a prepare the arguments for the system call to write
    push dword mylen          ; message length                           
    push dword mymsg          ; message to write
    push dword 1              ; file descriptor value

    ; 1b make the system call to write
    mov eax, 0x4              ; system call number for write
    sub esp, 4                ; OS X (and BSD) system calls needs "extra space" on stack
    int 0x80                  ; make the actual system call

    ; 1c clean up the stack
    add esp, 16               ; 3 args * 4 bytes/arg + 4 bytes extra space = 16 bytes

; 2 exit the program

    ; 2a prepare the argument for the sys call to exit
    push dword 0              ; exit status returned to the operating system

    ; 2b make the call to sys call to exit
    mov eax, 0x1              ; system call number for exit
    sub esp, 4                ; OS X (and BSD) system calls needs "extra space" on stack
    int 0x80                  ; make the system call

    ; 2c no need to clean up the stack because no code here would executed: already exited

section .data

  mymsg db "hello, world", 0xa  ; string with a carriage-return
  mylen equ $-mymsg             ; string length in bytes

将源代码(hello.nasm)组装成目标文件:

nasm -f macho hello.nasm

生成可执行文件的链接:

ld -o hello -e mystart hello.o

但是系统调用机制是否与Linux相同呢?我知道Solaris不同。 - Mr. Shickadance
语法在不同的编译器中可能会有很大的变化,包括不同的指令格式和调用约定。 - karlphillip
真正的区别在于32位mach二进制文件需要额外提供4个字节。这源自于BSD的遗产。请查看我的回复获取链接。 - Foo Bah

1
这个问题可能会有所帮助:OSX中XNU内核的系统调用列表和文档
不幸的是,看起来那里提到的书是唯一找到答案的途径。至于int 0x80,我怀疑它能否工作,因为它是一个相当特定于Linux的API,直接内置于内核中。
在处理陌生的操作系统时,我做出的妥协是只使用libc调用,但我可以理解,即使你只是想学习,这也可能过于高级。

0

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