Assembly (x86-64) Documentation
Talk to the CPU directly — registers, instructions, memory and how high-level code really runs.
Assembly language is a human-readable form of machine code — each line maps to (almost) one CPU instruction. You work directly with registers, memory addresses and the stack. You rarely write whole programs in assembly today, but learning it explains how C/C++ code really runs, how function calls and pointers work, and it's essential for operating systems, compilers, embedded devices, performance tuning, reverse engineering and security.
This page uses x86-64 with NASM syntax (Intel order: destination, source) on Linux.
1. Introduction & Setup
- Linux / WSL:
sudo apt install nasm gcc gdb. - macOS:
brew install nasm(macOS uses different system call numbers — use WSL/Linux or Docker for these examples). - Windows: use WSL (Ubuntu). Online: godbolt.org shows the assembly your C code compiles to.
Assemble and link:
nasm -f elf64 hello.asm -o hello.o # assemble to an object file
ld hello.o -o hello # link into an executable
./hello
; hello.asm — print a message using Linux system calls
section .data
msg db "Hello, Codify!", 10 ; 10 = newline
msg_len equ $ - msg ; length computed by the assembler
section .text
global _start
_start:
mov rax, 1 ; syscall number 1 = write
mov rdi, 1 ; file descriptor 1 = stdout
mov rsi, msg ; address of the text
mov rdx, msg_len ; number of bytes
syscall
mov rax, 60 ; syscall number 60 = exit
xor rdi, rdi ; exit code 0
syscall
Output:
Hello, Codify!
⚠️ Common error:
Segmentation faultright after printing — the program didn't callexit, so the CPU kept executing whatever bytes came next.
2. Basic Syntax & Program Structure
label: instruction operands ; comment
_start: mov rax, 1 ; rax = 1
- Sections:
.data(initialised variables),.bss(reserved, zeroed space),.text(code). - Directives:
db/dw/dd/dqdefine bytes / words (2 bytes) / doublewords (4) / quadwords (8);resb/resqreserve space;equdefines a constant;globalexports a symbol. - Operands: registers (
rax), immediates (42), memory ([rbx],[rbx + 8],[arr + rcx*4]). $is the current address — handy for computing lengths.
section .data
count dq 10 ; 64-bit integer
letter db 'A' ; one byte
nums dd 1, 2, 3, 4 ; four 32-bit integers
section .bss
buffer resb 64 ; 64 uninitialised bytes
section .text
global _start
_start:
mov rax, [count] ; load the value at address "count"
add rax, 5 ; rax = 15
mov [count], rax ; store it back
mov rax, 60
mov rdi, [count] ; exit code 15 (check with: echo $?)
syscall
Output (./prog; echo $?):
15
⚠️ Common error:
mov rax, countloads the address ofcount;mov rax, [count]loads the value stored there.
3. Registers & Data Sizes
x86-64 has sixteen 64-bit general-purpose registers. Smaller parts of each can be used by name:
| 64-bit | 32-bit | 16-bit | 8-bit | Common use |
|---|---|---|---|---|
rax |
eax |
ax |
al |
return value, syscall number |
rbx |
ebx |
bx |
bl |
general (callee-saved) |
rcx |
ecx |
cx |
cl |
counter, 4th argument |
rdx |
edx |
dx |
dl |
3rd argument, mul/div high part |
rsi |
esi |
si |
sil |
2nd argument, source |
rdi |
edi |
di |
dil |
1st argument, destination |
rsp |
stack pointer | |||
rbp |
base/frame pointer | |||
r8–r15 |
r8d |
r8w |
r8b |
more arguments / general |
Special registers: rip (instruction pointer — address of the next instruction) and rflags (status flags: ZF zero, SF sign, CF carry, OF overflow).
mov rax, 0x1122334455667788
mov eax, 0xAABBCCDD ; writing a 32-bit register ZEROES the upper 32 bits → rax = 0x00000000AABBCCDD
mov al, 0x01 ; writing 8 bits leaves the rest unchanged → rax = 0x00000000AABBCC01
movzx ecx, byte [letter] ; zero-extend a byte into a 32-bit register
movsx rdx, word [value] ; sign-extend a 16-bit value into 64 bits
⚠️ Common error:
operation size not specified—mov [x], 5is ambiguous. Say the size:mov qword [x], 5ormov byte [x], 5.
4. Instructions & Arithmetic
| Instruction | Effect |
|---|---|
mov dst, src |
copy |
add / sub dst, src |
dst = dst ± src (sets flags) |
inc / dec dst |
±1 |
imul dst, src |
signed multiply |
idiv src |
signed divide rdx:rax by src → quotient in rax, remainder in rdx |
neg dst |
dst = −dst |
and / or / xor / not |
bitwise operations |
shl / shr / sar |
shift left / right (logical / arithmetic) |
lea dst, [expr] |
compute an address (also handy maths: lea rax, [rbx + rbx*2] = rbx × 3) |
cmp a, b / test a, b |
set flags as if a − b / a & b (results discarded) |
mov rax, 17
mov rbx, 5
cqo ; sign-extend rax into rdx:rax before signed division
idiv rbx ; rax = 3 (quotient), rdx = 2 (remainder)
mov rcx, 6
imul rcx, rcx, 7 ; rcx = 42
lea rdx, [rcx + rcx*4] ; rdx = 42 * 5 = 210
shl rcx, 1 ; rcx = 84 (multiply by 2)
xor rbx, rbx ; rbx = 0 (fast way to clear a register)
⚠️ Common error:
idivwith garbage inrdxgives wrong results or a crash (Floating point exception). Usecqo(signed) orxor rdx, rdx(unsigneddiv) first.
5. Conditionals: Flags & Jumps
There is no if — you compare, then jump based on flags.
| Jump | Condition (after cmp a, b) |
|---|---|
je / jne |
a == b / a != b |
jg / jge / jl / jle |
signed > / ≥ / < / ≤ |
ja / jae / jb / jbe |
unsigned > / ≥ / < / ≤ |
jz / jnz |
result zero / not zero |
jmp |
always |
; C: if (marks >= 75) grade = 'B'; else grade = 'C';
mov rax, [marks]
cmp rax, 75
jl .grade_c ; jump if marks < 75
mov byte [grade], 'B'
jmp .done
.grade_c:
mov byte [grade], 'C'
.done:
Conditional move avoids a jump (faster when branches are unpredictable):
; rax = max(rax, rbx)
cmp rax, rbx
cmovl rax, rbx ; if rax < rbx then rax = rbx
⚠️ Common error: using
jg/jl(signed) for unsigned values like sizes and addresses — useja/jb.
6. Loops
; sum = 1 + 2 + ... + 10, then exit with the sum as the exit code
section .text
global _start
_start:
xor rax, rax ; sum = 0
mov rcx, 1 ; i = 1
.loop:
add rax, rcx ; sum += i
inc rcx ; i++
cmp rcx, 10
jle .loop ; while (i <= 10)
mov rdi, rax ; exit code = 55
mov rax, 60
syscall
Output (./sum; echo $?):
55
Looping over an array of 32-bit integers:
section .data
nums dd 4, 8, 15, 16, 23, 42
count equ ($ - nums) / 4 ; 6 elements
section .text
global _start
_start:
xor eax, eax ; max = 0
xor ecx, ecx ; index = 0
.next:
mov edx, [nums + rcx*4] ; scaled index addressing
cmp edx, eax
jle .skip
mov eax, edx ; new max
.skip:
inc ecx
cmp ecx, count
jl .next
mov edi, eax ; exit code = 42
mov eax, 60
syscall
42
7. Functions & the Stack
The stack grows downward; rsp points to its top. push stores (rsp −= 8), pop loads (rsp += 8). call pushes the return address and jumps; ret pops it and returns.
System V AMD64 calling convention (Linux/macOS):
- Integer/pointer arguments:
rdi, rsi, rdx, rcx, r8, r9(then the stack). - Return value:
rax. - Callee-saved (a function must preserve):
rbx, rbp, r12–r15. Others may be overwritten. rspmust be 16-byte aligned before acall.
; long square_sum(long a, long b) { return a*a + b*b; }
square_sum:
push rbp ; prologue: save the old frame pointer
mov rbp, rsp
mov rax, rdi
imul rax, rdi ; a*a
imul rsi, rsi ; b*b
add rax, rsi ; return value in rax
pop rbp ; epilogue
ret
_start:
mov rdi, 3
mov rsi, 4
call square_sum ; rax = 25
mov rdi, rax
mov rax, 60
syscall
Output (exit code):
25
Recursion uses the stack for each call's saved state:
; long fact(long n) { return n <= 1 ? 1 : n * fact(n - 1); }
fact:
cmp rdi, 1
jg .recurse
mov rax, 1
ret
.recurse:
push rdi ; save n (callee needs rdi for its own argument)
dec rdi
call fact ; rax = fact(n - 1)
pop rdi
imul rax, rdi ; rax = n * fact(n - 1)
ret
fact(5) returns 120.
⚠️ Common error: unbalanced
push/popbeforeret—retthen jumps to a wrong address and the program crashes.
8. Memory, Arrays & Strings
Addressing modes: [base + index*scale + displacement] where scale is 1, 2, 4 or 8.
section .data
text db "codify", 0 ; null-terminated string (like C)
section .text
global _start
; uppercase the string in place, then print it
_start:
lea rsi, [text]
.upper:
mov al, [rsi]
test al, al ; end of string?
jz .print
sub al, 32 ; 'a'..'z' → 'A'..'Z' (ASCII)
mov [rsi], al
inc rsi
jmp .upper
.print:
mov rdx, rsi
lea rsi, [text]
sub rdx, rsi ; length = end − start
mov rax, 1
mov rdi, 1
syscall
mov rax, 60
xor rdi, rdi
syscall
Output:
CODIFY
String instructions repeat with rep: rep movsb (copy rcx bytes from [rsi] to [rdi]), rep stosb (fill with al), repne scasb (search for al).
⚠️ Common error: forgetting a string's terminating
0(or its length) — code that searches for the end keeps reading random memory.
9. Calling C & Structs (The "OOP" Layer)
Assembly has no objects; structs are just offsets from a base address and methods are functions that receive the struct's address in rdi — exactly what C++ compiles this->field into.
; struct Point { long x; long y; } → x at offset 0, y at offset 8
section .data
p dq 3, 4
section .text
; long point_dot(struct Point *p) { return p->x * p->x + p->y * p->y; }
point_dot:
mov rax, [rdi] ; p->x
imul rax, rax
mov rcx, [rdi + 8] ; p->y
imul rcx, rcx
add rax, rcx
ret
Calling the C library (printf) — assemble and link with gcc:
; printf.asm build: nasm -f elf64 printf.asm && gcc -no-pie printf.o -o printf
extern printf
section .data
fmt db "x = %d, y = %d", 10, 0
section .text
global main
main:
push rbp ; keeps the stack 16-byte aligned for the call
lea rdi, [fmt] ; 1st argument: format string
mov esi, 3 ; 2nd argument
mov edx, 4 ; 3rd argument
xor eax, eax ; number of vector registers used (varargs)
call printf
pop rbp
xor eax, eax ; return 0 from main
ret
x = 3, y = 4
10. Advanced Concepts
- See what compilers generate:
gcc -O2 -S file.c -masm=intelor godbolt.org. Compare-O0and-O2to learn optimisation tricks (loop unrolling,leafor maths, branch-free code). - Debugging with GDB:
gdb ./prog, thenbreak _start,run,stepi(one instruction),info registers,x/8xb $rsp(examine memory),layout asm. - SIMD: SSE/AVX registers
xmm0–15/ymm0–15process 4–8 floats at once (addps,vmulps) — the basis of fast maths and media code. - Floating point: passed in
xmm0–xmm7under System V (movsd,addsd,cvtsi2sd). - Inline assembly in C:
asm volatile ("rdtsc" : "=a"(lo), "=d"(hi));. - Security: buffer overflows overwrite return addresses on the stack — protections include stack canaries, NX (non-executable stack) and ASLR.
- Other architectures: ARM64 (phones, Apple Silicon), RISC-V, and AVR (Arduino) follow the same ideas with different instructions.
11. Examples with Output
Example 1 — Exit code as a quick "print" for small numbers
; returns (7 * 6) as the exit code
global _start
section .text
_start:
mov rdi, 7
imul rdi, rdi, 6
mov rax, 60
syscall
$ ./answer; echo $?
42
Example 2 — Is a number even? (bit test)
; exit 1 if rdi is even, else 0
global _start
section .text
_start:
mov rdi, 1234
test rdi, 1 ; lowest bit set → odd
setz al ; al = 1 if ZF (even)
movzx rdi, al
mov rax, 60
syscall
$ ./even; echo $?
1
Example 3 — Count characters until the null terminator (strlen)
; size_t my_strlen(const char *s)
my_strlen:
xor rax, rax
.loop:
cmp byte [rdi + rax], 0
je .done
inc rax
jmp .loop
.done:
ret
my_strlen("codify") → 6
12. Practice Problems
- Print your name using the
writesystem call. - Exit with the sum of the numbers from 1 to 20 as the exit code (it's 210).
- Find the minimum of an array of 64-bit integers.
- Reverse a string in place, then print it.
- Write
long power(long base, long exp)with a loop and call it from_start. - Write a recursive Fibonacci function following the calling convention.
- Call
printffrom assembly to print a table of squares from 1 to 10. - Compile a small C function with
-O0and-O2, read both outputs and explain the differences.
13. Interview Questions
1. What is the difference between assembly and machine code? Machine code is raw binary instructions; assembly is its human-readable text form, translated 1:1 by an assembler.
2. What do the stack pointer and instruction pointer hold?
rsp holds the address of the top of the stack; rip holds the address of the next instruction to execute.
3. What happens during call and ret?
call pushes the return address and jumps to the function; ret pops that address into rip.
4. What is a calling convention?
Rules for passing arguments, returning values and which registers must be preserved — e.g. System V passes the first six integer arguments in rdi, rsi, rdx, rcx, r8, r9.
5. mov vs lea?
mov reg, [addr] loads the value at a memory address; lea reg, [addr] computes the address itself without touching memory.
6. What are flags used for?
Instructions like cmp, add and test set flags (zero, sign, carry, overflow) that conditional jumps and moves read.
7. Signed vs unsigned comparisons?
After cmp, use jg/jl for signed values and ja/jb for unsigned values — the bit patterns are compared differently.
8. What is a system call?
A request to the operating system kernel (write a file, exit, allocate memory) made with the syscall instruction and a number in rax.
9. Why does stack alignment matter?
The ABI requires rsp to be 16-byte aligned at calls; SIMD instructions and library functions can crash if it isn't.
10. How does a buffer overflow attack work? Writing past a stack buffer can overwrite the saved return address, redirecting execution; canaries, NX and ASLR mitigate it.
14. Cheat Sheet & References
Build and debug
# assemble, link, run, debug
nasm -f elf64 prog.asm -o prog.o
ld prog.o -o prog
./prog; echo $?
gdb ./prog
objdump -d -M intel prog
Data and sections
; data definitions
section .data
msg db "Hi", 10, 0
n dq 42
arr dd 1, 2, 3
len equ $ - msg
section .bss
buf resb 128
Core instructions
mov rax, rbx
mov rax, [rbx + 8]
lea rax, [rbx + rcx*4]
add rax, 5
sub rax, rbx
imul rax, rbx
cqo
idiv rbx
and rax, 0xFF
xor rax, rax
shl rax, 2
Control flow
cmp rax, rbx
je equal
jne different
jg bigger
jl smaller
ja above
jb below
jmp somewhere
cmovl rax, rbx
Stack and functions
push rbx
pop rbx
call func
ret
push rbp
mov rbp, rsp
sub rsp, 16
leave
Linux system calls
; write(1, msg, len)
mov rax, 1
mov rdi, 1
mov rsi, msg
mov rdx, len
syscall
; exit(0)
mov rax, 60
xor rdi, rdi
syscall
Official documentation