I'm learning assembly with the arm64 architecture on my M2 mac. I my hello world code (in file hello.s). hello.s (btw: I removed the comments for readability):
.global _start
.align 4
_start:
mov X0, #1
adr X1, msg
mov X2, #13
mov X16, #4
svc #0x80
mov X0, #0
mov X16, #1
svc #0x80
.data
msg: .ascii "Hello World!\n"
Hello.s assembles perfectly using as hello.s -o hello.o
I also tried retyping it as as -arch arm64 -o hello.o hello.s
and it returns an object file named hello.o. Then I link the object file as so:
ld -o hello hello.o -lSystem -syslibroot
xcrun -sdk macosx --show-sdk-path -e _start -arch arm64
It returns an executable file: hello
But the error occurs when I the run the file with ./hello
I get the error message:
zsh: invalid system call ./hello
I have tried changing the code in the assembly file as I saw in a Youtube video to
.global _start
_start:
mov x0, #1
ldr x1, =msg
mov x2, #14
mov x8, #64
svc #0
mov x0, #0
mov x8, #93
svc #0
.data
msg: .ascii"Hello, world!\n"
This still assembled and linked successfully, but gave the same runtime error.
I also tried changing the linking call, but that didn't do anything to fix it (I didn't try every linking possible, mostly because I'm new to assembly and don't understand all of the linking, so this still might be the error).
Please inform me if you need more information.
edit:
I recently tried to assemble in a different shell and I got that I had a Bad system call: 12
from sh-3.2$ ./hello
command
HelloWorld.c:
.global _start
.align 4
_start:
mov X0, #1
adrp X1, helloworld@page
add X1, X1, helloworld@pageoff
mov X2, #13
mov X16, #4
svc #0x80
mov X0, #0
mov X16, #1
svc #0x80
.data
helloworld:
.ascii "Hello World!\n"
Followed by:
cc -c HelloWorld.s
ld -o HelloWorld HelloWorld.o -e _start
./HelloWorld
It is poorly documented, but ldr <reg>,=<label>
doesn't work on MacOS when the label is in a different section of code. You must use adrp/add.