简体   繁体   中英

Illegal instruction: 4 (Mac 64-bit, NASM)

I'm trying to write a simple helloworld in assembler 64 on Mac with NASM. Every time I try to run it I'm getting this error:

Illegal instruction: 4

Here is my code:

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

I'm compiling with:

nasm -f macho64 HelloWorld.asm

And I'm linking with:

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

Any help is highly appreciated.

Let's start with the most important thing:

On Mac OSX, system calls are preceded by an 0x2000###, so for an exit it would 0x2000001.

Next, we need to use the correct registers to pass arguments.

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.

So bringing this together, a fixed version of your code is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM