13.3 — Registers and instructions
Registers: the CPU's own tiny variables#
The CPU can't do math directly on your variables in memory very fast. It first loads values into registers: a handful of super-fast boxes inside the CPU itself.
On x86-64 (the CPU type in most PCs), the main ones are:
| 64-bit | 32-bit part | Common job |
|---|---|---|
rax | eax | the return value of a function |
rdi | edi | 1st argument (Linux/Mac) |
rsi | esi | 2nd argument (Linux/Mac) |
rdx | edx | 3rd argument (Linux/Mac) |
rcx | ecx | 4th argument (Linux/Mac), 1st on Windows |
rsp | esp | the stack pointer — top of the stack |
rbp | ebp | often the base pointer of the current function |
r8–r15 | r8d–r15d | extra general registers |
An int is 32 bits, so code working with ints uses the 32-bit names like eax and edi. Pointers are 64 bits, so they use rax, rdi and so on.
Reading one instruction#
Most instructions look like this (Intel style):
instruction destination, sourcemov eax, edi ; eax = ediadd eax, 5 ; eax = eax + 5Everything after ; is a comment.
In Intel syntax, the left side is where the result goes. mov eax, edi copies into eax. Read it like eax = edi.
The instructions you'll see most#
| Instruction | Meaning | Like in C++ |
|---|---|---|
mov a, b | copy | a = b |
add a, b | add | a += b |
sub a, b | subtract | a -= b |
imul a, b | multiply | a *= b |
lea a, [x+y] | work out an address/sum | a = x + y |
cmp a, b | compare (sets flags) | a == b, a < b... |
test a, a | check zero / sign | a == 0, a < 0 |
jmp L | jump to label L | goto |
je / jne / jl / jg... | jump if equal / not equal / less / greater... | if |
call f | call a function | f() |
ret | return from function | return |
push / pop | put on / take off the stack | — |
Memory access#
Square brackets [ ] mean "the memory at this address" — just like * for a pointer.
mov eax, DWORD PTR [rdi+8] ; eax = the 4 bytes at address (rdi + 8)DWORD PTR= read 4 bytes (anint).QWORD PTR= read 8 bytes (a pointer orlong long).BYTE PTR= read 1 byte (achar).
There are two ways to write x86 assembly. Intel syntax (used here, by Ghidra, IDA and x64dbg) puts the destination first. AT&T syntax (the default of objdump and gdb on Linux) puts it last and adds % and $: movl %edi, %eax. Same instructions, different spelling. Use objdump -M intel to switch.
Tip: press ← / → to move between lessons, / to search.