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

I am trying to write a simple helloworld in 64 assembler on a Mac with NASM. Every time I try to run it I get 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 am compiling with:

nasm -f macho64 HelloWorld.asm

      

And I am linking with:

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

      

Any help is appreciated.

+3


source to share


1 answer


Let's start with the most important thing:

On Mac OSX, system calls are preceded by 0x2000 ###, so it will be 0x2000001 to exit.

Then 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.

      

Thus, when sharing a fixed version of your code:

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

      

+2


source







All Articles