Nasm on OS X 用子例程替换 int 0x80

Nasm on OS X replace int 0x80 with subroutine

我试图了解当您在 OS X 机器上调用子例程时到底发生了什么(因为这就是我面前的东西)。我正在使用 nasm 版本 0.98.40.

我阅读了一些主要针对其他平台的教程并注意到其中一些有定义

_syscall:
    int 0x80
    ret

因此,我尝试了一个简单的 hello world,有和没有该子例程,但其他方面相同。

我很难理解为什么在这种情况下 calling 一个子例程不是 "equivalent to" 直接使用它的主体。我认为我没有打扰系统调用需要的任何寄存器。

这是两个程序集文件。

; without_subr.asm
section .text
global start

start:
    push dword msg.len
    push dword msg
    push dword 1
    mov eax,4
    sub esp,4
    int 0x80

    add esp,16

    push dword 0
    mov  eax, 1
    sub  esp, 12
    int 0x80

section .data

msg:    db 'Hello, world!',10
msg.len:   equ $ - msg

和子例程:

; with_subr.asm
section .text
global start


_syscall:
    int 0x80
    ret

start:
    push dword msg.len
    push dword msg
    push dword 1
    mov eax,4
    sub esp,4
    call _syscall

    add esp,16

    push dword 0
    mov  eax, 1
    sub  esp, 12
    int 0x80

section .data

msg:    db 'Hello, world!',10
msg.len:   equ $ - msg

当我 assemble、link 和 运行 without_subr.asm 一切正常时:

$ nasm -f macho without_subr.asm 
$ ld -o without_subr without_subr.o
$ ./without_subr 
Hello, world!

但是with_subr.asm什么都不产生,异常退出

$ nasm -f macho with_subr.asm 
$ ld -o with_subr with_subr.o
$ ./with_subr 
Exit 1

当您 call 子程序时,return 地址被压入堆栈。堆栈上的额外值将您事先 push 编辑的值留在了错误的位置。