macos - 在 Mac OSX 上使用 NASM 和 ld

标签 macos assembly x86 nasm ld

我是汇编的初学者(事实上这是我第一次尝试),我想知道如何使用 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 可执行文件,但如果可以的话,我该怎么做呢?如果没有,我将如何更改此汇编代码以使其正常工作,但通常做同样的事情?

最佳答案

以下示例代码在使用 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 和其他高级操作。

关于macos - 在 Mac OSX 上使用 NASM 和 ld,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14225398/

相关文章:

c - 结构体中指针的偏移量,以及如何获取汇编中的值

c - 处理 TLB 未命中

c++ - 在 C++ 代码中使用嵌入式汇编语言进行错误分析

string - 复制字符串时出错 - ASM

objective-c - ARD 中的身份验证过程

macos - 如何丢弃 SourceTree 中未提交的更改?

ios - 强制 WKWebView 显示桌面版本

ios - IBM Worklight 应用程序构建器错误

assembly - .IF 和 CMP 之间的区别?调用和推送调用?使用哪一个?(MASM)

assembly - 任何在实模式下列出 BIOS 驱动器号的方法