我是汇编的初学者(事实上这是我第一次尝试),我想知道如何使用 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/