Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 3 (Sep 1), slide deck
03-machine. Reading: CS:APP3e §3.1–3.6. Lab: L0 due; L2 (bomblab) comes out with Lecture 4. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes. Its centerpiece isx86sim.py, a simulator that runs the compiler’s real x86-64 output instruction by instruction. All listings are clang output (Apple clang 21,-Og), whereas the slides show gcc on the shark machines, so register choices sometimes differ (§10). The real x86-64 code was run under Rosetta 2 on an Apple M4 Pro. A cross-check found 0 disagreements between the simulator and the hardware in 4,508 cases. Code:code/lecture03/. Reading time: ~90 minutes; ~40 more for the demos. This is a dense lecture. Read it twice, once for the big picture and once with the demos open.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain what an ISA is, how it differs from a microarchitecture, and what programmer-visible state an x86-64 program can see.
- Name the 16 general-purpose registers and their 1/2/4/8-byte sub-names, and state the rule for what writing each size does to the rest of the register.
- Read the three kinds of operand (immediate, register, memory) and evaluate any memory operand
D(Rb,Ri,S)by hand. - Translate between short C functions and their assembly, including
mov,lea, the arithmetic and logical instructions, and the extension movesmovz/movs. - Explain how condition codes are set by
cmp/test, and howsetcc andjcc turn them into booleans and decisions, including why signed “less” isSF ^ OF. - Follow a function from C to assembly to machine code bytes, and read an
objdumplisting.
0.2 Prerequisites and scope
- Lecture 2: bit patterns, two’s complement, sign/zero extension, little endianness. Everything in this lecture is those ideas executed by hardware.
- In scope: the slides of Lecture 3 (registers, operands,
mov, addressing, arithmetic, an introduction to condition codes and jumps, the toolchain) and CS:APP §3.1–3.6.3. - Later: loops,
switchand conditional moves (Lecture 4); the stack,call/retand calling conventions in depth (Lectures 4–5); arrays and structs (Lectures 5–6).
0.3 Section → code map
| Section | Idea | Demo in code/lecture03/ |
|---|---|---|
| §1–3 | levels of abstraction; ISA; visible state; x86 history | — |
| §4 | registers and their names | 04_operands_and_sizes.py (PART D) |
| §5 | operands and mov; swap | 02_trace_swap.py, 04 (PART A) |
| §6 | addressing modes D(Rb,Ri,S) | 03_arith_and_lea.py (PART A) |
| §7 | arithmetic, logic, lea; arith, m12 | 03 (PARTS B, C) |
| §8 | partial registers, movz/movs | 04 (PARTS B, C) |
| §9 | condition codes, cmp/test, setcc, jcc | 05_condition_codes.py |
| §10 | C → assembly → machine code; objdump | 01_c_to_machine_code.py |
| — | is the simulator right? | 06_crosscheck.py |
0.4 Notation and syntax
- These notes use AT&T syntax, as gcc, objdump, gdb, CS:APP and 15-213 do:
op source, destination. Registers start with%, immediates with$, and the size is a suffix on the mnemonic (movq). The other syntax, Intel’s, reverses the operand order. §10.4 compares them. R[%rax](orReg[%rax]) is the value in register%rax;M[a](orMem[a]) is the value in memory at address a.- Assembly comments use
#(gcc) or##(clang on macOS).
1. Why look below C at all?
1.1 Three levels of abstraction
The slides show the same program at three levels:
| You are a… | You see… | You don’t see… |
|---|---|---|
| C programmer | variables, types, expressions, if/for, functions | where values live, how many steps an operation takes |
| assembly programmer | registers, memory addresses, one small operation per instruction, jumps | how the hardware implements each instruction |
| computer designer | gates, clocks, pipelines, caches, circuit layout | which program will run |
15-213 lives in the middle layer. You will rarely write assembly, as Lecture 1 explained. But you must read it to debug code whose C-level model has broken (undefined behavior, memory corruption), to understand performance (Lecture 15), to understand security attacks (Lecture 6, attacklab), and to do bomblab, which is nothing but reading assembly.
1.2 Definitions you will use all semester
- Architecture, also called the ISA (instruction set architecture): the parts of a processor that you must understand to write assembly or machine code. That means the instruction set, the registers, the memory model and the encoding. It is the contract between software and hardware. Examples: x86-64, ARM (AArch64), RISC-V.
- Microarchitecture: how a particular chip implements the ISA: pipeline depth, cache sizes, clock frequency. A Core i7 and an AMD Zen 4 implement the same ISA with very different microarchitectures. Software written for the ISA runs on both.
- Machine code: the bytes the processor executes.
- Assembly code: a human-readable text form of machine code, one line per instruction.
1.3 The programmer-visible state
From the assembly programmer’s point of view, an x86-64 CPU running your program is just this:
CPU Memory
┌────────────────────────────┐ addresses ┌───────────────────┐
│ %rip (program counter) │ ───────────▶ │ code │
│ register file (16 x 64 bit)│ ◀────────▶ │ data (globals) │
│ condition codes CF ZF SF OF│ data │ heap │
└────────────────────────────┘ ◀────────── │ stack │
instructions └───────────────────┘
%rip(instruction pointer = program counter): the address of the next instruction.- Register file: 16 named 64-bit registers holding heavily used values.
- Condition codes: four 1-bit flags describing the most recent arithmetic or logical result. They exist for conditional branches (§9).
- Memory: one big array of bytes, addressed from 0 to 264−1 (in practice 248), holding code, global data, the heap and the stack.
Things C does have are missing here: there are no types, no arrays, no structs, no variables with names. Memory is bytes; registers are 64 bits. A value is “an int” or “a pointer” only because of how instructions use it. x86sim.py models exactly this state. Its Machine class holds rip, regs, flags and mem, and nothing else.
2. A short history of x86
x86 is an evolutionary design. Every generation stayed backward-compatible with the previous one, all the way back to 1978. That explains most of its quirks.
| Chip | Year | Transistors | What changed |
|---|---|---|---|
| 8086 | 1978 | 29 K | first 16-bit Intel CPU (IBM PC, DOS); 1 MB address space; registers ax, bx, … |
| 386 | 1985 | 275 K | first 32-bit x86 (“IA32”); “extended” registers eax, …; flat addressing, enough to run Unix |
| x86-64 (AMD) | 2003 | — | AMD extends IA32 to 64 bits: registers rax, …, plus r8–r15 |
| Pentium 4E | 2004 | 125 M | Intel’s first x86-64 chip |
| Core 2 | 2006 | 291 M | first multi-core Intel CPU |
| Core i7 | 2008 | 731 M | 4 cores (the shark machines are this family) |
x86 is a CISC (complex instruction set computer): many instructions with many formats, variable-length encodings (1–15 bytes), and memory operands on arithmetic instructions. The RISC philosophy (ARM, RISC-V) prefers few, simple, fixed-length instructions with loads and stores separate from arithmetic. For decades RISC was believed to be inherently faster. Intel matched RISC speed by translating x86 instructions into RISC-like micro-operations inside the chip. RISC designs have kept an advantage in power, which is one reason phones (and now Macs) use ARM. Real programs use only a small subset of x86’s ~5,000 pages of instructions, and that subset is what this lecture teaches.
3. Assembly as a language: nouns and verbs
The slides offer a useful framing. Assembly is a tiny language:
- nouns: registers (a fixed set of names) and memory (everything else, reached by address);
- verbs: operations, which move data, compute, or transfer control;
- suffixes: the operand size (
b,w,l,q); - “grammar”:
verb source, destination.
add %rbx, %rax # rax += rbx
There are only three kinds of verbs:
- move data between memory and registers (
mov,push,pop,lea…); - compute on registers or memory (
add,imul,and,sal…); - transfer control: unconditional jumps, conditional branches, indirect branches, procedure call/return.
Everything C does (variables, expressions, if, loops, functions, arrays, structs) must be expressed with these.
4. Registers
4.1 Sixteen registers, four sizes each
x86-64 has 16 general-purpose integer registers. Each has names for its low 8, 4, 2 and 1 bytes:
| 64-bit | 32-bit | 16-bit | 8-bit | conventional role |
|---|---|---|---|---|
%rax | %eax | %ax | %al | return value |
%rbx | %ebx | %bx | %bl | callee-saved |
%rcx | %ecx | %cx | %cl | 4th argument |
%rdx | %edx | %dx | %dl | 3rd argument |
%rsi | %esi | %si | %sil | 2nd argument |
%rdi | %edi | %di | %dil | 1st argument |
%rbp | %ebp | %bp | %bpl | callee-saved (sometimes frame pointer) |
%rsp | %esp | %sp | %spl | stack pointer |
%r8–%r15 | %r8d… | %r8w… | %r8b… | args 5–6 (r8, r9), others temporaries / callee-saved |
The odd names are history. In the 8086, ax was the “accumulator”, cx the “counter”, si/di the “source/destination index”, sp/bp the “stack/base pointer”. The 386 put an e in front for “extended” (32 bits); x86-64 used r for 64 bits and added eight numbered registers. The roles are now mostly conventions, not hardware requirements. Two exceptions are fixed by the architecture: %rsp is the stack pointer (push, pop, call and ret use it implicitly), and %rip is the program counter, which is not a general-purpose register at all.
The calling convention (the System V AMD64 ABI, which Linux and macOS share) says that the first six integer or pointer arguments arrive in %rdi, %rsi, %rdx, %rcx, %r8, %r9, in that order, and the return value goes in %rax. Memorize that sentence now: it lets you read any function’s assembly. Lecture 5 covers the rest of the convention.
4.2 Registers vs memory
The slides’ intuition is that registers are “super-fast memory right on the CPU core”. A register is accessed by name in a fraction of a nanosecond. Memory (DRAM) is accessed by address and is slower by one to two orders of magnitude, although caches hide much of that (Lectures 9–10). There are only 16 registers, so the compiler’s main job is deciding which values live in registers and when. A local int x that is used a lot will probably never be in memory at all. That is one reason the C-level picture of “variables in memory” breaks down when you debug optimized code.
5. Operands and moving data
5.1 Three kinds of operand
| Kind | Syntax | Meaning | C analogy |
|---|---|---|---|
| Immediate | $0x400, $-533 | a constant encoded in the instruction (1, 2 or 4 bytes; 8 only for movabsq) | a literal |
| Register | %rax, %r13 | the value in that register | a local variable |
| Memory | (%rax), 8(%rbp) | the bytes at the computed address | *p |
The rule of the slides: parentheses always mean a memory address computation. (%rdi) reads like *rdi.
5.2 mov and its legal combinations
movq Source, Dest copies 8 bytes from source to destination:
| Source → Dest | Example | C analogue |
|---|---|---|
| Imm → Reg | movq $0x4, %rax | temp = 0x4; |
| Imm → Mem | movq $-147, (%rax) | *p = -147; |
| Reg → Reg | movq %rax, %rdx | temp2 = temp1; |
| Reg → Mem | movq %rax, (%rdx) | *p = temp; |
| Mem → Reg | movq (%rax), %rdx | temp = *p; |
Memory → memory is not allowed in one instruction. To copy memory to memory you load into a register and then store, which is exactly what you will see in swap. An immediate can never be a destination.
5.3 Reading assembly: swap (the slides’ “whatAmI”)
The slides give a function with no source:
whatAmI:
movq (%rdi), %rax
movq (%rsi), %rdx
movq %rdx, (%rdi)
movq %rax, (%rsi)
ret
and ask what it does. Read it like this:
- Find the arguments.
%rdiand%rsiare the first two arguments. - How are they used? Only inside parentheses, so they are addresses: the arguments are pointers.
- What size?
movq= 8 bytes, so they point tolongs (or pointers). - Rename registers as variables.
t0 = *xp; t1 = *yp; *xp = t1; *yp = t0;. It isswap(long *xp, long *yp).
Clang produces the same four moves with %rcx instead of %rdx. Any free scratch register will do. 02_trace_swap.py reproduces the slides’ animation, with xp = 0x120 (holding 123) and yp = 0x100 (holding 456). A * marks what each instruction changed:
instruction %rdi %rsi %rax %rcx M[0x120] M[0x100]
(on entry) *0x120 *0x100 0 0 123 456
movq (%rdi), %rax 0x120 0x100 *123 0 123 456
movq (%rsi), %rcx 0x120 0x100 123 *456 123 456
movq %rcx, (%rdi) 0x120 0x100 123 456 *456 456
movq %rax, (%rsi) 0x120 0x100 123 456 456 *123
Two loads, then two stores. The registers hold the pointers and the temporaries; memory holds the data.
6. Memory addressing modes
6.1 The general form
- D: a constant displacement (1, 2 or 4 bytes);
- Rb: a base register (any of the 16);
- Ri: an index register (any except
%rsp); - S: a scale, which must be 1, 2, 4 or 8.
A missing part takes its identity value: +0 for D and the registers, ×1 for S. The special cases are (Rb), D(Rb), (Rb,Ri), D(Rb,Ri) and (Rb,Ri,S).
6.2 Why this shape?
Because it is exactly array indexing. In C, a[i] lives at address a + sizeof(*a) * i, and s.f[i] adds a constant offset for the field. So the hardware gives you base + scaled index + constant offset in one operand. The scales 1, 2, 4, 8 are the sizes of char, short, int/float and long/double/pointers. The slides ask “why these numbers?”, and that is the answer. The compiler output shows it directly (make asm):
long load_idx(long *a, long i) { return a[i]; } // movq (%rdi,%rsi,8), %rax
long load_disp(int *a, long i) { return a[i + 32]; } // movslq 128(%rdi,%rsi,4), %rax
void store_char(char *d, long y, char a) { d[y] = a; } // movb %dl, (%rdi,%rsi)
void store_int(int *d, long y, int a) { d[y] = a; } // movl %edx, (%rdi,%rsi,4)
The scale follows sizeof(element). In load_disp, a[i+32] became displacement 128 = 32 × 4, and the 4-byte int was sign-extended to a long by movslq, which is Lecture 2’s sign extension done by one instruction.
6.3 Practice: the slide’s table
With %rdx = 0xf000 and %rcx = 0x0100, 03_arith_and_lea.py evaluates each operand with the simulator’s own address calculator:
expression computation address
0x8(%rdx) 0xf000 + 0x8 0xf008
(%rdx,%rcx) 0xf000 + 0x100 0xf100
(%rdx,%rcx,4) 0xf000 + 4*0x100 0xf400
0x80(,%rdx,2) 2*0xf000 + 0x80 0x1e080
The last row has no base, only a scaled index. That form is useful for global arrays, where the displacement is the array’s address.
7. Arithmetic and logical operations
7.1 Two-operand and one-operand instructions
| Format | Computation | Note |
|---|---|---|
addq S, D | D ← D + S | |
subq S, D | D ← D − S | note the order: destination minus source |
imulq S, D | D ← D × S | low 64 bits (Lecture 2 §7.3) |
salq k, D / shlq k, D | D ← D ≪ k | same instruction, two names |
sarq k, D | D ← D ≫A k | arithmetic (signed) right shift |
shrq k, D | D ← D ≫L k | logical (unsigned) right shift |
xorq S, D, andq S, D, orq S, D | bitwise | |
incq D, decq D | D ± 1 | |
negq D | D ← −D | two’s-complement negation, ~D + 1 |
notq D | D ← ~D | bitwise complement |
The slides note “think datalab”: these are exactly Lecture 2’s operations, one instruction each. There is no distinction between signed and unsigned in add, sub or imul (the two-operand form), for exactly the reason Lecture 2 proved: they produce the same bits. Only right shifts (sar vs shr), comparisons (g/l vs a/b, §9), widening (movs vs movz) and division (idiv vs div) care about signedness. Shift counts are either an immediate or the register %cl.
7.2 lea: the address calculator that does arithmetic
leaq Src, Dst computes the address denoted by the memory operand Src and puts it in Dst, without accessing memory. Compare the same operand used two ways (demo 03, PART B):
movq 8(%rdi,%rsi,8), %rax -> %rax = 777 (the DATA at the address)
leaq 8(%rdi,%rsi,8), %rdx -> %rdx = 0x1018 (the ADDRESS itself)
In C: rax = p[i+1] (a load) vs rdx = &p[i+1] (pointer arithmetic)
The slides list the reasons compilers love it:
- its designers intended it for computing pointers, as in
p = &x[i]; - it computes
x + k·y + dwith k ∈ {1, 2, 4, 8} in one instruction; - it is one of x86’s few three-operand instructions: the destination need not be a source;
- it does not change the condition codes, so it can sit between a compare and a jump.
So compilers use lea for ordinary arithmetic all the time. m12(x) = x * 12 became two leas and no multiply:
leaq (,%rdi,4), %rax %rax = 4x (7 → 28)
leaq (%rax,%rax,2), %rax %rax = 4x + 2·4x = 12x (28 → 84)
7.3 Reading a whole function: arith
long arith(long x, long y, long z) {
long t1 = x + y; long t2 = z + t1;
long t3 = x + 4; long t4 = y * 48;
long t5 = t3 + t4; long rval = t2 * t5;
return rval;
}
Clang’s -Og code, traced with x = 5, y = 2, z = 11:
leaq (%rsi,%rdi), %rcx %rcx=7 t1 = x + y (lea as an adder)
leaq (%rdx,%rcx), %rax %rax=18 t2 = z + t1
leaq 4(%rdi), %r8 %r8=9 t3 = x + 4 (computed... then never used!)
shlq $4, %rsi %rsi=32 y = y << 4 (y*16)
leaq (%rsi,%rsi,2), %rsi %rsi=96 y = y + 2*y (y*48 = t4)
leaq (%rdi,%rsi), %r9 %r9=101 x + t4
addq $4, %r9 %r9=105 + 4 -> t5 = (x + t4) + 4: re-associated
imulq %r9, %rax %rax=1890 rval = t2 * t5 (the ONE real multiply)
result 1890, C formula gives 1890
Three lessons, all of which you will need in bomblab:
- Map registers to variables.
%rdi,%rsi,%rdxare x, y, z on entry, and%raxholds the answer at the end. In between, registers are reused freely:%rsistops being y once it is overwritten with 16y. - Multiplication by a constant becomes shifts and
leas. y·48 = (y·16)·3, computed as a shift by 4 followed bylea (%rsi,%rsi,2). Only t2·t5 needs a realimul, because neither factor is a constant. - The assembly need not follow your statements. Clang computed
t3 = x + 4into%r8, then found it easier to compute t5 as (x + t4) + 4 and never used%r8.-Ogis “optimize lightly, stay debuggable”, not “optimize fully”. The results must match the C; the steps need not. (The slides’ gcc version is cleaner:leaq 4(%rdi,%rdx), %rcxcomputes t5 in one instruction.)
8. Sizes, partial registers and extension
8.1 The size suffix is the number of bytes touched
| Suffix | Name (Intel’s historical terms) | Bytes | Typical C type |
|---|---|---|---|
b | byte | 1 | char |
w | word | 2 | short |
l | “long word” (double word) | 4 | int |
q | quad word | 8 | long, pointers |
(The “word” is 16 bits because the 8086 was a 16-bit machine. This is history again.) 04_operands_and_sizes.py fills memory with aa bytes and runs store_sizes:
c -> 0x200: 01 aa aa aa aa aa aa aa movb $1, (%rdi)
s -> 0x210: 02 00 aa aa aa aa aa aa movw $2, (%rsi)
i -> 0x220: 03 00 00 00 aa aa aa aa movl $3, (%rdx)
l -> 0x230: 04 00 00 00 00 00 00 00 movq $4, (%rcx)
Each store writes exactly its size, little endian. The suffix and the register name must agree. movl %rax, (%rsp) is an assembler error: l says 4 bytes, but %rax is 8.
8.2 The partial-register rule
What happens to the rest of %rax when you write %eax, %ax or %al? The answer is asymmetric. Demo 04 checks it against the real processor (x86-64 code running under Rosetta 2):
%rax starts as 0x0123456789abcdef, then one instruction writes a smaller name:
movl $0x11, %eax -> sim 0x0000000000000011, hardware 0x0000000000000011 (4 bytes, upper 4 bytes ZEROED)
movw $0x22, %ax -> sim 0x0123456789ab0022, hardware 0x0123456789ab0022 (2 bytes, the other 6 kept)
movb $0x33, %al -> sim 0x0123456789abcd33, hardware 0x0123456789abcd33 (1 byte, the other 7 kept)
Rule. An instruction that writes a 4-byte register (
%eax,%r8d, …) zeroes the upper 4 bytes of the 64-bit register. Writing a 1- or 2-byte register leaves the other bytes unchanged.
Why the difference? AMD chose this for x86-64 in 2003 for performance. If a 32-bit write kept the old upper half, every 32-bit operation would depend on the register’s previous value, and the out-of-order hardware would have to wait for it and merge the parts. Zeroing breaks that dependency. The 8- and 16-bit behavior was inherited from IA32 and could not be changed without breaking old code. You will see this rule used constantly: compilers write xorl %eax, %eax to zero all of %rax (it is shorter than xorq), and movl to zero-extend a 32-bit value for free.
8.3 Widening: movz and movs
Lecture 2’s zero and sign extension are single instructions: mov + z (zero) or s (sign) + source size + destination size.
movzbl %dil, %eax -> %rax = 0x00000000000000f0 = 240
movsbl %dil, %ecx -> %rcx = 0x00000000fffffff0 = 4294967280
movzbq %dil, %rdx -> %rdx = 0x00000000000000f0 = 240
movsbq %dil, %rsi -> %rsi = 0xfffffffffffffff0 = -16
Look at movsbl. It sign-extends the byte 0xf0 (−16) to the 32-bit value 0xfffffff0. Because the destination is a 4-byte register, the §8.2 rule then zeroes the upper half of %rcx. As a 64-bit value that is 4294967280, not −16. The destination size decides what the upper bits mean, which is exactly why the compiler picked movslq (sign-extend 4 → 8 bytes) for load_disp (§6.2). There is no movzlq, because movl already zero-extends 4 → 8 bytes by the §8.2 rule. Other names you will meet: cltq (sign-extend %eax into %rax) and cqto (sign-extend %rax into %rdx:%rax, before a division, Lecture 4).
9. Condition codes, comparisons and jumps
9.1 Why flags?
Assembly has no bool and no if. To make a decision, the CPU keeps four 1-bit condition codes in a special FLAGS register. Arithmetic and logical instructions set them as a side effect, and later instructions read them:
| Flag | Name | Set when the result… | Meaning |
|---|---|---|---|
| CF | carry flag | produced a carry out of (or a borrow into) the top bit | unsigned overflow |
| ZF | zero flag | is zero | equality |
| SF | sign flag | has its top bit set | “negative” if read as signed |
| OF | overflow flag | overflowed as a two’s-complement value | signed overflow |
CF and OF are Lecture 2 §7.2’s two overflow tests, computed by hardware on every addition. lea does not set flags (§7.2); inc/dec set all of them except CF.
9.2 cmp and test: compute only to set flags
cmpq b, acomputes a − b likesubq, sets the flags, and discards the result. It is used forif (a < b)and similar tests, whenever a − b isn’t needed for anything else. Note the operand order:cmpq %rsi, %rdicompares%rdiagainst%rsi.testq b, acomputes a & b likeandq, sets ZF and SF (CF = OF = 0), and discards the result. Its most common use istestq %rax, %raxto compare a value with zero. The second most common is testing whether any bits of a mask are set.
9.3 Reading the flags: jcc and setcc
| Condition | Flags | Meaning after cmp b, a |
|---|---|---|
e / z | ZF | a == b |
ne / nz | ~ZF | a != b |
s / ns | SF / ~SF | result negative / non-negative |
g | ~(SF^OF) & ~ZF | a > b, signed |
ge | ~(SF^OF) | a ≥ b, signed |
l | SF^OF | a < b, signed |
le | (SF^OF) | ZF | a ≤ b, signed |
a | ~CF & ~ZF | a > b, unsigned (“above”) |
ae | ~CF | a ≥ b, unsigned |
b | CF | a < b, unsigned (“below”) |
be | CF | ZF | a ≤ b, unsigned |
jcc jumps if the condition holds. setcc writes 1 or 0 into a single byte register. jmp jumps unconditionally.
Why “signed less” is SF ^ OF, not just SF. If a − b did not overflow, its sign tells you whether a < b. If it did overflow, the sign is wrong, so you flip it. That is exactly XOR with OF. 05_condition_codes.py shows the cases where it matters:
a b CF ZF SF OF true conditions
-1 2 0 0 1 0 ne l le a
-9223372036854775808 1 0 0 0 1 ne l le a
9223372036854775807 -1 1 0 1 1 ne g ge b
- (−1, 2): signed −1 < 2 (
l), but unsigned 0xff…ff > 2 (a). The same flags answer both questions, and the C types decide which instruction the compiler emits. - (TMin, 1): TMin − 1 overflows to TMax, so SF = 0 and the result “looks positive”, but OF = 1, so
l= SF^OF = 1. Correct.
The demo then checks the whole table exhaustively. It runs cmpb on all 65,536 pairs of bytes and compares each condition with Python’s own signed or unsigned comparison: 0 disagreements for every condition. A naive “less = SF” rule would be wrong in 16,384 pairs, exactly the ones where the subtraction overflows.
9.4 Turning a comparison into a value: setcc
int gt(long x, long y) { return x > y; }
xorl %eax, %eax # %rax = 0 (all 8 bytes, by the 32-bit write rule)
cmpq %rsi, %rdi # compute x - y, set flags
setg %al # %al = (x > y) ? 1 : 0
retq
setg writes only %al, so the rest of %eax must already be zero. Clang zeroes it before the cmp, because xorl itself changes the flags and could not go between cmp and setg. Gcc often writes the same idea as setg %al; movzbl %al, %eax instead. The unsigned version below(x, y) is identical except for setb.
9.5 Turning a comparison into a decision: if/else is goto
long decision(long x) { if (x) return op1(x); else return op2(x); }
testq %rdi, %rdi # is x zero?
je LBB17_2 # if so, go to the else part
jmp _op1 # then-part
LBB17_2:
xorl %edi, %edi # else-part: x is known to be 0 here
jmp _op2
The slides’ punchline is that assembly has only goto. An if is “test, conditionally jump over the then-part”. Demo 05 traces both paths: x = 5 (je not taken) returns 105, and x = 0 (je taken) returns −100. Two details are worth noticing. First, jmp _op1 instead of call _op1; ret is a tail call: when the last thing a function does is call another function and return its result, it can simply jump there, and that function’s ret goes straight back to our caller (Lecture 5). Second, in the else branch the compiler knows x = 0, so it passes 0 with xorl %edi,%edi. Lecture 4 develops conditional code and loops fully.
10. From C to machine code
10.1 The toolchain
p1.c p2.c ──[compiler: gcc -Og -S]──▶ p1.s p2.s ──[assembler: gcc -c / as]──▶ p1.o p2.o
│
static libraries (.a) ──▶ [linker: gcc / ld] ──▶ p (executable)
gcc -Og -S sum.c stops after compiling and writes sum.s. -Og means “optimizations that don’t hurt debugging”, the level CS:APP uses. The slides warn that you will get very different output on other machines (Mac, other gcc versions). These notes are an example: they use clang, and every listing is clang’s.
10.2 What a .s file really looks like
The compiler’s raw output is full of lines starting with .. These are directives, instructions to the assembler rather than machine instructions: .globl sumstore (make the symbol visible to the linker), .cfi_* (unwinding information for debuggers and exceptions), .p2align (alignment). Filtering them out leaves the real code. The make asm flags (-fno-asynchronous-unwind-tables -fomit-frame-pointer -fno-stack-protector -fcf-protection=none) suppress the noise, so the listings look like the textbook’s.
10.3 Object code and disassembly
01_c_to_machine_code.py follows sumstore all the way down:
void sumstore(long x, long y, long *dest) { long t = plus(x, y); *dest = t; }
Assembly (the .s file):
pushq %rbx # save %rbx (we will use it)
movq %rdx, %rbx # keep dest in %rbx: plus() may overwrite %rdx
callq _plus # t = plus(x, y) (x, y already in %rdi, %rsi)
movq %rax, (%rbx) # *dest = t
popq %rbx # restore %rbx
retq
Object file (.o), disassembled by objdump -d:
180: 53 pushq %rbx
181: 48 89 d3 movq %rdx, %rbx
184: e8 00 00 00 00 callq 0x189 <_sumstore+0x9>
189: 48 89 03 movq %rax, (%rbx)
18c: 5b popq %rbx
18d: c3 retq
Linked executable:
100000b74: e8 e7 ff ff ff callq 0x100000b60 <_plus>
-> sumstore is 14 bytes of machine code in 6 instructions
-> decoding the call: e8 = 'call rel32'; displacement bytes e7 ff ff ff
read little endian = -25; target = next instruction 0x100000b79 -25 = 0x100000b60
What to notice:
- Machine code is just bytes.
movq %rax,(%rbx)is48 89 03(the same 3 bytes as on the slide),retisc3,push %rbxis53. Instructions are 1, 3 or 5 bytes here. x86-64 encodings run from 1 to 15 bytes, and the total, 14 bytes, matches the slide’s gcc version exactly. - The call target is unknown in the
.ofile. The 4-byte displacement is00 00 00 00because the assembler doesn’t know wherepluswill end up. The linker fills it in (Lecture 7). In the executable it ise7 ff ff ff, which read little endian (Lecture 2) is −25: the call goes 25 bytes back from the next instruction. Calls and jumps are PC-relative, which is why the same code works wherever it is loaded. - Disassemblers work on any bytes. objdump and gdb’s
disassemblereconstruct assembly from raw bytes. The slides showobjdump -d WINWORD.EXE. That is how bomblab works: you get a binary, not source, and the disassembly is the program. (Reverse engineering is restricted by many software licenses. Bomblab is designed for it.) - The arm64 build of the same C (step 6 of the demo) uses fixed 4-byte instructions,
bl(branch-and-link) instead ofcall, and keeps the return address in registerx30. It is a different ISA with the same semantics, the Lecture 1 point again.
10.4 Two spellings: AT&T and Intel syntax
The same bytes, disassembled in Intel syntax:
push rbx
mov rbx, rdx # AT&T: movq %rdx, %rbx
call 0x100000b60 <_plus>
mov qword ptr [rbx], rax # AT&T: movq %rax, (%rbx)
| Feature | AT&T (gcc, objdump, gdb, 15-213) | Intel (Intel/AMD manuals, Windows tools) |
|---|---|---|
| operand order | source, destination | destination, source |
| register prefix | %eax | eax |
| immediate prefix | $10 | 10 |
| memory operand | disp(base,index,scale) | [base + index*scale + disp] |
| size | suffix: movl | inferred, or dword ptr |
Neither is better. Just know which one you are reading: the operand order is the classic trap.
11. Can we trust the simulator?
All traces in this lecture come from x86sim.py, so it is fair to ask whether it is right. 06_crosscheck.py sends the same 4,508 inputs (edge values such as 0, −1, TMin and TMax, plus seeded random ones) to three implementations: the simulator running clang’s x86-64 assembly, the real compiled x86-64 code (executed by Rosetta 2), and the native arm64 build. Result: 0 disagreements. To make sure that result means something, the author planted a bug in the simulator, merging 32-bit register writes instead of zeroing the upper half. The cross-check then reported 548 disagreements. (Details are in the code README.)
Summary
- An ISA is the hardware/software contract. The programmer sees only
%rip, 16 registers, 4 condition codes and a byte-addressed memory, with no types, variables or arrays. The microarchitecture implements the ISA, invisibly. - x86-64 evolved from the 16-bit 8086, which explains its register names (
ax→eax→rax) and its CISC quirks. The calling convention puts arguments in%rdi, %rsi, %rdx, %rcx, %r8, %r9and the result in%rax. - Operands are immediates (
$), registers (%) or memory (parentheses).movcopies between any two kinds except memory-to-memory. The size suffixb/w/l/q= 1/2/4/8 bytes. D(Rb,Ri,S)= Mem[Rb + S·Ri + D] is array indexing in one operand, with S ∈ {1, 2, 4, 8} = sizeof(C types).leacomputes the address without touching memory, which makes it a 3-operand adder that compilers use for arithmetic like x·12 and x + 4y + 4.- Arithmetic instructions are Lecture 2’s operations.
add/sub/imuldon’t care about signedness;sar/shr,movs/movzand the comparison conditions do. - Writing a 32-bit register zeroes the upper half; writing 8 or 16 bits doesn’t. This was checked against real hardware.
cmp/testset CF ZF SF OF.jcc/setcc read them. Signed comparisons use SF, OF, ZF (g,l), unsigned ones CF, ZF (a,b). Signed less is SF ^ OF, verified on all byte pairs. Anifis a conditional goto.- The toolchain goes C → assembly (compiler) → object code (assembler) → executable (linker). Machine code is bytes; calls are PC-relative with little-endian displacements filled in by the linker. objdump/gdb disassemble any bytes.
Common pitfalls
- Operand order. AT&T is
source, destination, andsubq %rax, %rdxcomputes%rdx − %rax.cmpq %rsi, %rdicompares%rdiwith%rsi, sojlmeans%rdi < %rsi. - Treating
leaas a memory read.leaq (%rdi), %raxcopies the pointer, not*rdi. - Forgetting the 32-bit zeroing rule when reading code that mixes
%eaxand%rax, for examplemovl %eax, %eaxused purely to zero-extend. - Signed vs unsigned conditions.
ja/jbafter a comparison ofints, orjg/jlfor pointers andsize_t, means the types say something different from what you thought. - Expecting the assembly to mirror your statements. Even
-Ogreorders, merges and drops work (the dead%r8inarith), and makes tail calls. - Expecting the slides’ exact registers. Different compilers and versions choose different registers. Read by role, not by name.
Exercises
-
What am I? Write C for this function (types included):
f: movq (%rdi), %rax addq %rax, (%rsi) retAnswer
`void f(long *a, long *b) { *b += *a; }`. `%rdi` and `%rsi` are used in parentheses, so they are pointers; `q` means 8-byte data. The function also leaves `*a` in `%rax`, but since there is no meaningful return value, `void` is the natural reading. -
Addresses. With
%rax = 0x100,%rcx = 0x1,%rdx = 0x3, compute the address of:9(%rax,%rdx),260(%rcx,%rdx),0xFC(,%rcx,4),(%rax,%rdx,4). (CS:APP practice 3.1 style.)Answer
0x100 + 3 + 9 = 0x10C; 1 + 3 + 260 = 264 = 0x108; 4·1 + 0xFC = 0x100; 0x100 + 4·3 = 0x10C. -
Find the error in each instruction: (a)
movl %rax, (%rsp)(b)movw (%rax), 4(%rsp)(c)movb %al, %sl(d)movq %rax, $0x123(e)movl %eax, %rdx(f)movb %si, 8(%rbp).Answer
(a) suffix `l` (4 bytes) but `%rax` is 8 bytes. (b) memory-to-memory move. (c) there is no register `%sl` (it's `%sil`). (d) an immediate can't be a destination. (e) destination `%rdx` is 8 bytes but the suffix says 4 (use `movl %eax, %edx`, which zero-extends anyway). (f) suffix `b` but `%si` is 2 bytes. -
lea arithmetic. If
%raxholds x and%rcxholds y, what does each compute?leaq 9(%rax,%rcx,2), %rdx;leaq (%rcx,%rcx,8), %rdx;leaq 0xA(,%rax,4), %rdx.Answer
9 + x + 2y; 9y; 4x + 10. None of them reads memory or changes the flags. -
Partial registers. After
movq $-1, %rax, what is%raxfollowing each of:movl $0, %eax;movw $0, %ax;movb $0, %al;movzbl %al, %eax(starting again from −1)?Answer
0x0000000000000000 (32-bit write zeroes the top); 0xFFFFFFFFFFFF0000; 0xFFFFFFFFFFFFFF00; 0x00000000000000FF (zero-extend `%al` = 0xFF into `%eax`, and the 32-bit write clears the upper half). -
Which jumps are taken? After
movq $-1, %rdi; movq $0, %rsi; cmpq %rsi, %rdi, which ofje jl jb jg jajump?Answer
The comparison is −1 vs 0. Signed: −1 < 0, so `jl` jumps and `jg` doesn't. Unsigned: 0xFF…FF > 0, so `ja` jumps and `jb` doesn't. `je` doesn't jump. Flags: CF = 0 (no borrow, since 0xFF…FF ≥ 0), ZF = 0, SF = 1, OF = 0. -
Decode a call. The slide’s listing shows
400599: e8 f2 ff ff ff callq 400590 <plus>. Verify the target from the bytes.Answer
The instruction is 5 bytes, so the next instruction is at 0x40059e. The displacement bytes `f2 ff ff ff` read little endian are 0xfffffff2 = −14. 0x40059e − 14 = 0x400590 = `plus`. ✓ -
Explain the order. Why does clang’s
gtputxorl %eax,%eaxbeforecmpq, while gcc’s version putsmovzbl %al,%eaxaftersetg?Answer
`setg` writes only `%al`, so the upper bits of `%eax` must be cleared somehow. Clearing *before* with `xorl` is shortest, but `xorl` sets the flags, so it must come before the `cmp` whose flags `setg` reads. Clearing *after* with `movzbl` (which doesn't touch the flags) works too. Both give `%rax` = 0 or 1.
The related lab: L2 (bomblab, released with Lecture 4)
Each student gets a unique “binary bomb”: an executable with several phases, each of which reads a line of input and “explodes” unless the input is right. You have no source, only the machine code. Defusing it is pure application of Lectures 3–6. Disassemble it (objdump -d), set breakpoints in gdb (crucially, on the function that explodes the bomb), step through instructions, inspect registers (info registers) and memory (x/s, x/8xg), and reconstruct what each phase compares your input against. Everything in this lecture is a skill you will use: the argument registers, reading mov/lea/arithmetic, cmp plus jcc to find the condition that must hold, and little-endian memory dumps. These notes contain no bomb solutions (each bomb is different anyway). Recitations 2–3 introduce the gdb workflow, and x86sim.py is a gentle way to practise tracing before you meet gdb.
Further reading
- CS:APP3e §3.1–3.6.3, and the practice problems with their solutions.
- Bootcamp 2 (“Debugging & GDB”) on the course page, and the gdb cheat sheet linked from the 15-213 resources page.
- Compiler Explorer (godbolt.org): paste C, pick gcc or clang and
-Og, and see the assembly side by side. The Lecture 15 slides use it. - Intel® 64 and IA-32 Architectures Software Developer’s Manual, Vol. 2 (instruction reference), for when you need the exact definition of one instruction.
Preview of Lecture 4: Machine-level programming II, control
Lecture 3 ended with a single if. Lecture 4 builds all of C’s control flow from compares and jumps. It reviews instruction encoding and when a register holds a pointer. It shows loops in their do-while, while and for forms, the goto translations compilers use, and why a loop’s backward jump marks it. It covers conditional moves (cmov), which turn branches into data flow, and when they are unsafe. It shows switch statements compiled into jump tables with indirect jumps. Finally it starts on procedures: the run-time stack, push/pop, and how call and ret move the return address. You will need the condition-code table of §9.3 on every page.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| instruction set architecture (ISA) | 指令集架构 |
| microarchitecture | 微体系结构(微架构) |
| machine code / object code | 机器码 / 目标代码 |
| assembly language / assembler | 汇编语言 / 汇编器 |
| compiler / linker / disassembler | 编译器 / 链接器 / 反汇编器 |
| programmer-visible state | 程序员可见状态 |
| program counter (PC) / instruction pointer (%rip) | 程序计数器 / 指令指针 |
| register / register file | 寄存器 / 寄存器文件 |
| general-purpose register | 通用寄存器 |
| stack pointer (%rsp) | 栈指针 |
| calling convention / ABI | 调用约定 / 应用程序二进制接口 |
| CISC / RISC | 复杂指令集计算机 / 精简指令集计算机 |
| backward compatibility | 向后兼容 |
| operand (immediate / register / memory) | 操作数(立即数 / 寄存器 / 内存) |
| addressing mode | 寻址方式 |
| displacement / base / index / scale | 偏移量 / 基址 / 变址 / 比例因子 |
| effective address | 有效地址 |
| load effective address (lea) | 加载有效地址 |
| operand size suffix (byte / word / double word / quad word) | 操作数大小后缀(字节 / 字 / 双字 / 四字) |
| partial register | 部分寄存器 |
| zero extension / sign extension (movz / movs) | 零扩展 / 符号扩展 |
| arithmetic shift / logical shift | 算术移位 / 逻辑移位 |
| condition codes / flags register | 条件码 / 标志寄存器 |
| carry flag / zero flag / sign flag / overflow flag | 进位标志 / 零标志 / 符号标志 / 溢出标志 |
| compare (cmp) / test | 比较 / 测试 |
| conditional jump / unconditional jump | 条件跳转 / 无条件跳转 |
| indirect jump | 间接跳转 |
| tail call | 尾调用 |
| directive (assembler) | 汇编伪指令 |
| relocation / PC-relative addressing | 重定位 / PC 相对寻址 |
| AT&T syntax / Intel syntax | AT&T 语法 / Intel 语法 |
| reverse engineering | 逆向工程 |
| breakpoint (gdb) | 断点 |