Skip to content

Instantly share code, notes, and snippets.

@hawkinsw
Created July 9, 2024 20:22
Show Gist options
  • Save hawkinsw/6fff79043c59048ddae7ed1f58974bbf to your computer and use it in GitHub Desktop.
Save hawkinsw/6fff79043c59048ddae7ed1f58974bbf to your computer and use it in GitHub Desktop.
Annotated Hello, World Program in Assembly
; To build and execute this program on Linux, you can use:
; nasm -f elf32 hello.S -o hello.o
; ld -m elf_i386 hello.o -o hello
section .data
hello db 'Hello, World.', 0
section .text
global _main
_main:
; In C, we could write a Hello, World program as
; write(1, hello, 13);
; write is a system call (sys_write). You can read more
; about how it works by reading its "man page":
; https://linux.die.net/man/3/write
; Because we are _not_ in C, we have to do the compiler's
; work ourselves.
;
; The value of the first parameter goes in ebx:
mov ebx, 1 ; the always-available file descriptor for stdout (the console)
; The value of the second parameter goes in ecx:
mov ecx, hello ; set the address of the string "Hello, World.\n" into ecx
; The value of the third parameter goes in edx:
mov edx, 13 ; set the length of the string "Hello, World.\0" into edx
; How did we know which registers to fill?
; https://github.com/torvalds/linux/blob/v3.13/arch/x86/ia32/ia32entry.S#L378-L397
;
; Ultimately there is only a generic mechanism to tell the Kernel
; that we want to execute a system call. We will need to set some
; specific information to tell the Kernel _which_ system call
; we want to execute. In order to do that, we set the system call
; number in eax:
mov eax, 4 ; https://github.com/torvalds/linux/blob/d8ec26d7f8287f5788a494f56e8814210f0e64be/arch/x86/syscalls/syscall_32.tbl#L13
; Now that everything is set up, we will signal to the Kernel that
; we want to execute a system call. When the Kernel answers that signal,
; it knows to look in the eax register to see which system call we want to execute.
int 0x80 ;
; When we are here, the system call has been performed and our string is on
; the screen. All that's left to do is stop the program. Good news for us:
; stopping the program is just another system call! Take a stab at deciphering
; how the following lines of assembly code make the program exit:
mov eax, 1
xor ebx, ebx ; Note: This is just a _fancy_ way of setting the ebx register to 0
int 0x80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment