【发布时间】:2011-10-22 21:12:01
【问题描述】:
我一步步用汇编语言学习linux上的汇编语言编程。我最近有一台 Mac,int 0x80 似乎无法在其上工作(非法指令)。
所以只是想知道是否有一个很好的参考(书籍/网页),它给出了标准 unix 程序集和 darwin 程序集的 b/w 差异。
【问题讨论】:
我一步步用汇编语言学习linux上的汇编语言编程。我最近有一台 Mac,int 0x80 似乎无法在其上工作(非法指令)。
所以只是想知道是否有一个很好的参考(书籍/网页),它给出了标准 unix 程序集和 darwin 程序集的 b/w 差异。
【问题讨论】:
出于实际目的,此答案显示how to compile a hello world application using nasm on OSX。
此代码可以按原样为 linux 编译,但编译它的 cmd-line 命令可能会有所不同:
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
【讨论】:
这个问题可能会有所帮助:List of and documentation for system calls for XNU kernel in OSX。
不幸的是,看起来只有提到的书才能找到答案。至于 int 0x80,我怀疑它是否会起作用,因为它是一个非常特定于 Linux 的 API,内置于内核中。
在不熟悉的操作系统上工作时我做出的妥协是只使用 libc 调用,但我可以理解,如果您只是想学习,即使这样也可能太高级了。
【讨论】:
你能发布你的代码以及你是如何编译的吗? (引发非法指令错误的方法有很多)
OSX 采用了 bsd 传递参数的风格,这就是为什么你必须做一些稍微不同的事情。
我不久前收藏了这个:http://www.freebsd.org/doc/en/books/developers-handbook/book.html#X86-SYSTEM-CALLS
【讨论】: