2013-01-08 78 views
2

我是Assembly中的初學者(實際上這是我的第一次嘗試),我想知道如何讓這個x86彙編代碼在我的Mac上使用NASM和ld鏈接器運行。在Mac OSX上使用NASM和ld

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可執行文件,但是如果可以的話,我該怎麼做呢?如果不是,我將如何改變這個彙編代碼,以便它能夠工作,但通常情況是一樣的?

+0

謝謝,但我又是一個完整的初學者,你介意我應該怎樣稱呼標準庫嗎? –

回答

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 

注意,「世界,你好」是一個特別糟糕的第一彙編程序,並且通常不建議使用asm來完成I/O和其他高級別的事情。

+0

很好的答案。組裝和鏈接的語法和方法看起來與linux完全不同,我似乎找不到任何關於mac的彙編的優秀和全面的資源,有誰知道嗎? –

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可執行更多信息。組裝時

+0

thexploit鏈接404'd。 thexploit.com首頁似乎是一個空的Apache服務器。 –

+1

謝謝 - 我將刪除無效鏈接。 –