Assembly in macOS: Hello World

Home PDF

Hello World

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
	.section	__TEXT,__text,regular,pure_instructions
	.build_version macos, 15, 0	sdk_version 15, 2
	.globl	_main                           ; -- Begin function main
	.p2align	2
_main:                                  ; @main
	.cfi_startproc
; %bb.0:
	sub	sp, sp, #32
	stp	x29, x30, [sp, #16]             ; 16-byte Folded Spill
	add	x29, sp, #16
	.cfi_def_cfa w29, 16
	.cfi_offset w30, -8
	.cfi_offset w29, -16
	mov	w8, #0                          ; =0x0
	str	w8, [sp, #8]                    ; 4-byte Folded Spill
	stur	wzr, [x29, #-4]
	adrp	x0, l_.str@PAGE
	add	x0, x0, l_.str@PAGEOFF
	bl	_printf
	ldr	w0, [sp, #8]                    ; 4-byte Folded Reload
	ldp	x29, x30, [sp, #16]             ; 16-byte Folded Reload
	add	sp, sp, #32
	ret
	.cfi_endproc
                                        ; -- End function
	.section	__TEXT,__cstring,cstring_literals
l_.str:                                 ; @.str
	.asciz	"Hello, World!\n"

.subsections_via_symbols
gcc -S hello.c -o hello.s
gcc -c hello.s -o hello.o
gcc hello.o -o hello
./hello
hexdump -C hello.o

Experiment

This as code creates a “Hello, World!” program. It uses system calls to write the message to the console and then exit. The .text section holds the executable instructions, starting at _start. It first sets up the sys_write call (printing to stdout) and then the sys_exit call (exiting cleanly). The .data section stores the message itself and calculates its length.

.global _start
.text

_start:
    // Write "Hello, World!" to stdout
    mov x8, #64             // syscall number for write (sys_write)
    mov x0, #1              // file descriptor 1 (stdout)
    ldr x1, =msg            // address of the message
    mov x2, #14             // length of the message
    svc #0                  // invoke syscall

    // Exit the program
    mov x8, #93             // syscall number for exit (sys_exit)
    mov x0, #0              // exit code 0
    svc #0                  // invoke syscall

.data
msg:
    .asciz "Hello, World!\n"
as -o hello.o hello.s

% clang -o hello hello.o -nostdlib -e _start -Wl,-platform_version,macos,15.0,15.0 -arch arm64

% ./hello
zsh: invalid system call  ./hello

Back 2025.02.22 Donate