【问题标题】:Illegal instruction: 4 (Mac 64-bit, NASM)非法指令:4(Mac 64 位,NASM)
【发布时间】:2015-01-09 16:53:56
【问题描述】:

我正在尝试使用 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

非常感谢任何帮助。

【问题讨论】:

  • 尝试在调试器下运行。
  • -macosx_version_min 和 10.10 之间应该有一个 =,对吧?
  • 如果this page 可信,那么您使用了错误的系统调用号并将您的参数放入错误的寄存器中。
  • @ChrisStratton 我反汇编了编译版本,似乎将所有 64 位寄存器(rax、rbx)更改为 32 位寄存器(eax、ebx),但 rcx 除外。
  • @harold 不,不应该有“=”之间。

标签: macos assembly nasm x86-64 ld


【解决方案1】:

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

在 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

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多