Assembly Hello World on Mac

31 Aug 2019


brew install nasm

Hello World

Create a file hello_world.asm

global start

section .text

	mov		rax, 0x2000004 ; write
	mov 	rdi, 1 ; stdout
	mov		rsi, msg
	mov		rdx, msg.len

  mov 	rax, 0x2000001 ; exit
  mov		rdi, 0

section .data

msg:	db	"Hello, world!", 10
.len: equ	$ - msg

Then run: nasm -f macho64 hello_world.asm to output a file hello_world.o

Then link the file: ld -macosx_version_min 10.7.0 -lSystem -o hello_world hello_worl.o to output the binary file hello_world

Run the file: ./hello_world


Another Hello World

Create a hello.asm file

; ----------------------------------------------------------------------------------------
; Writes "Hello, World" to the console using only system calls. Runs on 64-bit macOS only.
; To assemble and run:
;     nasm -fmacho64 hello.asm && ld hello.o && ./a.out
; ----------------------------------------------------------------------------------------

          global start

          section   .text
start:    mov       rax, 0x02000004       ; system call for write
          mov       rdi, 1                ; file handle 1 is stdout
          mov       rsi, message          ; address of string to output
          mov       rdx, 13               ; number of types
          syscall                         ; invoke operating system to do the write
          mov       rax, 0x02000001       ; system call for exit
          xor       rdi, rdi              ; exit code 0
          syscall                         ; invoke operating system to exist

          section   .data
message:  db        "Hello, World", 10    ; note the newline at the end

Run: nasm -fmacho64 hello.asm to get hello.o

Run: ld -macosx_version_min 10.7.0 -lSystem hello.o to get binary filea

Run: ./a to get “Hello, World”



Generally, you put code in .text section, put constant data in .data section.