非法指令:4(Mac 64位,NASM)

4

我正在尝试使用NASM在Mac上编写64位汇编语言的helloworld程序。

每次运行时,我都会收到以下错误:

Illegal instruction: 4

以下是我的代码:

section .text
global _main

_main:
    mov rax, 4
    mov rbx, 1
    mov rcx, tekst
    mov rdx, dlugosc
    int 80h

    mov rax, 1
    int 80h

section .data

tekst   db  "Hello, world", 0ah
dlugosc equ $ - tekst

我正在使用以下编译方式:

nasm -f macho64 HelloWorld.asm

我正在链接以下内容:

ld -o HelloWorld -arch x86_64 -macosx_version_min 10.10 -lSystem -no_pie HelloWorld.o

非常感谢您的帮助。

相关的IT技术问题请随时与我联系。

尝试在调试器下运行它。 - Chris Stratton
"-macosx_version_min"和"10.10"之间应该有一个"=",对吗? - harold
如果相信 这个页面,你可能正在使用错误的系统调用号码并将参数放置在错误的寄存器中。 - nobody
你读了链接的页面吗?它看起来像是一个关于你正在尝试做的事情的教程。 - nobody
@AndrewMedico 非常感谢。之前没看到链接。我只需要改变所有的 "start" 为 "_main",就能够让链接页面上的代码正常运行。 - UssCompany
显示剩余4条评论
1个回答

3

让我们从最重要的事情开始:

在Mac OSX上,系统调用前缀为0x2000###,例如退出程序的系统调用为0x2000001。

接下来,我们需要使用正确的寄存器传递参数。

The number of the syscall has to be passed in register rax.

rdi - used to pass 1st argument to functions
rsi - used to pass 2nd argument to functions
rdx - used to pass 3rd argument to functions
rcx - used to pass 4th argument to functions
r8 - used to pass 5th argument to functions
r9 - used to pass 6th argument to functions

A system-call is done via the syscall instruction. The kernel destroys registers rcx and r11.

综上所述,您的代码的修正版本如下:

section .text
global _main

_main:
    mov rax, 0x2000004
    mov rdi, 1
    mov rsi, tekst
    mov rdx, dlugosc
    syscall

    mov rax, 0x2000001
    syscall

section .data

tekst   db  "Hello, world", 0ah
dlugosc equ $ - tekst

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接