How a Computer Runs Code
Foundations · Assembly 1
Why Assembly
Every language you have used is translated, in the end, into machine code: numbers the processor executes directly. Assembly is a human-readable spelling of those numbers, one line per instruction. You learn it not to write big programs but to understand what the machine actually does: why a loop is slow, what a pointer is, how a function call works, and what a compiler did with your code.
- x86-64, the 64-bit architecture in nearly every laptop, desktop and server (Intel and AMD).
- Linux and the NASM assembler with Intel syntax:
mov rax, 5means “put 5 in rax”, destination first. - The System V calling convention, which is how C and assembly talk to each other on Linux and macOS.
- A tab at the end on AT&T syntax, which is what
gcc -Sand most textbooks print, so you can read both.
- A Linux machine, a virtual machine, WSL on Windows, or an online assembler sandbox.
nasm(the assembler),ldorgcc(the linker) andgdb(the debugger):sudo apt install nasm gcc gdb.- Any text editor. Save files as
.asm.
The Pieces of the Machine
| Part | What it is | In assembly |
|---|---|---|
| CPU (processor) | Executes one instruction after another, billions per second | Your code is the list it executes |
| Registers | A handful of tiny, extremely fast storage slots inside the CPU, 64 bits each | rax, rbx, rcx, … the names you use most |
| Memory (RAM) | Billions of numbered bytes; slow compared with registers | [address]: square brackets mean “the contents at” |
| Instruction pointer | The register rip: the address of the next instruction | Jumps and calls change it; you never write to it directly |
| Flags | A register of yes/no bits set by the last arithmetic: was it zero, negative, did it overflow | What conditional jumps look at |
| Stack | A region of memory that grows and shrinks at one end, tracked by rsp | push, pop, call, ret |
- Fetch — read the instruction bytes at
rip - Decode — work out which operation and which operands
- Execute — do it: move data, add, compare, jump
- Advance —
ripmoves to the next instruction, unless this one was a jump
hello.asm— what you writenasm -f elf64 hello.asm— the assembler turns it into an object filehello.oof machine code with unresolved addressesld hello.o -o hello— the linker fixes the addresses and produces the executable./hello— the operating system loads it into memory and setsripto_start
What an Instruction Looks Like
Anatomy of a line
; label: mnemonic destination, source ; comment
loop_top: add rax, rbx ; rax = rax + rbx
mov rcx, [rdi + 8] ; rcx = the 8 bytes in memory at address rdi + 8
cmp rax, 100 ; set the flags from rax - 100
jl loop_top ; jump back if rax < 100 (signed)- Mnemonic: the operation, such as
mov,add,cmp,jmp. About thirty cover a first course. - Operands: at most two for most instructions, destination first in Intel syntax. At most one may be a memory operand.
- Label: a name for an address, ending in a colon. Jumps and calls use labels; the assembler turns them into numbers.
- Comment: from
;to the end of the line. Assembly needs more comments than any other language: say what the register means, not what the instruction does. - One instruction does one small thing.
x = a + bis two or three instructions; aforloop is five or six.
Assembly has no types and no safety net. A register is just 64 bits; whether they are a number, an address or four characters is up to you. Nothing stops you adding an address to a letter or jumping into data. The assembler checks spelling, not meaning.
Number Systems: Binary, Hex and Two’s Complement
Foundations · Assembly 1
Binary and Hexadecimal
The machine stores everything as bits. Writing 64 bits in binary is unreadable, so assembly programmers use hexadecimal: one hex digit per four bits, two per byte. Learn to convert between the three without thinking.
| Decimal | Binary | Hex | Decimal | Binary | Hex |
|---|---|---|---|---|---|
| 0 | 0000 | 0 | 8 | 1000 | 8 |
| 1 | 0001 | 1 | 9 | 1001 | 9 |
| 2 | 0010 | 2 | 10 | 1010 | A |
| 3 | 0011 | 3 | 11 | 1011 | B |
| 4 | 0100 | 4 | 12 | 1100 | C |
| 5 | 0101 | 5 | 13 | 1101 | D |
| 6 | 0110 | 6 | 14 | 1110 | E |
| 7 | 0111 | 7 | 15 | 1111 | F |
Converting
- Binary → hex: group into fours from the right, convert each group.
1011 0110→B6. - Hex → decimal: each digit is a power of 16.
0x1F= 1×16 + 15 = 31. - Decimal → binary: divide by 2 repeatedly, read the remainders bottom up. 13 → 1101.
- Powers of two to know by heart: 28 = 256, 210 = 1024, 216 = 65,536, 232 ≈ 4.29 billion.
How NASM writes them
mov rax, 255 ; decimal
mov rax, 0xFF ; hex, C style
mov rax, 0FFh ; hex, old style (must start with a digit)
mov rax, 0b1111_1111 ; binary (underscores allowed)
mov rax, 'A' ; a character: its code, 65
mov rax, -1 ; all 64 bits set: 0xFFFFFFFFFFFFFFFFSizes and Two’s Complement
| Size | Bits | Unsigned range | Signed range | NASM name |
|---|---|---|---|---|
| byte | 8 | 0 to 255 | -128 to 127 | byte / db |
| word | 16 | 0 to 65,535 | -32,768 to 32,767 | word / dw |
| double word | 32 | 0 to about 4.29 billion | ± about 2.15 billion | dword / dd |
| quad word | 64 | 0 to about 1.8 × 1019 | ± about 9.2 × 1018 | qword / dq |
Negative numbers use two’s complement: to negate, flip every bit and add 1. The top bit is the sign bit. The same bits mean different numbers depending on whether you read them as signed or unsigned; the hardware does not know which you meant, so it keeps flags for both.
Negating by hand (8 bits)
5 = 0000 0101
flip = 1111 1010
add 1 = 1111 1011 = -5 (= 251 if read as unsigned)
-1 = 1111 1111 (all ones, in every size)
-128 = 1000 0000 (the most negative value has no positive partner)Why it works
- Addition is the same circuit for signed and unsigned: 5 + (-5) = 0000 0101 + 1111 1011 = 1 0000 0000, and the carry out is dropped, leaving 0.
- Subtraction is adding the negation. The CPU has one adder.
- Sign extension: to widen -5 from 8 to 16 bits, copy the sign bit:
1111 1111 1111 1011.movsxdoes this;movzxfills with zeros instead. - Overflow: 127 + 1 in 8 bits is 1000 0000 = -128. The hardware sets the overflow flag (signed) or carry flag (unsigned) and carries on.
Bits, Bytes and Addresses
- Memory is addressed by byte. A qword at address 1000 occupies bytes 1000 through 1007; the next qword starts at 1008.
- x86 is little-endian: the least significant byte comes first in memory. The qword
0x0000000000000102at address 1000 is stored as bytes02 01 00 00 00 00 00 00. Reading the first byte alone gives 2. - An address is itself a 64-bit number and fits in a register. “Pointer” is just a name for a register or variable that holds an address.
- Characters are bytes:
'A'is 65,'a'is 97,'0'is 48, newline is 10.'a' - 'A'is 32, so clearing bit 5 uppercases a letter.
Signed or unsigned is your decision, instruction by instruction. cmp rax, rbx sets flags for both interpretations; jl (jump if less) reads the signed ones and jb (jump if below) the unsigned ones. Choosing the wrong one is the classic assembly bug, and it only shows up for values with the top bit set.
Registers, Memory and Addressing
Foundations · Assembly 1
The General-Purpose Registers
x86-64 has sixteen 64-bit general-purpose registers. Each can be used as a whole or in parts: the low 32, 16 or 8 bits have their own names, and writing the 32-bit part zeroes the upper 32 bits (writing the 16- or 8-bit part does not).
| 64-bit | 32-bit | 16-bit | 8-bit | Conventional use |
|---|---|---|---|---|
rax | eax | ax | al | Accumulator; return value; syscall number |
rbx | ebx | bx | bl | Callee-saved scratch |
rcx | ecx | cx | cl | Counter; 4th argument; shift count |
rdx | edx | dx | dl | 3rd argument; high half of multiply/divide |
rsi | esi | si | sil | 2nd argument; source index |
rdi | edi | di | dil | 1st argument; destination index |
rbp | ebp | bp | bpl | Frame pointer (base of the current stack frame) |
rsp | esp | sp | spl | Stack pointer: always the top of the stack |
r8 to r15 | r8d … | r8w … | r8b … | r8, r9 are the 5th and 6th arguments; the rest are scratch |
Parts of a register
mov rax, 0x1122334455667788
; rax = 1122334455667788
; eax = 55667788 (low 32 bits)
; ax = 7788 (low 16)
; al = 88 (low 8)
; ah = 77 (bits 8-15; only a, b, c, d have an h part)
mov eax, 1 ; rax is now 0000000000000001: the upper half is CLEARED
mov ax, 1 ; only the low 16 bits change; the rest keep their valueSpecial registers
| Register | Holds |
|---|---|
rip | Address of the next instruction |
rflags | The flags: ZF (zero), SF (sign), CF (carry), OF (overflow), and others |
xmm0 to xmm15 | Floating-point and vector values; xmm0 returns a double |
| Segment registers | Legacy; you will not touch them in a first course |
Memory Operands
Square brackets mean “the contents of memory at this address”. The address inside can combine a base register, an index register scaled by 1, 2, 4 or 8, and a constant. This one shape handles variables, arrays, structures and stack slots.
; general form: [base + index*scale + displacement]
mov rax, [rbx] ; the qword at the address in rbx
mov rax, [rbx + 8] ; 8 bytes further on: the next qword
mov rax, [rbx + rcx*8] ; element rcx of an array of qwords starting at rbx
mov eax, [rbx + rcx*4 + 16] ; element rcx of a dword array that starts 16 bytes into a structure
mov rax, [counter] ; a variable, by name (its address is a constant)
mov rax, [rel counter] ; the same, position-independent (needed when linking with gcc)Size matters
mov rax, [rbx] ; 8 bytes: the size comes from rax
mov al, [rbx] ; 1 byte: from al
mov [rbx], rax ; store 8 bytes
mov qword [rbx], 0 ; storing a constant: NASM must be TOLD the size
mov byte [rbx], 'A'
mov dword [rbx + 4], 7
movzx eax, byte [rbx] ; load a byte and zero-extend into eax
movsx rax, dword [rbx] ; load a dword and sign-extend into raxRules
- At most one operand may be in memory.
mov [a], [b]does not exist; go through a register. - When neither operand is a register the size is ambiguous and NASM demands
byte,word,dwordorqword:mov [rbx], 0stops witherror: operation size not specified. With a register operand the size is never ambiguous, and writing a size that disagrees with the register (mov qword [rbx], eax) iserror: invalid combination of opcode and operands. lea(load effective address) computes the address without reading memory:lea rax, [rbx + rcx*8]puts the address in rax. It is also a free three-operand add.- Reading memory is tens to hundreds of times slower than a register. Keep hot values in registers inside loops.
Where Things Live
| Section | Directive | Contents | Example |
|---|---|---|---|
.data | section .data | Initialized variables and constants | msg db "Hello", 10, count dq 0 |
.bss | section .bss | Uninitialized space, zero at start, costs nothing in the file | buffer resb 64, total resq 1 |
.text | section .text | The instructions | global _start and your code |
| Stack | none; managed by rsp | Return addresses, saved registers, local variables | push rbx, sub rsp, 32 |
| Registers | none | The values you are working on right now |
A variable name in NASM is an address. mov rax, count loads the address of count; mov rax, [count] loads its value. Forgetting the brackets is the second classic assembly bug.
Your First Program
Writing Programs · Assembly 1
Hello, World with System Calls
With no libraries at all, a program asks the operating system to do things through system calls: put a number in rax saying which service, the arguments in rdi, rsi, rdx, and execute syscall. Writing to the screen is call 1; exiting is call 60.
hello.asm
; hello.asm - prints a line and exits (Linux x86-64, NASM)
section .data
msg db "Hello, World!", 10 ; the text, then a newline (10)
msg_len equ $ - msg ; length = current address - start of msg
section .text
global _start ; the linker needs to see the entry point
_start:
mov rax, 1 ; syscall number 1 = write
mov rdi, 1 ; file descriptor 1 = standard output
mov rsi, msg ; address of the text
mov rdx, msg_len ; how many bytes
syscall
mov rax, 60 ; syscall number 60 = exit
xor edi, edi ; exit code 0 (xor a register with itself is the idiom for zero)
syscallAssemble, link, run
nasm -f elf64 hello.asm -o hello.o
ld hello.o -o hello
./hello
echo $? # the exit code: 0Hello, World!
0Read it
section .dataholds the bytes of the message;dbmeans “define bytes”.equdefines a constant at assembly time.$is “the address here”, so$ - msgis the length.global _startexports the label;ldstarts the program there.- Each
syscallis a request to the kernel. Nothing prints until the kernel does it. - Without the exit call the CPU would run off the end of your code into garbage and crash.
What the first mistakes look like
- Leave out the
exitsyscall: the text prints, thenSegmentation faultandecho $?shows 139 (128 + signal 11). The CPU kept executing past your last instruction. - Write
mov rsi, [msg]instead ofmov rsi, msg: the program prints nothing and exits normally. You passed the first eight letters of the message as an address; the kernel refused it and returned an error code inrax, which nothing checked. - Forget
global _start:ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000. It usually still works because your code happens to start there, but it is luck; export the label. - Forget the
, 10after the message: it prints, but the shell prompt appears on the same line.
| Linux syscall | rax | rdi | rsi | rdx | Returns in rax |
|---|---|---|---|---|---|
| read | 0 | fd (0 = keyboard) | buffer address | max bytes | bytes read, 0 at end of input |
| write | 1 | fd (1 = screen, 2 = errors) | text address | byte count | bytes written |
| exit | 60 | exit code | never returns |
Hello, World with the C Library
Most courses link with gcc instead, so you can call printf, scanf and friends. Then your entry point is main, and the C library handles starting up and exiting.
hello2.asm
; hello2.asm - the same program, calling printf
default rel ; use rip-relative addresses (required for modern gcc)
extern printf ; defined in the C library
section .data
fmt db "Hello, %s! You are %d.", 10, 0 ; printf wants a 0-terminated string
who db "World", 0
section .text
global main
main:
push rbp ; keep the stack 16-byte aligned for the call
mov rbp, rsp
lea rdi, [fmt] ; 1st argument: the format string
lea rsi, [who] ; 2nd argument: the %s
mov edx, 42 ; 3rd argument: the %d
xor eax, eax ; number of vector registers used = 0 (printf is variadic)
call printf
xor eax, eax ; return 0 from main
pop rbp
retnasm -f elf64 hello2.asm -o hello2.o
gcc -no-pie hello2.o -o hello2
./hello2Hello, World! You are 42.- C strings end with a 0 byte; the syscall version needed a length instead. Mixing the two conventions is a common bug.
lea rdi, [fmt]withdefault relloads the address relative torip, which is what position-independent executables need.mov rdi, fmtworks only with-no-pie.- Before any
call,rspmust be a multiple of 16. On entry tomainit is 8 off (the return address was pushed); onepush rbpfixes it. xor eax, eaxbefore a variadic function such asprintftells it how many floating-point arguments are in xmm registers. Forgetting it can crash.
The Shape of Every Source File
Template
default rel
extern printf, scanf, puts ; C functions you call
global main ; or _start if you link with ld
section .data ; initialized data
; name size value
fmt db "%d", 10, 0
total dq 0
section .bss ; zeroed space
buffer resb 256
section .text ; code
main:
push rbp
mov rbp, rsp
; ... your program ...
xor eax, eax
pop rbp
retHabits that save hours
- Comment the meaning of every register at the top of each routine:
; rdi = array, rsi = length, rax = running sum. - Assemble often. NASM’s messages name the line.
- Run under
gdbfrom the first day:gdb ./hello, thenbreak main,run,stepi,info registers,x/8xb &buffer. Watching registers change teaches more than any explanation. - A crash with Segmentation fault means a bad address: unbalanced
push/pop, a missingret, brackets where you meant none, or acallwith a misaligned stack.
Reading the assembler’s and linker’s messages
| Message | Cause | Fix |
|---|---|---|
error: symbol `done' not defined | A label is misspelled, or a .done local label is used from a different routine | Match the spelling; local labels belong to the nearest non-dot label above them |
error: parser: instruction expected | A typo in a mnemonic (mvo), or a label without its colon followed by an operand | Fix the spelling; every label ends in : |
error: invalid combination of opcode and operands | Operand sizes differ (add rax, ecx), two memory operands, a constant as destination (mov 5, rax), or idiv 10 with an immediate | Widen first, go through a register, swap the operands, put the divisor in a register |
error: operation size not specified | mov [rbx], 0: neither operand says how many bytes | mov qword [rbx], 0 |
warning: byte data exceeds bounds | x db 300: 300 does not fit in a byte; 44 (300 − 256) is stored | Use dw or larger |
ld: warning: cannot find entry symbol _start | You wrote main but linked with ld, or forgot global _start | ld needs _start; gcc needs main |
multiple definition of `_start' | You wrote _start and linked with gcc, which brings its own | Rename the entry point to main and return with ret |
undefined reference to `printf' | Called a C function but linked with ld | Link with gcc -no-pie file.o |
NASM reports the file and line before every message (hello.asm:12: error: ...) and keeps going, so fix the first error and re-assemble; later ones are often consequences of it.
The three ways a first program dies: the stack is misaligned at a call (printf crashes), a string is missing its terminating 0 (printf prints garbage), or you wrote mov rsi, [msg] and passed the first eight letters as the address.
Data Movement and Arithmetic
Writing Programs · Assembly 1
Moving Data
| Instruction | Does | Notes |
|---|---|---|
mov dst, src | Copies src to dst | Register, memory or immediate; not memory to memory; sizes must match |
movzx dst, src | Copies a smaller value and fills the top with zeros | Unsigned widening: movzx eax, byte [rsi] |
movsx dst, src | Copies a smaller value and fills the top with the sign bit | Signed widening; movsxd rax, ecx for 32 to 64 |
lea dst, [expr] | Puts the address expr in dst | No memory access; also a fast dst = base + index*scale + k |
xchg a, b | Swaps two operands | Rarely needed; use three movs |
push src / pop dst | Copies to / from the top of the stack and moves rsp by 8 | See The Stack |
mov rax, 10 ; rax = 10
mov rbx, rax ; rbx = 10
mov [total], rax ; store to memory
mov rcx, [total] ; load from memory
mov eax, [total] ; load only the low 4 bytes (and clear the top of rax)
lea rax, [rbx + rbx*2] ; rax = 3 * rbx, in one instruction, flags untouched
xor eax, eax ; rax = 0: shorter than mov rax, 0 and the idiom everyone usesAdd, Subtract and Friends
| Instruction | Does | Flags |
|---|---|---|
add dst, src | dst = dst + src | ZF, SF, CF, OF set from the result |
sub dst, src | dst = dst - src | Same; cmp is a sub that throws the result away |
inc dst / dec dst | dst ± 1 | Does not touch CF |
neg dst | dst = -dst (two’s complement) | |
adc / sbb | Add / subtract with the carry | For numbers wider than 64 bits |
C to assembly
; int x = a + b - 7; (a in rdi, b in rsi)
mov rax, rdi
add rax, rsi
sub rax, 7
; x += 5; count--; y = -y;
add qword [x], 5
dec qword [count]
neg rcxCommon mistakes
- The sizes of the two operands must agree:
add rax, ecxis rejected witherror: invalid combination of opcode and operands; widen first withmovsxd rcx, ecx. - An immediate (constant) is at most 32 bits for most instructions, sign-extended. Only
mov reg, imm64takes a full 64-bit constant;add rax, 0x100000000assembles withwarning: signed dword value exceeds boundsand adds the wrong number. Load the constant into a register withmovfirst. addandsubchange the destination and the flags;cmpchanges only the flags. Readingadd rax, rbxas “rax += rbx” keeps the operand order straight: the destination is on the left in every two-operand instruction.- Every arithmetic instruction overwrites the flags. Do the
cmpright before the jump that needs it.
Multiply and Divide
Multiplication is friendly; division is the awkward one. Signed division works on the 128-bit pair rdx:rax, so you must sign-extend rax into rdx first with cqo, or zero rdx for unsigned division. Forgetting this is the number one cause of wrong answers and “floating point exception” crashes.
Multiply
imul rax, rbx ; rax = rax * rbx (signed, low 64 bits)
imul rax, rbx, 10 ; rax = rbx * 10 (three operands)
imul rax, [count] ; rax = rax * memory
; unsigned full-width: mul rbx -> rdx:rax = rax * rbx
; multiply by constants without imul:
shl rax, 3 ; rax * 8
lea rax, [rax + rax*4] ; rax * 5Divide
; signed: quotient = rax / divisor, remainder in rdx
mov rax, [dividend]
cqo ; sign-extend rax into rdx (rdx:rax)
idiv rbx ; rax = quotient, rdx = remainder
; idiv by a constant is not allowed: put it in a register first
mov rcx, 10
idiv rcx
; unsigned: zero rdx instead
mov rax, [dividend]
xor edx, edx
div rbx| Instruction | Before | After | Use for |
|---|---|---|---|
cqo | rax | rdx:rax sign-extended | 64-bit signed division |
cdq | eax | edx:eax sign-extended | 32-bit signed division (idiv ecx) |
cdqe | eax | rax sign-extended | Widening a 32-bit int to 64 |
Dividing by zero, or a quotient that does not fit, raises an exception and kills the program. Check the divisor first. And remember idiv uses all of rdx:rax: a leftover value in rdx silently gives a huge wrong quotient or a crash.
The crash looks like this in the shell: Floating point exception (core dumped), and echo $? shows 136 (128 + signal 8, SIGFPE), even though no floating point was involved: the CPU raises the same “divide error” for integer division by zero and for a quotient too big for 64 bits. idiv 10 is a different failure, at assembly time: error: invalid combination of opcode and operands, because idiv takes no immediate operand.
A Worked Example: Average of Three
; average = (a + b + c) / 3 a, b, c are qwords in memory; result in rax, remainder in rdx
mov rax, [a]
add rax, [b]
add rax, [c]
cqo
mov rcx, 3
idiv rcx ; rax = average (truncated), rdx = remainder
mov [avg], rax; the same routine traced with a = 10, b = 20, c = 35
mov rax, [a] ; rax = 10
add rax, [b] ; rax = 30
add rax, [c] ; rax = 65
cqo ; rdx = 0: rax is positive, so the sign-extension is all zeros
mov rcx, 3 ; rcx = 3 (idiv needs the divisor in a register or memory)
idiv rcx ; rdx:rax = 65 divided by 3 -> rax = 21, rdx = 2
mov [avg], rax ; avg = 21
; with a = -101 instead: rax = -46, cqo makes rdx all ones (-1),
; idiv gives rax = -15, rdx = -1: the quotient truncates toward zero and
; the remainder takes the sign of the dividend, exactly like CTwo things to notice. add rax, [b] reads memory as the source; the size (8 bytes) comes from rax. And cqo must come after the sum is complete and before idiv: putting mov rcx, 3 between them is harmless, but any instruction that writes rdx there would corrupt the dividend.
Read a routine like this by annotating the register contents after every line in the margin. That habit is the whole skill of reading assembly.
Comparisons and Jumps
Writing Programs · Assembly 1
How Decisions Work
There is no if. A decision is two instructions: a compare that sets the flags, then a conditional jump that changes rip if the flags say so, and otherwise falls through to the next line. Everything higher-level is built from this.
cmp rax, rbx ; computes rax - rbx, keeps only the flags
je equal ; jump if the result was zero (rax == rbx)
; ... code for rax != rbx ...
jmp done ; unconditional: skip the other branch
equal:
; ... code for rax == rbx ...
done:After cmp a, b | Signed jump | Unsigned jump | Reads flags |
|---|---|---|---|
| a == b | je (jz) | je | ZF = 1 |
| a != b | jne (jnz) | jne | ZF = 0 |
| a < b | jl | jb | SF ≠ OF / CF = 1 |
| a ≤ b | jle | jbe | |
| a > b | jg | ja | |
| a ≥ b | jge | jae | SF = OF / CF = 0 |
Mnemonic: less and greater are signed; below and above are unsigned. Addresses, sizes and counts are unsigned; most arithmetic values are signed.
test, and Jumps Without a cmp
test for bits and zero
test rax, rax ; AND with itself: sets ZF if rax == 0, SF if negative
jz is_zero ; shorter and faster than cmp rax, 0
js is_negative
test al, 1 ; is the low bit set?
jnz is_odd
test rdi, rdi ; the idiom for "is this pointer null?"
je null_pointerFlags set by arithmetic
sub rcx, 1 ; the flags already describe rcx
jnz loop_top ; so no cmp is needed
dec rcx
jnz loop_top ; dec sets ZF too (but not CF)
add rax, rbx
jo overflow ; signed overflow happened
jc carried ; unsigned carry out| Other conditional jumps | Jump when |
|---|---|
js / jns | the result was negative / not negative (SF) |
jo / jno | signed overflow / no overflow (OF) |
jc / jnc | carry / no carry (CF); same as jb / jae |
jmp | always; also jmp rax or jmp [table + rcx*8] to a computed address |
Translating if, else and &&
if / else if / else
; if (x < 0) y = -1;
; else if (x == 0) y = 0;
; else y = 1; x in rdi, y in rax
cmp rdi, 0
jge not_negative
mov rax, -1
jmp done
not_negative:
jne positive
xor eax, eax
jmp done
positive:
mov rax, 1
done:Compound conditions: jump past the body
; if (x > 0 && x < 10) { body } x in rdi
cmp rdi, 0
jle skip ; first test false: skip
cmp rdi, 10
jge skip ; second test false: skip
; ... body ...
skip:
; if (x < 0 || x > 9) { body }
cmp rdi, 0
jl body ; first test true: go
cmp rdi, 9
jle skip ; both false: skip
body:
; ...
skip:Conditional moves: no branch at all
; max = (a > b) ? a : b a in rdi, b in rsi
mov rax, rsi
cmp rdi, rsi
cmovg rax, rdi ; move only if rdi > rsi (signed)
; setcc: a 0/1 result from the flags
cmp rdi, rsi
setl al ; al = 1 if rdi < rsi, else 0
movzx eax, al ; clear the rest of raxRules of thumb
- Write the condition, then jump when it is false to skip the body. That mirrors the C and keeps the code in order.
- The jump instruction must be the next flag-reading instruction after the
cmportest; anything arithmetic in between clobbers the flags.movandleaare safe. - Every path needs a way out: an
ifwithoutelsefalls through, anif/elseneeds thejmp doneor the first branch runs into the second. - Label names are free:
.loop,.donewith a leading dot are local to the nearest non-dot label, so you can reuse them in every routine.
Loops
Writing Programs · Assembly 1
A Loop Is a Backward Jump
A loop is a label, a body, and a conditional jump back to the label. The test can be at the top (a while) or at the bottom (a do-while). Compilers prefer the test at the bottom, with one jump per iteration instead of two.
| Instruction in the loops below | Does | Flags |
|---|---|---|
xor eax, eax | rax = 0 (writing eax clears the top half); the idiom for i = 0, sum = 0 | ZF = 1, CF = OF = 0 |
cmp rcx, rsi | Computes rcx − rsi and throws the result away; neither operand changes | Sets all of them, for the next jump |
jl, jge, jle, jg | Jump on a signed compare: less, greater-or-equal, … (jb, jae for unsigned counts and addresses) | Reads SF, OF, ZF |
inc rcx / dec rcx | rcx ± 1 | ZF, SF, OF, but not CF |
test rcx, rcx | AND of rcx with itself, result discarded: the shortest way to ask “is it zero?” | ZF = 1 if rcx == 0, SF = its sign bit |
jz / jnz | Jump if the last result was zero / not zero (same instructions as je / jne) | Reads ZF |
jmp .top | Always jump | None |
add rax, [rdi + rcx*8] | rax += element rcx of a qword array at rdi; the source may be memory, the size comes from rax | All |
call printf | Push the return address and jump; on return rax, rcx, rdx, rsi, rdi, r8 to r11 may hold anything | Anything |
while, test at the top
; while (i < n) { sum += a[i]; i++; } rdi = a, rsi = n, rcx = i, rax = sum
xor eax, eax
xor ecx, ecx
.top:
cmp rcx, rsi
jge .done ; exit when the condition fails
add rax, [rdi + rcx*8]
inc rcx
jmp .top
.done:The same loop, test at the bottom
xor eax, eax
xor ecx, ecx
cmp rcx, rsi
jge .done ; guard: skip entirely if n <= 0
.top:
add rax, [rdi + rcx*8]
inc rcx
cmp rcx, rsi
jl .top ; one jump per iteration
.done:Counting down to zero
; for (i = n; i > 0; i--) body rcx = i
mov rcx, rsi
test rcx, rcx
jz .done
.top:
; ... body (must preserve rcx) ...
dec rcx
jnz .top ; dec sets ZF: no cmp needed
.done:do-while
; do { x = read(); } while (x != 0);
.again:
call read_number ; result in rax
test rax, rax
jnz .againSetting up a loop, step by step
- 1. Write the C version as a comment above the code:
; while (i < n) { sum += a[i]; i++; }. You will check every instruction against it. - 2. Assign a register to every variable and write the map down:
; rdi = a, rsi = n, rcx = i, rax = sum. If the body contains acall, put the counter and the running total inrbx,r12tor15instead, because the callee may destroy the others. - 3. Initialize before the label:
xor eax, eaxfor the sum,xor ecx, ecxfor the counter. Nothing inside the loop may reset them. - 4. Guard the zero case if the body must not run when
nis 0:cmp rcx, rsi/jge .done(ortest rsi, rsi/jz .done) before the label. - 5. Label, body, step:
.top:, the work, theninc rcx(oradd rsi, 8if you walk a pointer). - 6. Compare and jump back with the condition for continuing:
cmp rcx, rsi/jl .topmeans “go again while i < n”. Nothing that changes flags may sit between thecmpand the jump. - 7. Trace n = 0, 1 and 2 on paper, writing the registers after every line. This catches the off-by-one (
jlversusjle) and a counter that is never stepped before you run anything.
Classic Loop Algorithms
Sum and maximum of an array
; rdi = address of qword array, rsi = count; returns max in rax
array_max:
mov rax, [rdi] ; start with the first element
mov rcx, 1
.top:
cmp rcx, rsi
jge .done
mov rdx, [rdi + rcx*8]
cmp rdx, rax
jle .next ; not bigger: skip
mov rax, rdx
.next:
inc rcx
jmp .top
.done:
retLength of a C string
; rdi = address of a 0-terminated string; returns length in rax
strlen:
xor eax, eax
.top:
cmp byte [rdi + rax], 0 ; the byte at position rax
je .done
inc rax
jmp .top
.done:
retLinear search
; rdi = array, rsi = count, rdx = target; returns index in rax or -1
find:
xor ecx, ecx
.top:
cmp rcx, rsi
jge .missing
cmp [rdi + rcx*8], rdx
je .found
inc rcx
jmp .top
.found:
mov rax, rcx
ret
.missing:
mov rax, -1
retNested loops: a multiplication table
; for (r = 1; r <= 3; r++) for (c = 1; c <= 4; c++) print(r*c)
mov r12, 1 ; r (callee-saved, survives the call)
.rows:
mov r13, 1 ; c
.cols:
mov rax, r12
imul rax, r13
mov rsi, rax
lea rdi, [fmt] ; "%4d"
xor eax, eax
call printf
inc r13
cmp r13, 4
jle .cols
; print newline, then
inc r12
cmp r12, 3
jle .rowsTraps
- The body clobbers the counter. A
callinside the loop may destroyrcx,rdx,rsi,rdiand every other caller-saved register. Keep the counter inrbx,r12tor15, or on the stack. - Off by one.
jleversusjlis the difference between<=and<. Trace n = 0 and n = 1 by hand. - Wrong signedness. A count compared with
jlworks until it exceeds 263; an index compared withjbtreats -1 as enormous. Pick deliberately. - Scale.
[rdi + rcx*8]for qwords,*4for dwords,*1for bytes. Using the wrong scale reads between elements. - The flags are stale. An
incoraddbetween thecmpand the jump changes what the jump sees. Put the compare last.
The loop instruction (decrement rcx, jump if not zero) exists, but it is slow on modern CPUs and compilers never emit it. Use dec rcx / jnz.
Memory, Arrays and Strings
Data and Procedures · Assembly 1
Defining Data
| Directive | Reserves | Example | Meaning |
|---|---|---|---|
db | 1 byte each | msg db "Hi", 10, 0 | The bytes 72, 105, 10, 0 |
dw | 2 bytes each | ports dw 80, 443 | Two 16-bit values |
dd | 4 bytes each | nums dd 1, 2, 3 | Three 32-bit ints (a C int array) |
dq | 8 bytes each | big dq 1 << 40, pi dq 3.14159 | 64-bit ints or doubles |
times n | repeats | zeros times 10 dq 0 | Ten qwords of 0 |
resb / resw / resd / resq | uninitialized, in .bss | buf resb 256 | 256 bytes, zero at start |
equ | nothing: a constant | N equ 100 | Replaced at assembly time |
section .data
scores dq 88, 92, 79, 95 ; an array of four qwords
count equ ($ - scores) / 8 ; 4, computed by the assembler
name db "Max", 0 ; a C string
grid times 3*4 dd 0 ; a 3 by 4 table of dwords
section .bss
input resb 128
total resq 1scoresis 32 bytes long;count equ ($ - scores) / 8divides that by the element size, so adding a fifth score changescountautomatically.$is the address at the point where it is written.grid times 3*4 dd 0is 12 dwords; the assembler evaluates3*4for you. There is no two-dimensional directive: the row and column arithmetic is yours (see Indexing Arrays).- A value that does not fit is a warning, not an error:
x db 300assembles withwarning: byte data exceeds boundsand stores 44, which is 300 − 256. Treat that warning as an error. pi dq 3.14159stores the 8 bytes of a double. Integer instructions such asaddwill happily operate on them and produce nonsense; floating point needsmovsd xmm0, [pi]and the SSE instructions, which are beyond this sheet.- Nothing in
.bssmay have a value;total resq 1reserves 8 zero bytes andtotal dq 0in.datadoes the same but takes 8 bytes in the executable file.
Indexing Arrays
The address of element i of an array is base + i × element size. The addressing mode does that multiplication for sizes 1, 2, 4 and 8, so an array access is one instruction. For other sizes (a structure of 24 bytes, say) multiply first with imul or lea.
By index
mov rax, [scores + rcx*8] ; scores[rcx] (qwords)
mov eax, [grid + rcx*4] ; grid[rcx] (dwords, flat)
movzx eax, byte [name + rcx] ; name[rcx] (bytes)
mov [scores + rcx*8], rax ; scores[rcx] = rax
; two-dimensional, row-major: grid[r][c] = base + (r*COLS + c)*4
mov rax, r8 ; r
imul rax, 4 ; COLS = 4
add rax, r9 ; r*COLS + c
mov eax, [grid + rax*4]By pointer
; walk an array with a moving address
lea rsi, [scores] ; rsi = &scores[0]
lea rdx, [scores + count*8] ; one past the end
xor eax, eax
.top:
cmp rsi, rdx
jae .done ; unsigned: addresses
add rax, [rsi]
add rsi, 8 ; next element
jmp .top
.done:Both styles are common. Index form keeps i around for other uses; pointer form saves an instruction per iteration. Compilers emit both.
Strings and Bytes
Upper-case a C string in place
; rdi = string
to_upper:
.top:
mov al, [rdi]
test al, al
jz .done ; the 0 terminator
cmp al, 'a'
jb .next
cmp al, 'z'
ja .next
and al, 0xDF ; clear bit 5: 'a' (0x61) -> 'A' (0x41)
mov [rdi], al
.next:
inc rdi
jmp .top
.done:
retDigits to a number (atoi)
; rdi = string of digits; returns value in rax
atoi:
xor eax, eax
.top:
movzx ecx, byte [rdi]
sub ecx, '0' ; '0'..'9' -> 0..9
cmp ecx, 9
ja .done ; unsigned: anything not a digit, including the 0 terminator (which went negative = huge)
imul rax, 10
add rax, rcx
inc rdi
jmp .top
.done:
retCopy a block of memory
; rdi = destination, rsi = source, rcx = byte count
rep movsb ; the one-instruction memcpy: see the note below
; the long way
.top:
test rcx, rcx
jz .done
mov al, [rsi]
mov [rdi], al
inc rsi
inc rdi
dec rcx
jmp .top
.done:Little-endian in practice
section .data
v dq 0x0102030405060708
mov al, [v] ; 0x08: the LOWEST byte is stored first
mov ax, [v] ; 0x0708
mov eax, [v] ; 0x05060708
mov rax, [v] ; 0x0102030405060708
; gdb: x/8xb &v prints 08 07 06 05 04 03 02 01rep movsb is two things: movsb copies the byte at [rsi] to [rdi] and adds 1 to both registers; the rep prefix repeats it rcx times, decrementing rcx to 0. The registers are fixed, which is why the long version above uses the same three. movsq copies 8 bytes at a time (and steps by 8); rep stosb fills rcx bytes at [rdi] with al, the one-instruction memset. The System V convention guarantees the direction flag is clear on entry to every function, so the pointers count upward.
No bounds, no terminator, no mercy. Writing past the end of buf overwrites whatever is next in memory, often the return address on the stack. A string without its 0 byte makes printf and your own loops run into the next variable. These two bugs are the origin of most security holes ever found.
The Stack and Procedures
Data and Procedures · Assembly 1
How the Stack Works
The stack is a region of memory that grows downward: push subtracts 8 from rsp and stores the value there; pop loads from [rsp] and adds 8. rsp always points at the most recently pushed item. It holds return addresses, saved registers and local variables, and it is why recursion works at all.
push rax ; rsp -= 8 ; [rsp] = rax
push rbx ; rsp -= 8 ; [rsp] = rbx (rax is now at [rsp + 8])
mov rcx, [rsp] ; peek at the top without popping
pop rbx ; rbx = [rsp] ; rsp += 8
pop rax ; rax = [rsp] ; rsp += 8 pops come out in REVERSE order
sub rsp, 32 ; reserve 32 bytes of local space (four qwords) in one go
mov [rsp], rax ; local 0
mov [rsp + 8], rbx ; local 1
add rsp, 32 ; give it backcall and ret
call square ; push the address of the NEXT instruction, then jump to square
; ... execution resumes here after ret ...
square: ; rdi = x ; returns x*x in rax
mov rax, rdi
imul rax, rdi
ret ; pop the return address into ripThe two rules
- Every push has a pop, and every
sub rsphas anadd rsp, before theret. Otherwiseretpops the wrong thing intoripand the program jumps into garbage. - Never write below rsp (at addresses less than rsp). That memory is not yours: a signal or a
callmay overwrite it at any moment. Reserve space first withsub rsp.
The Stack Frame
A stack frame is the part of the stack belonging to one call: the return address, the caller’s saved rbp, saved registers, and locals. Using rbp as a fixed frame pointer makes locals easy to address while rsp moves around; compilers often skip it, but it is the right way to learn.
The standard prologue and epilogue
my_function:
; prologue
push rbp ; save the caller's frame pointer
mov rbp, rsp ; this frame starts here
sub rsp, 16 ; two qword locals: [rbp - 8] and [rbp - 16]
push rbx ; save a callee-saved register we intend to use
; body: the locals and arguments by fixed offsets from rbp
mov [rbp - 8], rdi ; local a = first argument
mov rbx, [rbp - 8]
; [rbp + 8] is the return address
; [rbp + 16] is the first stack-passed argument (the 7th argument, if any)
; epilogue: undo everything in reverse
pop rbx
mov rsp, rbp ; discard the locals, however many
pop rbp
ret| Address | Holds | Who put it there |
|---|---|---|
[rbp + 16], [rbp + 24] … | Arguments 7, 8, … (only if there are more than six) | The caller, by pushing before call |
[rbp + 8] | The return address | call |
[rbp] | The caller’s saved rbp | push rbp |
[rbp - 8], [rbp - 16] … | Local variables | sub rsp, N |
below the locals, down to rsp | Saved callee-saved registers, temporary pushes | push |
leave is a one-instruction mov rsp, rbp / pop rbp. enter exists too but is slow; write the prologue out.
Recursion on the Stack
Factorial
; rdi = n ; returns n! in rax
factorial:
cmp rdi, 1
jg .recurse
mov rax, 1 ; base case
ret
.recurse:
push rdi ; save n: the recursive call will change rdi
dec rdi
call factorial ; rax = (n-1)!
pop rdi ; n is back
imul rax, rdi ; n * (n-1)!
retWhat the stack looks like during factorial(3)
higher addresses
...
return address into main
3 <- pushed by factorial(3)
return address into factorial
2 <- pushed by factorial(2)
return address into factorial <- rsp, inside factorial(1)
lower addresses
Each level keeps its own n safe on the stack while the deeper call runs.
Ten thousand levels deep, the stack (usually 8 MB) runs out: a segfault.- Anything you need after a
callmust be in a callee-saved register (rbx,rbp,r12tor15) or on the stack. Everything else may come back changed. - If you use a callee-saved register, you must push it at the start and pop it at the end of your routine, so your caller finds it intact.
- Match the pushes and pops in the same order reversed. Drawing the stack on paper for each routine is not cheating; it is the method.
Symptoms of a broken stack: ret jumps somewhere random (segfault at a weird address), a variable changes “by itself” after a call, or a recursive routine returns the wrong answer only for n > 1. Check that pushes and pops balance on every path, including early returns.
Calling Conventions: Talking to C
Data and Procedures · Assembly 1
The System V AMD64 Convention
A calling convention is the agreement about where arguments go, where the result comes back, who saves which registers and how the stack is aligned. On Linux and macOS it is System V AMD64. Follow it and your assembly can call any C function, and C can call your assembly.
| What | Where | Notes |
|---|---|---|
| Integer / pointer arguments 1 to 6 | rdi, rsi, rdx, rcx, r8, r9 | In that order. “Diane’s silk dress costs $89” |
| Arguments 7 and up | Pushed on the stack, right to left | At [rbp + 16], [rbp + 24], … inside the callee |
| Floating-point arguments | xmm0 to xmm7 | al = how many, for variadic functions such as printf |
| Return value | rax (and rdx for 128 bits); xmm0 for doubles | |
| Caller-saved (scratch) | rax, rcx, rdx, rsi, rdi, r8 to r11 | A called function may destroy them; save what you need before the call |
| Callee-saved (preserved) | rbx, rbp, r12 to r15 | A function that uses them must restore them before ret |
| Stack alignment | rsp is a multiple of 16 at the moment of every call | So inside a function, right after entry, rsp is 8 mod 16 |
| Red zone | 128 bytes below rsp | Leaf functions (that call nothing) may use it without sub rsp |
Windows uses a different convention (arguments in rcx, rdx, r8, r9, plus 32 bytes of “shadow space”). If your course uses Visual Studio and MASM, the register names change but the ideas do not.
Calling C from Assembly
add_two.asm: nasm -f elf64 add_two.asm && gcc -no-pie add_two.o -o add_two
default rel
extern printf, scanf
global main
section .data
prompt db "Enter two numbers: ", 0
in_fmt db "%ld %ld", 0
out_fmt db "%ld + %ld = %ld", 10, 0
section .bss
a resq 1
b resq 1
section .text
main:
push rbp
mov rbp, rsp ; rsp is now 16-byte aligned
lea rdi, [prompt]
xor eax, eax
call printf
lea rdi, [in_fmt] ; scanf("%ld %ld", &a, &b)
lea rsi, [a] ; ADDRESSES, because scanf writes into them
lea rdx, [b]
xor eax, eax
call scanf
mov rsi, [a] ; printf("%ld + %ld = %ld\n", a, b, a + b)
mov rdx, [b]
mov rcx, rsi
add rcx, rdx
lea rdi, [out_fmt]
xor eax, eax
call printf
xor eax, eax ; return 0
pop rbp
retscanfand anything that fills in a result takes addresses (lea);printftakes values (movfrom memory).- Use
%ldfor 64-bit values;%dreads or prints only 32 bits. - After the call, assume
rax,rcx,rdx,rsi,rdi,r8tor11are garbage. Here[a]and[b]live in memory, so nothing is lost. - Alignment:
mainstarts 8 mod 16;push rbpmakes it 0 mod 16; everycallabove happens with no further pushes, so all are aligned. Push one more register and you mustsub rsp, 8to compensate.
Calling a C function, step by step
- 1. Declare it at the top of the file:
extern printf, anddefault relso thatlea rdi, [fmt]works in a position-independent executable. - 2. Save what you still need. Anything live in
rax,rcx,rdx,rsi,rdi,r8tor11must be moved to a callee-saved register (rbx,r12tor15, pushed in your prologue) or to memory, because the callee may overwrite them. - 3. Load the arguments, in order: 1st
rdi, 2ndrsi, 3rdrdx, 4thrcx, 5thr8, 6thr9.movfor values,leafor addresses (format strings, buffers, anythingscanffills in). A 7th and later are pushed right to left. - 4. Set
alfor a variadic function (printf,scanf): the number ofxmmregisters holding arguments, soxor eax, eaxwhen there are no doubles. Non-variadic functions ignore it. - 5. Check the alignment.
rspmust be a multiple of 16 at thecall. You entermain8 off; eachpushmoves 8. An odd number of pushes (countingpush rbp) makes it right; otherwise addsub rsp, 8and undo it afterwards. - 6.
callthe function. - 7. Collect the result from
rax(xmm0for a double) before anything else clobbers it, pop any stack arguments withadd rsp, 8*k, and remember that the registers from step 2 are now garbage.
Applied to printf("%ld + %ld = %ld\n", a, b, a + b) above: rdi = format, rsi = a, rdx = b, rcx = a + b, al = 0, one push rbp since entry, call printf. The return value (the number of characters printed) is in rax and ignored.
Writing a Function C Can Call
Assembly
; long sum_array(const long *a, long n);
global sum_array
section .text
sum_array: ; rdi = a, rsi = n
xor eax, eax ; sum = 0
test rsi, rsi
jle .done
xor ecx, ecx ; i = 0
.top:
add rax, [rdi + rcx*8]
inc rcx
cmp rcx, rsi
jl .top
.done:
ret ; result already in rax; nothing to restoreC
#include <stdio.h>
long sum_array(const long *a, long n); /* defined in sum.asm */
int main(void)
{
long data[] = { 3, 1, 4, 1, 5, 9 };
printf("%ld\n", sum_array(data, 6)); /* 23 */
return 0;
}
/* nasm -f elf64 sum.asm && gcc main.c sum.o -o prog */A function that needs more registers
; long dot(const long *a, const long *b, long n);
global dot
dot:
push rbx ; we will use rbx: callee-saved, so save it
xor eax, eax
xor ecx, ecx
.top:
cmp rcx, rdx
jge .done
mov rbx, [rdi + rcx*8]
imul rbx, [rsi + rcx*8]
add rax, rbx
inc rcx
jmp .top
.done:
pop rbx ; restore before returning
retChecklist for a callable routine
- Arguments arrive in
rdi,rsi,rdx,rcx,r8,r9; the result leaves inrax. - Push any of
rbx,rbp,r12tor15you use; pop them in reverse beforeret. - If you
callanything, align the stack (an odd number of pushes, orsub rsp, 8) and keep your own live values in callee-saved registers. - Declare the label
global, and write the C prototype so the types match the registers you read.
Bit Manipulation and Shifts
Going Deeper · Assembly 1
The Logical Instructions
| Instruction | Each bit of the result is | Use for |
|---|---|---|
and dst, src | 1 only if both bits are 1 | Clearing bits, keeping a field (masking), testing |
or dst, src | 1 if either bit is 1 | Setting bits |
xor dst, src | 1 if the bits differ | Toggling bits; zeroing a register (xor eax, eax); swapping without a temporary |
not dst | flipped | Inverting a mask |
test a, b | an and that only sets flags | Is a bit set? Is the value zero? |
Set, clear, toggle, test bit k
or rax, 1 << 3 ; set bit 3
and rax, ~(1 << 3) ; clear bit 3 (~ is NASM's bitwise not, computed at assembly time)
xor rax, 1 << 3 ; toggle bit 3
test rax, 1 << 3 ; is bit 3 set? ZF = 0 if so
jnz .bit_is_set
bt rax, 3 ; "bit test": copies bit 3 into CF
jc .bit_is_set
bts rax, 3 ; test and set ; btr: test and reset ; btc: test and complementMasks
and eax, 0xFF ; keep the low byte (eax = eax mod 256)
and eax, 0xFFFFFFF0 ; round down to a multiple of 16
and rsp, -16 ; align the stack pointer down to 16 (-16 = ...FFF0)
mov edx, eax
shr edx, 8
and edx, 0xFF ; extract the SECOND byte
or eax, 0x80000000 ; set the sign bit of a 32-bit valueShifts
| Instruction | Does | Fills with | Arithmetic meaning |
|---|---|---|---|
shl dst, k (= sal) | Shift left k bits | Zeros on the right | Multiply by 2k |
shr dst, k | Shift right k bits, logical | Zeros on the left | Unsigned divide by 2k |
sar dst, k | Shift right k bits, arithmetic | Copies of the sign bit | Signed divide by 2k, rounding toward minus infinity |
rol / ror dst, k | Rotate: bits that fall off come back on the other side | Hashing, cryptography | |
shl dst, cl | Shift by a variable count | The count must be in cl |
Powers of two
shl rax, 1 ; rax * 2
shl rax, 4 ; rax * 16
shr rax, 3 ; rax / 8 (unsigned)
sar rax, 3 ; rax / 8 (signed; -9 >> 3 = -2, not -1)
; the compiler's signed division by 8 that rounds toward zero like C:
mov rdx, rax
sar rdx, 63 ; rdx = all ones if negative, else zero
and rdx, 7 ; bias = 7 for negative numbers, 0 otherwise
add rax, rdx
sar rax, 3Why shifts and masks
- A shift is one cycle;
imulis three or four andidivtwenty to ninety. Compilers turn every multiply or divide by a power of two into shifts. - Flags are stored one bit each: a byte holds eight yes/no values, and a mask picks one out.
- Hardware registers, file permissions (
rwxr-xr-x=0755), network headers and pixel colors (0xRRGGBB) are all bit fields you read with shifts and masks. - The last bit shifted out lands in CF, so
shr rax, 1/jc oddtests the low bit.
Worked Examples
Count the 1 bits (population count)
; rdi = value ; returns count in rax
popcount:
xor eax, eax
.top:
test rdi, rdi
jz .done
mov rcx, rdi
and rcx, 1 ; the low bit
add rax, rcx
shr rdi, 1 ; next bit
jmp .top
.done:
ret
; one instruction on modern CPUs: popcnt rax, rdiIs it a power of two?
; a power of two has exactly one 1 bit, so n & (n - 1) clears it to zero
; rdi = n ; returns 1 in rax if a power of two, else 0
is_pow2:
xor eax, eax
test rdi, rdi
jz .done ; 0 is not a power of two
lea rcx, [rdi - 1]
test rdi, rcx
setz al ; al = 1 if (n & (n-1)) == 0
.done:
retPack and unpack a color
; rgb = (r << 16) | (g << 8) | b r, g, b in edi, esi, edx (0..255)
mov eax, edi
shl eax, 16
shl esi, 8
or eax, esi
or eax, edx ; eax = 0x00RRGGBB
; green = (rgb >> 8) & 0xFF
mov ecx, eax
shr ecx, 8
and ecx, 0xFFSwap two registers with xor
xor rax, rbx
xor rbx, rax
xor rax, rbx ; rax and rbx have traded values, no temporary needed
; (a classic trick; on real CPUs three movs or xchg are just as fast)shr on a signed number is wrong. -8 shr 1 is a huge positive number, not -4. Use sar for signed values, shr for unsigned, and remember that C’s / rounds toward zero while sar rounds down, which is why compilers add the bias shown above.
Reading Compiler Output and AT&T Syntax
Going Deeper · Assembly 1
Seeing What the Compiler Did
The payoff of the course: take C you understand, ask the compiler for the assembly, and recognize every construct from the earlier tabs. gcc -S produces AT&T syntax by default; -masm=intel gives the syntax used on this sheet.
Commands
gcc -O1 -S -masm=intel -fno-asynchronous-unwind-tables sum.c # writes sum.s, readable
gcc -O0 -S sum.c # unoptimized: every variable lives on the stack, easiest to map to the C
gcc -O2 -S sum.c # optimized: what ships; loops rewritten, variables in registers
objdump -d -M intel prog | less # disassemble a finished executable
gdb ./prog -> disassemble main # or inside the debuggerC
long sum(const long *a, long n)
{
long total = 0;
for (long i = 0; i < n; i++)
total += a[i];
return total;
}gcc -O1 -masm=intel (lightly cleaned)
sum:
test rsi, rsi ; if (n <= 0) goto zero
jle .L4
mov eax, 0 ; total = 0
mov edx, 0 ; i = 0
.L3:
add rax, [rdi + rdx*8] ; total += a[i]
add rdx, 1 ; i++
cmp rsi, rdx
jne .L3 ; loop while i != n (the compiler knows i never passes n)
ret
.L4:
mov eax, 0
retNotice: the test moved to the bottom, i < n became i != n, mov eax, 0 is used because writing eax clears rax in fewer bytes, and nothing touched the stack because the function is a leaf with everything in registers.
Recognizing Constructs
| In the C | In the assembly | Tell-tale signs |
|---|---|---|
if / else | cmp or test + a conditional jump that skips a block; jmp over the else | Two labels close together |
? : or a small if assigning one value | cmovcc or setcc | No jump at all |
while / for | A label, a body, a cmp and a jump backward; often a guard jump before the label | A jump to a lower address |
switch with dense cases | A bounds check, then jmp [table + rax*8]: a jump table | .rodata holds a list of label addresses |
| Function call | Arguments into rdi, rsi, …; call; result read from rax | Pushes of callee-saved registers at the start of the callee |
| Local variables at -O0 | [rbp - 8], [rbp - 12], … | Loads before every use, stores after |
| Array indexing | [base + index*8] or a pointer that advances by 8 | lea computing addresses |
x * 10, x / 8, x % 16 | lea + shl; sar with a bias; and with 15 | No imul or idiv for constants |
struct field access | A fixed displacement: [rdi + 16] | Offsets are multiples of the field sizes |
| Returning a value | Last write to rax (or eax) before ret |
A switch becomes a jump table
; switch (x) { case 0: ... case 1: ... case 2: ... default: ... }
cmp rdi, 2
ja .default ; unsigned compare handles negatives too
jmp [.table + rdi*8]
.table: dq .case0, .case1, .case2
.case0: ...A struct and a pointer
; struct point { long x; long y; }; long sum(struct point *p) { return p->x + p->y; }
sum:
mov rax, [rdi] ; p->x (offset 0)
add rax, [rdi + 8] ; p->y (offset 8)
retAT&T Syntax: The Other Spelling
gcc, objdump and gdb default to AT&T syntax, used by the GNU assembler. Same instructions, different spelling. Four rules convert one to the other.
| Rule | Intel (NASM, this sheet) | AT&T (gas, gcc -S) |
|---|---|---|
| Operand order is reversed: source first, destination last | mov rax, rbx | movq %rbx, %rax |
Registers get %, immediates get $ | mov rax, 5 | movq $5, %rax |
| The size is a suffix on the mnemonic: b, w, l, q | mov dword [rbx], 1 | movl $1, (%rbx) |
Memory is disp(base, index, scale) | mov rax, [rdi + rcx*8 + 16] | movq 16(%rdi, %rcx, 8), %rax |
| Variables by name | mov rax, [count] / lea rax, [rel count] | movq count(%rip), %rax / leaq count(%rip), %rax |
| Comments | ; text | # text |
| Jumps and calls | the same | the same; indirect ones get a *: jmp *%rax |
Intel (NASM): the same square() function
; Intel (NASM)
push rbp
mov rbp, rsp
mov dword [rbp - 4], edi
mov eax, [rbp - 4]
imul eax, eax
pop rbp
retAT&T (gas)
# AT&T (gas)
pushq %rbp
movq %rsp, %rbp
movl %edi, -4(%rbp)
movl -4(%rbp), %eax
imull %eax, %eax
popq %rbp
ret- Read AT&T left to right as “move this into that”; read Intel as “set that to this”.
- When a listing has
%signs, it is AT&T. Flip the operands in your head before anything else. gdb:set disassembly-flavor intelswitches it permanently (put it in~/.gdbinit).- Textbooks: Computer Systems: A Programmer’s Perspective uses AT&T; most NASM tutorials and Intel’s manuals use Intel. You will meet both, and after a week you stop noticing.
The single most common reading error is applying one syntax’s operand order to the other. mov rax, rbx and movq %rax, %rbx look alike and do opposite things.