Last active
May 6, 2024 01:13
-
-
Save zeusdeux/bb5b5b0aac1a39d4f9cec0d4f9a44ffb to your computer and use it in GitHub Desktop.
M1 macOS ARM64 assembly (Darwin Kernel syscalls) — Hello World
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.global _start | |
.align 2 | |
.text | |
;;; COMPILE and RUN CMD: | |
;;; as -o hello.o hello.s && ld -macos_version_min 14.0.0 -o hello.bin hello.o -e _start -arch arm64 && ./hello.bin | |
;;; | |
;;; EXTRACT FLAT (PURE) BINARY: | |
;;; 1. otool -l hello.bin and search for sectname __text > offset field (it's in decimal not hex btw) | |
;;; 1a. Take the offset, convert to hex and verify code starts there in the hexdump view of the compiled binary | |
;;; 2. dd if=hello.bin of=hello_flat.bin ibs=<offset> skip=1 | |
;;; | |
;;; syscalls from https://opensource.apple.com/source/xnu/xnu-1504.3.12/bsd/kern/syscalls.master | |
;;; search for function such as "exit(" for exit syscall or "write(int fd" for write syscall | |
;;; More here: https://filippo.io/making-system-calls-from-assembly-in-mac-os-x/ | |
;;; And here: https://stackoverflow.com/a/34191324 | |
;;; And here: https://stackoverflow.com/questions/56985859/ios-arm64-syscalls | |
_start: | |
mov x16, #4 ; 4 -> write syscall | |
mov x0, #1 ; 1 -> stdout | |
adrp x1, msg@PAGE ; or adr x1, msg if NOT using .text and .data section markers from https://stackoverflow.com/a/65354324 | |
add x1, x1, msg@PAGEOFF ; also from https://stackoverflow.com/a/65354324 and https://mariokartwii.com/armv8/ch20.html (this is arm64 on linux though hence the :lo12: and not @PAGEOFF aka page offset) | |
mov x2, 14 ; length of msg aka "Hello, World!\n" | |
svc 0x80 ; syscall SWI_SYSCALL found in /Library/Developer/CommandLineTools/SDKs/MacOSX13.3.sdk/usr/include/mach/arm/vm_param.h and used in /Library/Developer/CommandLineTools/SDKs/MacOSX13.3.sdk/usr/include/mach/arm/syscall_sw.h | |
mov x16, #1 ; 1 -> exit syscall | |
mov x0, #69 ; exit code is 69 | |
svc 0x80 | |
ret | |
.data | |
msg: .ascii "Hello, World!\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment