os x中的汇编语言

yaa*_*ami 7 macos assembly

我一步一步地使用汇编语言来学习linux上的汇编语言编程.我最近买了一台Mac int 0x80似乎无法正常工作(非法指令).

所以只是想知道是否有一个很好的参考书(书/网页),它给出了标准的unix程序集和darwin程序集的差异.

kar*_*lip 4

出于实用目的,此答案展示了如何在 OSX 上使用nasm编译hello world应用程序。

可以按原样为 Linux 编译此代码,但编译它的 cmd 行命令可能会有所不同:

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
Run Code Online (Sandbox Code Playgroud)

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

nasm -f macho hello.nasm
Run Code Online (Sandbox Code Playgroud)

生成可执行文件的链接:

ld -o hello -e mystart hello.o
Run Code Online (Sandbox Code Playgroud)