2

我是汇编的初学者(事实上这是我第一次尝试),我想知道如何使用 NASM 和 ld 链接器让这个 x86 汇编代码在我的 Mac 上运行。

SECTION .data           ; Section containing initialised data

    EatMsg: db "Eat at Joe's!",10
    EatLen: equ $-EatMsg    

SECTION .bss            ; Section containing uninitialized data 

SECTION .text           ; Section containing code

global  _start          ; Linker needs this to find the entry point!

_start:
    nop         ; This no-op keeps gdb happy...
    mov eax,4       ; Specify sys_write call
    mov ebx,1       ; Specify File Descriptor 1: Standard Output
    mov ecx,EatMsg      ; Pass offset of the message
    mov edx,EatLen      ; Pass the length of the message
    int 80H         ; Make kernel call

    MOV eax,1       ; Code for Exit Syscall
    mov ebx,0       ; Return a code of zero 
    int 80H         ; Make kernel call

这个汇编代码来自一本为 linux 编写的书,但是由于 linux 和 mac 都是基于 unix 的操作系统,我认为汇编代码通常是相同的。我现在意识到我可能无法通过 nasm 和 ld 将它转换为 mac 可执行文件,但如果可以,我该怎么做?如果没有,我将如何更改此汇编代码以使其正常工作,但通常做同样的事情?

4

2 回答 2

4

以下示例代码在使用 nasm 组装并使用 gcc 链接时应该可以工作(需要与标准 c 库链接!)

SECTION .data           ; Section containing initialised data

    EatMsg: db "Eat at Joe's!",10
    EatLen: equ $-EatMsg

SECTION .bss            ; Section containing uninitialized data

SECTION .text           ; Section containing code

global main
extern write

main:
    sub esp, 12                 ; allocate space for locals/arguments
    mov dword [esp], 1          ; stdout
    mov dword [esp+4], EatMsg   ; Pass offset of the message
    mov dword [esp+8], EatLen   ; Pass the length of the message
    call write                  ; Make library call

    mov eax,0                   ; Return a code of zero
    add esp, 12                 ; restore stack
    ret

请注意,“Hello world”是一个特别糟糕的第一个 asm 程序,通常不建议从 asm 进行 I/O 和其他高级操作。

于 2013-01-08T22:58:46.817 回答
3

int 80H在 OS X 上已弃用,无论如何它使用与 Linux 不同的选择器。您可能应该改用syscall或调用标准 C 库。

请参阅:thexploit.com/secdev/mac-os-x-64-bit-assembly-system-calls以获取在 Mac OS X 上使用 nasm 的有用“Hello World”教程。

另请参阅:daveeveritt.tumblr.com/post/67819832/webstraction-2-from-unix-history-and-assembly-language,了解有关使用 nasm 构建 OS X 可执行文件的更多信息。

于 2013-01-08T22:53:54.423 回答