CComputer Science, Built

Act III · Speaking to the Machine

Part 11 of 61

The Running Program

Degreestarts at this level47 min of film18 chaptersprerequisites: Part 6

What happens between a program's source text and a running process, and how can input become code?

The Job is rewritten as a compiler would write it: four object files with 16 holes where a name's address is not yet known, which Pebble's new linker joins into one 864-byte program that prints the same twenty words. Beside it stands a greeting program that prints 'pwned' when given 81 chosen bytes. The part follows a program's life to explain both. Data becomes bytes with an endianness, an alignment and padding; ifs, loops and a switch become branches and a jump table; calls become frames on a stack under a calling convention, traced on fact(10) and Ackermann's function. The heap is managed with free lists and boundary tags, five allocators replay a trace of 146,336 real allocations, and Knuth's fifty-percent rule is derived and set against Robson's worst case. Object files, static and dynamic linking, loading and the address space are read from this machine's own binaries. The part turns at undefined behaviour and the stack smash: an unchecked copy runs 76 bytes up the frame and overwrites the saved return address, and a canary, a no-execute stack, randomization and bounds each stop a different step. It ends with CHERI capabilities, verified compilation and what is still open about allocators.

What you need. Reading C at the level of structs, arrays and pointers helps; Part 6's assembly is used throughout.

Mathematics, ideas and history
data in memory, the stack and calling conventions, the heap and allocators, linking, loading, undefined behaviour, stack smashing
What we build or compute
Pebble's linker and loader

What you will be able to do

Degree

  • Lay out a struct with its padding, compute an array element's address, and read a word's bytes in little-endian order.
  • Write a function's prologue and epilogue under Pebble's calling convention, and draw the stack during a recursive call.
  • Explain step by step how an unbounded copy overwrites a return address, and what a canary and a no-execute stack each detect.

Graduate

  • Implement first fit with splitting and coalescing, and compare allocation policies on a trace by peak heap over peak live bytes.
  • Derive Knuth's fifty-percent rule from its balance argument, stating its assumptions.
  • Link two object files by hand: resolve the symbols, lay out the sections and patch each relocation.

Research

  • State Robson's model (online, nonmoving, bounded live storage) and explain why one adversarial replay is not a proof against every allocator.
  • Explain what spatial capabilities guarantee and what they leave to temporal safety, and what a verified compiler's theorem does and does not cover.

Industry

  • Diagnose undefined references, duplicate symbols and archive-order errors from the linker's messages, and read a backtrace.
  • Use UBSan and AddressSanitizer on a failing program, and check which stack, page and randomization defences a build actually enables.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 21 min · Graduate 45 min · Research 47 min · Industry 28 min.

  1. 0From text to a running processDegree2 min
  2. 1A program's lifeDegree2 min
  3. 2Data in memoryDegree3 min
  4. 3Control flow in machine codeDegree2 min
  5. 4The call stackDegree3 min
  6. 5Recursion, depth and tail callsDegree3 min
  7. 6The heapDegree2 min
  8. 7Five allocators, one real traceGraduate4 min
  9. 8Knuth's rule and Robson's boundGraduate3 min
  10. 9Object filesGraduate3 min
  11. 10Linking, step by stepGraduate3 min
  12. 11Dynamic linkingIndustry2 min
  13. 12Loading and the address spaceGraduate2 min
  14. 13Undefined behaviourIndustry4 min
  15. 14Smashing the stackDegree3 min
  16. 15The Job, linkedGraduate2 min
  17. 16Frontier: bounds, semantics, capabilitiesResearch3 min
  18. Recap, problems, and where this comes backAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

From text to a running processDegree2 min

Until now every Pebble program has been one file of assembly, written by hand, that the machine runs from address zero. Real programs are not like that. Here is the Job again, written the way a compiler would write it: four separate files. The main loop; the word table, now a linked list of nodes on a heap; a memory allocator; and the input and output routines. Each is assembled on its own, and each has holes in it: places where it uses a name, like lookup or alloc, whose address it cannot know. A linker fills the holes and joins the four into one program. It prints exactly the same twenty words as Part 6's program, and on the first chapter it is even a little faster.

And here is a program that does something its author never wrote. It asks for a name and says hello, copying the name into a buffer of sixty-four bytes. Give it a name, and it greets you. Give it eighty-one carefully chosen bytes, and it prints pwned, a word that appears nowhere in the program. The input ran past the end of the buffer, overwrote the address the function was going to return to, and the processor returned into the input itself. To see how, and how to stop it, we need to know how a running program is laid out in memory.

The route through this part connects representation to behavior. Bytes, alignment, arrays and typed pointers explain where data goes. Calling conventions and frames explain how separately compiled functions cooperate. A recorded allocation trace lets us compare five simulated policies under explicit accounting rules. Object files, linking and loading connect Pebble's small implementation to compiled host examples. Finally, undefined behavior and a toy stack overwrite show why bounds, lifetime rules and defense coverage matter. Each measurement belongs to its stated program, model and build.

1A program's lifeDegree2 min

Follow the build pipeline from text to a process. Source code describes the program in a language. A compiler can translate it into assembly; Part 13 builds that stage. Real toolchains may combine stages or use an intermediate representation. The assembler encodes instructions and records unresolved symbols as relocations in an object file. The linker combines objects and libraries, lays out sections and resolves references that can be fixed at link time. Dynamic references can remain for later. On Linux, the loader maps the executable's segments, arranges zero-filled memory and an initial stack, and transfers control to the entry point or dynamic linker. Runtime startup eventually calls main. Mapping need not read every file page immediately; demand paging comes in Part 32.

Follow one call through. In the source it is a call to lookup, with the word and its length. In assembly it becomes call lookup. But lookup is in another file, so the assembler cannot know how far away it is. It emits a jump-and-link with an offset of zero, and a note, a relocation: at byte eighty-eight of my code, put the distance to lookup, in the 22-bit form a jump uses. The linker places main's code at address zero and the table's code after it, so lookup lands at . It writes the distance, instructions, into the hole. Nothing else about the word changes.

2Data in memoryDegree3 min

Memory has byte addresses, while many values span several bytes. A 32-bit word occupies four bytes; endianness specifies their order. Big-endian puts the most significant byte at the lowest address. Many network protocols use this network byte order; each protocol defines its own encoding. Little-endian puts the least significant byte first. x86, the usual Arm configuration and our Pebble use it. The compiled host probe displays zero D, zero C, zero B, zero A for hexadecimal zero A zero B zero C zero D. Danny Cohen's 1980 essay borrowed the names from Gulliver's Travels. Neither order changes the value when decoded consistently; a format mismatch changes what the same bytes mean.

Alignment is part of a machine and language implementation's layout rules. Here a four-byte integer has four-byte alignment. This often makes access simpler and can avoid crossing a normally aligned cache line. Pebble requires aligned word accesses; x86 also supports many unaligned accesses. In this compiled structure, char, int, char occupy bytes: padding aligns the integer, then trailing padding aligns consecutive array elements. Reordering the integer first reduces the size to . This is a layout change, so an external binary format must agree. The two-pointer, two-integer node occupies bytes under this host ABI and sixteen on Pebble. Pointer width, alignment and ABI determine these sizes; they are not universal C constants.

An array gives indexing a regular address calculation. Take a C array with three rows and four columns of four-byte integers. Its rows are consecutive: row-major order. Fortran normally uses column-major order; other languages may instead store references to separate row objects. Within this C array, element i, j starts at base plus four times the quantity four i plus j. In C, adding one to a typed pointer advances by the size of its element, and a of i is defined through pointer addition and dereference. These operations have object-bound and lifetime rules: a pointer is more than an unrestricted permission to access any numeric address. Our basic Pebble hardware does not check an array's logical bounds; the Frontier adds a toy capability check.

3Control flow in machine codeDegree2 min

Structured control flow disappears in machine code: everything becomes a branch. Here are two pieces of the Job, in C-like source on the left and Pebble on the right. An if becomes a conditional branch around its body. And notice the trick for the range test: subtract A, and then one unsigned comparison against 26 asks both questions at once, because anything below A wraps round to a huge unsigned number. Compilers do this routinely. A loop becomes a test at the top that leaves, and a jump back at the bottom.

Dense switch cases can use a jump table. This is the actual gcc output for eight cases on our x86-64 host. Different targets, options and case patterns can produce a different lowering. One unsigned bounds comparison rejects values outside zero through seven. The code loads a signed relative offset from the table, then adds the table's base address. Computing an address with lea is not a second data-memory load. An indirect jump transfers control to the selected case. The instruction count alone does not determine latency: prediction and memory matter too. Each case ends with a jump to its function because that call is in tail position. Its result goes straight back to our caller; chapter five explains when this transformation is valid.

4The call stackDegree3 min

Separately compiled functions need a shared calling convention. This table specifies Pebble's contract. Arguments use a0 through a5, a0 returns a value, and call writes the return address into ra. A caller preserves any t-register or argument register whose old value it still needs after a call. A callee that changes s0 through s2 restores their incoming values before returning. Stack alignment must meet the convention at the required boundaries. The hardware executes instructions; interoperability depends on following the same ABI. Real conventions depend on architecture and operating system: System V AMD64 on many Unix systems, Microsoft x64, RISC-V's psABI and Apple's platform conventions. Mixing conventions requires an explicit bridge.

Here is lookup's explicit Pebble frame. The function changes s0, s1 and s2 and calls alloc, which changes ra. It subtracts sixteen from sp and saves those four registers in the new frame. Above it is main's frame, containing the input word buffer. This drawing follows this program's downward-growing stack. Before returning, lookup restores the registers and releases its frame. These ordinary calls make the stack reflect the active call chain. Leaf functions and optimized tail calls can avoid a new frame; the next chapter compares those cases.

Watch it on a recursive function, the factorial. fact of ten calls fact of nine, which calls fact of eight, and so on down to one, each call pushing a frame holding its own n and its return address. Here is the stack's depth, measured on Pebble's emulator instruction by instruction: it climbs to ten frames, then, as each call returns and multiplies, it unwinds to nothing. The result is ten factorial, and the deepest the stack went was a hundred and sixty bytes.

A debugger reads the same structure on a real machine. We compiled a C factorial on this computer, ran it under gdb, and stopped it at its deepest call, fact of one. Asked for a backtrace, gdb lists six frames: five calls of fact and main. It finds them by walking the stack. Each frame keeps its caller's frame address and its own return address, so from the stack pointer the debugger can step from frame to frame. The stack pointers it reports are thirty-two bytes apart, one frame of fact each. And the saved return addresses tell the story of the calls: four of them point to the same instruction in fact, the one just after the recursive call; the fifth returns into main, and main's into the C library that started it. That is all a backtrace is.

5Recursion, depth and tail callsDegree3 min

A small recursive definition can demand a large call tree. This two-argument Ackermann variant has three rules. As a function of both arguments it is computable but not primitive recursive: no fixed nesting of bounded loops computes all its values. That is a computability classification, not a ban on while-loop implementations. Our Pebble run for A of three, six returns 509 after 172,233 calls, with 511 frames at maximum depth. Work counts every call; depth counts only the longest active chain. A of four, two equals two to the 65,536 minus three, a value with 19,729 decimal digits. The experiment demonstrates both enormous work and stack demand; it does not compute that larger case by naive recursion.

A tail call can reuse a frame when nothing remains to do after it. This recursive call returns its result directly: no addition, cleanup or other pending operation follows it. In this Pebble example the arguments can be updated and control can jump back without saving another return address. General tail calls also have to respect calling conventions and language cleanup rules. Our ordinary sum uses bytes of stack and instructions; this hand-written tail version uses no additional stack. Scheme requires proper tail recursion. C compilers may optimize eligible calls, but the language does not guarantee it. CPython does not generally eliminate Python tail-call frames.

Stack limits depend on the process, thread and runtime. Eight megabytes is a common Linux soft limit for the main thread's stack, and one megabyte a common Windows executable default; neither is a universal constant, and thread stacks can be configured. Guard pages can make an access beyond a stack boundary fault. Large unchecked jumps can skip a guard, so stack probing and stack-clash protections matter too. CPython has a configurable recursion limit, commonly around a thousand. Java can report StackOverflowError; the available depth depends on stack size and frame sizes. Mutual recursion consumes frames just as direct recursion does. An explicit heap worklist or an iterative algorithm can control call-stack growth, but it still needs memory for pending work.

6The heapDegree2 min

The stack naturally serves data whose lifetime follows a call. Many objects have different lifetimes. The Job's word table survives the functions that add entries, and its eventual size depends on input. Dynamic allocation requests storage whose lifetime lasts until it is released. In C, malloc may fail and return null; a successful allocation does not initialize its bytes. After free, aliases no longer authorize access to that object. Our allocator handles requests online, without future knowledge. With ordinary raw pointers it cannot transparently relocate a live block: existing pointers would still name its old location. Moving collectors and handle-based systems use extra machinery to update or redirect references.

This diagram explains a classic free-list design. Divide storage into blocks with metadata recording size and allocation state. Link the free blocks into a searchable structure. To allocate, find a sufficiently large hole and split it if the remainder can form a useful free block. The request must first account for metadata and alignment. To free, coalesce adjacent free blocks. This reduces separated holes but cannot combine holes across a live object. Boundary tags record information at block boundaries so a neighbor can be found efficiently. The Python simulator represents those relationships with dictionaries and ordered lists: its eight-byte-header accounting does not charge a literal footer or reproduce native execution time.

To compare allocators honestly we need real requests, not made-up ones. So we recorded a real program: Perl, counting the words of Pride and Prejudice, which builds a hash table much like the one Part 17 will build. We wrote our own malloc that logs every request and then calls the real one, and slipped it in front of the C library, a trick chapter eleven explains. Over a hundred and forty thousand allocations, and most of them tiny: sixteen bytes or less, the size of a short word and its bookkeeping. And the live data climbs as the table fills, to about two megabytes. Now we can replay this exact sequence through allocators of our own.

7Five allocators, one real traceGraduate4 min

When several free blocks would do, which should a request get? First fit takes the first one it finds, in address order. Next fit does the same but starts each search where the last one stopped, so it does not keep re-scanning the front. Best fit takes the smallest block that fits, leaving the biggest pieces intact. Segregated fits keeps a separate list for each size class and looks in the request's own class first. And the buddy system allows only blocks whose sizes are powers of two, which makes splitting and merging almost free. We implemented all five on the same simulated heap and replayed Perl's trace through each.

These results describe one recorded trace and our simulator's rules. The ratio is peak heap size divided by peak requested live bytes. These peaks need not occur at the same instant. The ratio includes metadata, alignment, rounding and unused holes; it is not external fragmentation alone. First fit, best fit and segregated fits are near 1.13 here. Next fit is slightly larger, and buddy is about 1.82, or 82 percent above peak requested live bytes. A universal quarter-waste rule would require a request-size distribution. The other panel counts blocks examined per allocation. Next fit examines about eighteen, and segregated fits fewer than one on average because some requests extend the heap without a search. These are operation counts, not measured execution times. Size classes can reduce searching, but real performance also depends on synchronization, locality, metadata and workload. One trace does not rank every allocator for every program.

A binary buddy allocator splits power-of-two blocks. In our simulator a sixteen-byte payload needs an eight-byte header and alignment, so it occupies a thirty-two-byte block. Split 256 into 128, 64 and 32, leaving the other half free at each level. With addresses measured relative to an aligned arena, a block's buddy is its address exclusive-or its block size. This identifies its partner, not an arbitrary adjacent free block. Merge only when that partner is free and has the same size; repeat at the next level. The arithmetic is simple, but splitting, lookup and merging still have costs. A twenty-five-byte payload plus the header crosses the thirty-two-byte class and needs sixty-four bytes here. Waste within an allocated block is internal fragmentation; separated free holes contribute external fragmentation.

Production allocators combine policies with concurrency and locality mechanisms. glibc's ptmalloc uses size-organized bins, coalescing and boundary metadata, with caches and multiple arenas. Details vary by release. jemalloc, tcmalloc and mimalloc use size classes and local fast paths. Their ownership differs: some configurations use thread caches, others CPU-local or page-local structures. They are not identical designs. Large requests may use separate operating-system mappings rather than extending a contiguous brk heap, depending on policy and thresholds. Local caches can reduce shared-list contention, at a cost in retained memory and cross-thread transfer complexity. Part 10's coherence lessons explain one part of that tradeoff. Garbage-collected runtimes decide when unreachable objects can be reclaimed, while still relying on allocation machinery. Part 15 builds those mechanisms.

8Knuth's rule and Robson's boundGraduate3 min

Knuth's fifty-percent rule is a statistical balance argument under specific assumptions. Consider a roughly stationary, coalescing heap with N live blocks and uniformly selected frees. Let p be the probability that allocation splits an existing free hole. Ignore boundary and heap-growth corrections in this simplified derivation. Classify live blocks as A, B or C when zero, one or two neighbors are free. For interior holes, counting neighboring live blocks gives twice M equals B plus two C. A uniformly selected free creates a hole with probability A over N and removes one with probability C over N. Freeing B changes neither count. If allocation consumes an entire existing hole with probability one minus p, it removes that hole. Stationary expected gains and losses therefore give A minus C approximately equal to one minus p times N, and M approximately one half p N. This counts holes, not their total bytes, and is not a worst-case guarantee for arbitrary workloads.

The simulation tests whether this approximation is useful for a specified workload. We hold 200, 1,000 or 3,000 live blocks, repeatedly free one uniformly at random and allocate a uniformly chosen size from sixteen through two thousand bytes. Hole counts are averaged after warm-up; the recorded p includes the full run. The displayed holes-per-block ratios are close to p over two, with small differences from finite sampling, boundaries and heap growth. Agreement on this workload supports this approximation here. It neither validates arbitrary lifetime correlations nor predicts how many bytes those holes occupy.

Average-case balance does not prevent bad allocation sequences. Robson's classical lower bounds concern online, nonmoving allocation with a bound M on simultaneously live storage and a largest-to-smallest block-size ratio n. The leading growth is proportional to M log n; exact constants and finite corrections depend on the theorem's model. The plotted one plus half log base two n is our reference curve. Our constructed trace fills with small blocks, frees selected blocks while keeping holes too small for the next size, then doubles that size. On the implemented first-fit and best-fit policies, the measured heap follows this curve: from M to four and a half M as total block size grows from 32 to 4,096 bytes, so n is 128. The general impossibility result needs a strategy-dependent adversary and its proof. Moving objects, restricting lifetimes or changing the allocation model changes the assumptions. A compacting collector must also find or redirect references safely.

9Object filesGraduate3 min

Now the same story on a real machine. Two C files. main uses a function, count, and a variable, total, that live in the other file, and it has data of its own: a pointer to a string, and a counter private to the file. lib defines count and total, and one weak variable we will come back to. Each file is compiled on its own into an object file, and then the two are linked into a program. We compiled them on this computer and read the object files with the standard tool, readelf.

An object file is a set of named sections. Here are main dot o's. The machine code is in one section, the string constants in a read-only one. The pointer greeting gets a section of its own, because its value, the address of the string, is not known yet. The private counter goes in bss: a section that records only its size, since it starts as zeros and needs no space in the file. Then two sections of relocations, the holes and what fills them, and the symbol table with its names. The format is ELF, from AT and T's System V in 1988, used today by Linux, the BSDs and most game consoles. Pebble's object files are a toy version of it.

The symbol table says what each file offers and what it needs. main dot o defines main and greeting as global symbols, visible to other files, and the counter as local. It lists total, count and the C library's printf as undefined: used here, defined elsewhere. lib dot o defines count and total, globally, and verbose as weak. And it needs strlen: the optimizer recognised count's loop as a string length and replaced it with a call to the library. The relocations say exactly which bytes depend on which symbol, and how: here, a 32-bit distance from the instruction to the target, a call that may go through a table we meet in chapter eleven, or a whole 64-bit address for the pointer.

For this static-link example, distinguish definitions from references and binding strength. An ordinary referenced strong symbol must resolve to a definition in the final link. Unresolved weak references have special platform rules and can resolve to zero. Multiple ordinary strong definitions are an error in this example. A selected strong definition takes precedence over weak definitions. If only weak definitions exist, the linker selects one under its rules; source code should not depend on an unspecified choice among differing implementations. Leaving out lib produces undefined references; including it twice produces duplicate strong definitions. Weak defaults are one override mechanism. Dynamic symbol interposition and library-specific hooks have related but different resolution rules.

10Linking, step by stepGraduate3 min

Now our own linker, on the Job's four object files. Each file says what it defines and what it needs. main defines start and needs getc, lookup and report. The table defines lookup and report and needs alloc, putc and printnum. alloc and io need nothing. The first job is to match every need to exactly one definition. Here, every name is defined once, so each gets an address. Leave out the allocator, or include it twice, and Pebble's linker refuses, with the same two complaints this machine's linker gave.

Step two: decide where everything goes. The linker lays out all the files' code first, one after another in the order the files were given, each aligned to sixteen bytes. Then all their data. Then the bss sections, which take addresses but no bytes in the file: here, the allocator's three hundred and eighty-four kilobytes of heap. So the program file is eight hundred and sixty-four bytes, but the program in memory is almost four hundred kilobytes. Now that every section has an address, so does every symbol.

Step three: fill the holes. There are relocations across the four files. Each says where the hole is, what kind of hole, and which symbol's address belongs in it. Take one: the table code loads the address of its list head with la, which the assembler emitted as a lui and an ori with zeros. head now lives at . The linker splits that into its top twenty-two bits, , and its low ten, , and writes them into the two instructions. For a call, it writes the distance from the call to the function, counted in instructions, into the jump's 22-bit field. That is all a static linker does. Load the result and run it, and the four files behave as one program.

Real programs also link against libraries, and a static library is simply an archive of object files. Here is one we built, lib job dot a, holding two members: count dot o, and unused dot o, which carries a hundred-kilobyte table. The linker reads its inputs left to right, keeping a list of the names still undefined. After main dot o, that list holds count. In the archive it takes only the members that define a name on the list: count dot o comes in, unused dot o stays out. The program is kilobytes; listing all three object files instead gives . Now put the library first. When the linker reads it, nothing is undefined yet, so it takes nothing; then main dot o needs count, too late. Undefined reference to count. That is why, on a command line, libraries go after the files that use them.

11Dynamic linkingIndustry2 min

We compiled the same hello program with static and dynamic glibc linking. The static executable is kibibytes; the dynamic executable is . These are file sizes for this toolchain and build. The dynamic file records a dependency on libc and versioned imports, including puts. The library's code is stored separately. Our best batch-average launch measurements include process creation and execution, not just dynamic-linker work. Their difference is not an isolated measurement of relocation overhead. Read-only library pages can be shared among processes using the same library file. Replacing a compatible shared library can benefit subsequently started dynamic programs; static binaries, private copies, incompatible interfaces and already running processes need separate consideration. ldd reports the dependencies resolved in this environment.

Position-independent code can run at different load addresses. On this x86-64 example, many local references use instruction-pointer-relative addressing. References requiring dynamic resolution can use the global offset table, filled or relocated by the loader. Not every address lives in that table. A traditional external function call can pass through a procedure linkage table stub and a GOT slot. With lazy binding enabled, the first call invokes the dynamic resolver, which looks up the symbol and updates the slot. Later calls use the resolved destination. Eager binding resolves such slots at startup, and options such as no-PLT generate other call sequences.

Dynamic linking has a remarkable side effect: you can replace a library function without touching the program. Set LD_PRELOAD to a library of your own, and the dynamic linker searches it before the C library. So when Perl calls malloc, it reaches our malloc, which writes a record of the request and then calls the real one, found by asking for the next definition of the same name. That is how chapter six recorded almost two hundred and seventy-seven thousand events from an unmodified Perl. Profilers and memory-leak checkers use the same trick, and so, sometimes, does malware.

12Loading and the address spaceGraduate2 min

This is a schematic built from one Linux process's proc self maps snapshot. It orders selected mappings by virtual address: executable segments, a brk heap region, libraries and stack. Large allocations can use other mappings, and the layout is neither universal nor drawn to scale. Mapping virtual space does not mean every byte occupies physical RAM. The actual snapshot records permissions per mapping. In this build the code is executable and not writable; ordinary data and stack are writable and not executable. The schematic groups library mappings for readability, although those mappings have different permissions. Part 32 connects virtual mappings to physical pages.

The compiled probe prints five kinds of address across three runs. Here the PIE program, global, heap, stack and printf addresses vary. The executable's PIE configuration matters: non-PIE text can remain fixed while other regions move. Address-space layout randomization makes useful addresses less predictable; the PaX project introduced an influential implementation in 2001. Coverage and entropy depend on platform and configuration. Leaks, limited entropy and repeated guesses can weaken it. The final panel records whether disabling randomization with setarch was permitted. This environment may reject that request. A rejected request is not evidence of a successful fixed-address comparison, and ASLR does not itself prevent an out-of-bounds write.

The initial stack is an interface between the operating system and runtime startup. Our diagram simplifies a Unix-style arrangement to argument strings, an array of pointers ending in null, and an argument count. A real Linux initial stack also includes environment pointers and an auxiliary vector, with architecture-specific alignment. The entry routine runs before main and passes the arguments according to the platform's conventions. It is runtime startup, not a universal direct loader call to main. Pebble's small loader implements the argument-only teaching layout and supplies argc and argv in a0 and a1. Its tests check the strings and pointer array; it is not a complete implementation of Linux process startup.

13Undefined behaviourIndustry4 min

C leaves some operations undefined. Overflowing a signed integer, reading past the end of an array, dereferencing a null pointer, using memory after freeing it. For these the standard does not say the program crashes, or gives a wrong answer. It says nothing at all: any behaviour is allowed. There were reasons. Machines handled overflow differently, and checking every array access costs time. But modern optimizers draw a sharper conclusion: since a correct program never does these things, the compiler may assume they never happen, and optimize on that assumption. We measured what that does on this computer.

Signed overflow separates C semantics from a particular instruction's arithmetic. At INT_MAX, evaluating signed x plus one is undefined in ordinary C. The host instruction set has wrapping addition, but this expression is not required to compile into that instruction. gcc can return one for x plus one greater than x because every defined signed addition satisfies the comparison. The table records the loop-trip counts produced by these exact builds. Once the loop overflows, ordinary C imposes no portable trip count; optimization-level differences are observations, not language guarantees. gcc's fwrapv option supplies wrapping semantics for the relevant signed arithmetic in these examples. That implementation option changes the assumptions; it does not make unrelated bounds or lifetime violations defined.

Second, a null check. This function reads through a pointer, and only then checks whether the pointer was null. Without optimization, gcc compiles both: the load, the comparison, the early return. With optimization, the whole function is one load and a return. The reasoning: the program already dereferenced p, and dereferencing null is undefined, so p cannot be null, so the check can never fire. This is not hypothetical. In 2009 exactly this pattern in the Linux kernel's network tunnel driver let the compiler delete a null check, and the result was exploitable. Linux has been built ever since with a flag that forbids this particular optimization. The lesson of the chapter: in C, the program you meant and the program you wrote can differ, and the optimizer will take the one you wrote at its word.

The practical defence is to catch undefined behaviour as it happens. Compile with the undefined-behaviour sanitizer, and our overflowing addition stops to report it: the largest int plus one cannot be represented in type int. AddressSanitizer catches memory errors: a write just past the end of a sixty-four-byte block from malloc, a read from a block already freed, and a write past an array on the stack, the very bug of the next chapter. Each report gives the address, the line of source, and for the heap, where the block was allocated.

A typical AddressSanitizer implementation tracks addressability with shadow memory. It poisons allocation red zones and can quarantine freed blocks, delaying reuse. Detection still depends on instrumentation and what executes. In the usual one-to-eight mapping, zero means all eight bytes are addressable; positive values describe partially addressable groups, and negative poison codes describe inaccessible regions. The compiler instruments eligible accesses with checks of their shadow state and access size. Here the compiled word-count experiment takes times the plain time, and the allocation-only loop times. Those workload-specific launch-inclusive measurements are not universal slowdowns. Sanitizers are especially useful in testing and fuzzing. Clang describes the standard ASan runtime as a testing tool that is not hardened for production security. Other instrumentation choices have different tradeoffs. Passing a run does not prove memory safety.

14Smashing the stackDegree3 min

Here is the greeting program from the start of this part, on Pebble. greet makes an eighty-byte frame. At the bottom, a sixty-four-byte buffer for the name; near the top, the saved return address, the way back to the caller. It passes the buffer to gets, which, like C's gets, copies input until it sees a newline, however long that is. The copy runs upward, from the bottom of the buffer towards the saved return address. So a name longer than seventy-six bytes reaches it.

So here is the attack. Its first part is code: Pebble instructions that print the letters p w n e d and stop, bytes. Then bytes of padding, to fill the rest of the buffer and the gap: seventy-six bytes so far. Then four bytes that land exactly on the saved return address: the address of the buffer itself. gets copies all of it. greet prints its greeting, restores the return address from the stack, which is now ours, and returns, into the buffer, where our code runs. On the emulator it prints pwned. The attacker needed one fact, where the stack is, and on a machine with no randomization that never changes. This is how the Morris worm spread through the internet's fingerd servers in 1988, and Aleph One's 1996 article, Smashing the Stack for Fun and Profit, taught it to everyone.

Modern toolchains offer several defenses, with coverage determined by the build and platform. Our Pebble variants illustrate their mechanisms. A canary checked before return can detect this contiguous overwrite, provided the attacker cannot reproduce the expected value. It does not protect every memory access. A non-executable stack stops this attempt to execute injected stack bytes. It does not stop the overwrite itself. ASLR makes the injected destination harder to predict; it needs sufficient entropy and resistance to leaks. A bounds-carrying pointer can reject the first write outside this buffer; the Frontier adds a miniature check. These defenses address different failure modes. Code-reuse attacks can use executable fragments already present, including return-oriented programming. Layered mitigation complements bounds and lifetime safety; no universal claim that every binary enables all of these is warranted.

15The Job, linkedGraduate2 min

Here is the Job written the way a compiler would write it. main reads letters into a buffer in its own stack frame. The table is a linked list of sixteen-byte nodes on the heap, kept in the order words were first seen, so ties break exactly as before. The allocator just bumps a pointer through three hundred and eighty-four kilobytes of bss, never freeing anything, which is all the Job needs. And the input and output routines include printnum, which keeps its digits in a small buffer in its frame. Each node holds a pointer to the next, a pointer to the word's letters, its length and its count. And every function obeys the calling convention of chapter four.

How does it compare with Part 6's single hand-written file? On a paragraph, the first chapter of Pride and Prejudice, and twenty thousand bytes, the output is identical every time. On the paragraph, version one is a few percent slower: every byte of input now costs a function call and return. On longer texts it is faster, by eleven percent at twenty thousand bytes, because following a next pointer takes one instruction fewer per entry than counting through an array. The stack never went deeper than three hundred and twenty bytes. Structure, it turns out, costs almost nothing here. But the algorithm has not changed: each word still pays for a scan of the vocabulary. Part 13's compiler will write this program automatically, and Act Four will change the algorithm.

16Frontier: bounds, semantics, capabilitiesResearch3 min

Ordinary address arithmetic does not automatically enforce object bounds. CHERI associates capabilities with address, bounds, permissions and a protected validity tag. This diagram is conceptual; encodings vary. Morello uses 128-bit capabilities plus a tag, with compressed bounds rather than these literal separate fields. Capability-based accesses check authority. Derivation cannot increase authority beyond what is held, although the cursor can move within the rules; bounds need not become strictly smaller on every operation. Hybrid systems can also retain ordinary pointers. Arm's Morello prototype arrived in 2022. Pebble's miniature model attaches exact sixty-four-byte bounds to greet's buffer pointer. It traps this attack at the sixty-fifth byte and still greets Ada. Spatial bounds alone do not generally solve use-after-free: temporal safety needs additional mechanisms.

Compiler correctness requires an explicit source semantics and a stated proof boundary. The theorem connects behaviors in source and target languages, including how undefined source behavior limits the guarantee. CompCert proves semantic preservation for its verified compilation passes and supported C subset. Cerberus explores executable models of C, including the difficult interactions of pointers, objects and real implementation practice. Pointer provenance asks which storage instance a pointer may access, even when numeric addresses coincide. Research compares formal guarantees, compatibility with existing code and optimizer behavior. We should name the particular semantics and version before claiming that all three agree.

Allocator research depends strongly on the model and workload. Robson's lower bounds and policy-specific upper and lower bounds require their own hypotheses; our eight-phase trace establishes only the displayed measurements for our implementations. Johnstone and Wilson's 1998 study found low fragmentation for selected policies and measured programs. Our Perl replay is one additional workload, and its peak ratio includes headers and alignment. Neither establishes that all programs stay near the average. Lifetime correlations, size distributions, locality and concurrency help explain behavior; finding useful predictive models remains a research question, rather than a claim that no model exists. Temporal safety is another challenge. Quarantines delay reuse, type segregation limits some reuse patterns, and checked smart-pointer schemes protect selected references. Each has coverage and overhead limits; a spatial capability by itself does not revoke every stale reference.

Recap, problems, and where this comes backAll tracks2 min

We followed a program from source to a process. The diagrams connected byte layout and pointer arithmetic to branches, frames and calling conventions. Five simulated allocators replayed one recorded Perl trace. Knuth's balance argument matched that workload approximately, while an adversarial trace illustrated the worst-case question without proving a general theorem. Pebble gained a linker and loader; compiled host examples exposed object sections, dynamic references and virtual mappings. Finally, a toy stack overwrite showed how distinct defenses interrupt different parts of an attack.

These mechanisms return throughout the course. Part 13 builds a compiler that emits structured calls and references. Part 15 builds runtime reclamation, including moving collectors whose assumptions differ from nonmoving allocation. Part 31 adds exceptional control flow, signals and system calls, and Part 32 connects virtual addresses to pages. Part 54 studies program and compiler correctness under explicit semantics. Part 55 studies code-reuse attacks and the trust placed in our tools.

In practice, inspect a backtrace with the build's symbols and unwinding information. Use sanitizers and memory-checking tools to find exercised classes of errors, while recognizing their instrumentation and coverage limits. Read linker diagnostics separately from compiler diagnostics: undefined references, duplicate symbols and archive ordering are concrete clues. Benchmark allocator choices on representative workloads before claiming a speedup. Check which stack, page, randomization and control-flow defenses your platform and build actually enable; defaults and coverage vary.

The notes give six exercises and worked guidance. The fifth implements an allocator in Pebble assembly and compares a trace replay under identical header, alignment and splitting rules. The research exercise asks you to state a precise nonmoving-allocation model, locate the relevant upper and lower bounds, and explore small adversarial cases. A simulation can reveal a counterexample or motivate a conjecture; it cannot establish a universal worst-case theorem by itself.

Next time. To build Part 13's compiler we first need the theory of reading text: regular expressions, finite automata and grammars, and the parsers built from them. Part 12, Languages and Automata.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. The calling convention and object files are what Part 13's compiler emits; reclamation and moving collectors are built in Part 15; exceptional control flow, signals and system calls come in Part 31 and pages behind the address space in Part 32; compiler correctness returns in Part 54, and the stack smash grows into code-reuse attacks in Part 55.

Key results

The part's results in one place, for revision.

Alignment\(\displaystyle \text{offset}(f)\equiv 0 \pmod{\text{align}(f)},\qquad\allowbreak \text{size}\equiv 0 \pmod{\max_f \text{align}(f)}\)
Row-major arrays\(\displaystyle \&a[i][j]=\text{base}+(i\cdot\text{cols}+j)\cdot\text{size}\)
Knuth's fifty-percent rule\(\displaystyle \text{holes}\ \approx\ \tfrac12\,p\,N\)
Robson's worst case\(\displaystyle \text{heap}\ \propto\ M\log n,\qquad\allowbreak n=\frac{\text{largest block}}{\text{smallest block}}\)
A buddy's address\(\displaystyle \text{buddy}(a)=a\oplus\text{size}\)
Relocating la on Pebble\(\displaystyle \text{lui}\leftarrow\lfloor S/2^{10}\rfloor,\qquad\allowbreak \text{ori}\leftarrow S \bmod 2^{10}\)

Try it

Lab 11 · Holes in the heap, and 81 bytes on the stack

Keep N blocks live in Pebble's first-fit heap, free one at random and allocate a new one thousands of times, and compare the number of holes with Knuth's fifty-percent rule, p N / 2. Then feed the linked greeting program its 81-byte attack, and run it again with a stack canary and with a no-execute stack.

Figure produced by Lab 11: Holes in the heap, and 81 bytes on the stack
Produced by the lab below, seed 0, in 0.4 s.
python -m videos.cs.labs 11 needs numpy, scipy, matplotlib · download lab11.py · source on GitHub
N = 200 live blocks: holes         87 measured   p N / 2 = 86   (p = 0.86)
N = 1000 live blocks: holes        406 measured   p N / 2 = 401   (p = 0.80)
greet, given 'Ada'                 'hello, Ada\nbye\n'
greet, given the 81-byte attack    prints 'pwned'
the same, with a no-execute stack  execute from the stack at 0xfff90: no-execute fault
the same, with a canary            *** stack smashing detected ***

With random frees, a first-fit heap settles at about p N / 2 holes; the copy that runs 76 bytes past a buffer's start reaches the saved return address, and each defence stops a different step of the attack.
The code (104 lines; it asserts its own result)
"""Lab 11: count the holes in a first-fit heap against Knuth's rule, then smash Pebble's stack and stop it twice."""

from videos.coursekit import labs

import numpy as np

from explainer.cs.pebble import heap as H
from explainer.cs.pebble import smash
from explainer.cs.pebble.asm import assemble

TITLE = "Holes in the heap, and 81 bytes on the stack"
GOAL = ("Keep N blocks live in Pebble's first-fit heap, free one at random and allocate a new one thousands of times, "
        "and compare the number of holes with Knuth's fifty-percent rule, p N / 2. Then feed the linked greeting "
        "program its 81-byte attack, and run it again with a stack canary and with a no-execute stack.")
TASKS = [
    "Use H.BestFit instead of H.FirstFit. Does p change, and does the hole count still follow p N / 2?",
    "Free the oldest block instead of a random one (live.pop(0)). Which assumption of the rule breaks, and what happens to the holes?",
    "Shorten the attack by one byte and lengthen it by four. Which inputs still print 'pwned', and why?",
]


class Counting(H.FirstFit):
    """First fit that records how each request was met: a hole split, a hole taken whole, or the heap extended."""

    def __init__(self):
        super().__init__()
        self.splits = self.whole = self.grown = 0

    def after_split(self, i):
        self.splits += 1

    def after_take(self, i):
        self.whole += 1

    def malloc(self, n):
        top = self.top
        a = super().malloc(n)
        self.grown += self.top != top
        return a


def churn(n_live, steps, rng):
    heap = Counting()
    live = [heap.malloc(int(s)) for s in rng.integers(16, 2001, n_live)]
    heap.splits = heap.whole = heap.grown = 0
    sizes, picks, holes = rng.integers(16, 2001, steps), rng.random(steps), []
    for k in range(steps):
        heap.free(live.pop(int(picks[k] * len(live))))  # a uniformly chosen live block dies
        live.append(heap.malloc(int(sizes[k])))
        holes.append(len(heap.addrs))
    p = heap.splits / (heap.splits + heap.whole + heap.grown)
    return np.array(holes), p


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    traces = {}
    for n_live in (200, 1000):
        holes, p = churn(n_live, 15000, rng)
        mean = holes[5000:].mean()  # after warm-up
        traces[n_live] = (holes, p)
        lab.row(f"N = {n_live} live blocks: holes", f"{mean:.0f} measured   p N / 2 = {p * n_live / 2:.0f}   (p = {p:.2f})")
        assert abs(mean / n_live - p / 2) < 0.03, "Knuth's rule: about p N / 2 holes"

    exe = smash.build()
    attack = smash.exploit(exe)
    benign, owned = smash.run(exe, b"Ada\n"), smash.run(exe, attack)
    nx = smash.run(exe, attack, nx=True)
    guarded = smash.build(canary=True)
    caught = smash.run(guarded, smash.exploit(guarded))
    lab.row("greet, given 'Ada'", repr(benign["output"]))
    lab.row(f"greet, given the {len(attack)}-byte attack", "prints 'pwned'" if "pwned" in owned["output"] else "survives")
    lab.row("the same, with a no-execute stack", nx["fault"] or "no fault")
    lab.row("the same, with a canary", caught["output"].strip().splitlines()[-1])
    assert benign["output"] == "hello, Ada\nbye\n" and "pwned" not in benign["output"]
    assert len(attack) == 81 and owned["output"].endswith("pwned") and "bye" not in owned["output"]
    assert nx["fault"] and "no-execute" in nx["fault"] and "pwned" not in nx["output"]
    assert "stack smashing detected" in caught["output"] and "pwned" not in caught["output"]
    lab.note = ("With random frees, a first-fit heap settles at about p N / 2 holes; the copy that runs 76 bytes "
                "past a buffer's start reaches the saved return address, and each defence stops a different step "
                "of the attack.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    for n_live, color in ((200, labs.BLUE), (1000, labs.GOLD)):
        holes, p = traces[n_live]
        ax[0].plot(holes / n_live, color=color, lw=0.8, label=f"N = {n_live}: holes / N")
        ax[0].axhline(p / 2, color=color, ls="--", lw=1.2, label=f"p / 2 = {p / 2:.2f}")
    ax[0].set(title="First fit under random frees: holes per live block", xlabel="free-and-allocate steps", ylabel="holes / N",
              ylim=(0, 0.6))
    ax[0].legend(ncols=2, loc="lower right")
    code = len(assemble(smash.SHELLCODE).image)  # the injected instructions; the rest is padding
    parts = [("buffer (64 bytes)", 0, 64, labs.BLUE), ("gap", 64, 72, labs.GREY), ("canary slot", 72, 76, labs.GREEN),
             ("saved return address", 76, 80, labs.RED)]
    for name, lo, hi, color in parts:
        ax[1].barh(1, hi - lo, left=lo, color=color, height=0.5, label=name)
    ax[1].barh(0, code, left=0, color=labs.PURPLE, height=0.5, label=f"attack: {code} bytes of code")
    ax[1].barh(0, smash.RA_OFF - code, left=code, color=labs.SAND, height=0.5, label="attack: padding")
    ax[1].barh(0, 4, left=smash.RA_OFF, color=labs.ORANGE, height=0.5, label="attack: the buffer's address")
    ax[1].set(title="greet's 80-byte frame, and the input copied over it", xlabel="byte offset from sp", yticks=[0, 1],
              yticklabels=["input", "frame"], ylim=(-0.6, 3.4), xlim=(0, 80))
    ax[1].legend(ncols=2, loc="upper center")
    lab.fig = fig
    return lab

Now change it

  1. Use H.BestFit instead of H.FirstFit. Does p change, and does the hole count still follow p N / 2?
  2. Free the oldest block instead of a random one (live.pop(0)). Which assumption of the rule breaks, and what happens to the holes?
  3. Shorten the attack by one byte and lengthen it by four. Which inputs still print 'pwned', and why?

Problems, with solutions

Try each problem before opening its solution.

  1. Padding. On x86-64, how big is struct { char a; double b; short c; char d; }? Reorder it to make it as small as possible.

    Solution

    a at 0, seven bytes of padding, b at 8, c at 16, d at 18, then padding to a multiple of 8: 24 bytes. Largest first, { double b; short c; char a; char d; }: 8 + 2 + 1 + 1 = 12, padded to 16.

  2. A frame. Write the prologue and epilogue of a Pebble function that calls another function and uses s0 and s1. How big is its frame?

    Solution

    It must save ra (the call overwrites it) and both s-registers: 12 bytes, rounded up to keep sp 16-byte aligned: 16 bytes.

    f:   addi sp, sp, -16        lw   s1, 4(sp)
         sw   ra, 12(sp)         lw   s0, 8(sp)
         sw   s0, 8(sp)          lw   ra, 12(sp)
         sw   s1, 4(sp)          addi sp, sp, 16
         ...                     ret
    
  3. Holes. A first-fit heap holds 1,000 blocks, and 80% of allocations split their hole. About how many holes?

    Solution

    Knuth's rule: ½ p N = ½ × 0.8 × 1,000 = about 400, assuming uniformly selected frees, stationarity and negligible boundary/growth effects. This estimates hole count, not wasted bytes. The displayed 399 is a finite-sample mean for this workload.

  4. A relocation. la t0, sym with sym at 0x12345: what do the immediates become?

    Solution

    0x12345 = 74,565. lui takes the top 22 bits, 74,565 >> 10 = 72 (0x48); ori the low 10, 74,565 & 1023 = 837 (0x345). Check: 72 × 1024 + 837 = 74,565.

  5. Build: an allocator in Pebble. Write first-fit malloc and free with boundary tags in Pebble assembly, replay Perl's first 10,000 events on the emulator, and compare with heap.py.

    Solution

    Solution sketch. Keep each block's size, with the low bit as the in-use flag, in a header word and in a footer word; keep free blocks in an address-ordered doubly linked list (next and previous pointers in the free block's payload). malloc walks the list from its head and splits when the remainder is at least 32 bytes; free reads the footer just before its header to find the previous block, and the header just after its end to find the next, merging with either if free. Drive it from a tape of events: generate the tape from heap.events(...)[:10000] as 32-bit records (op, id, size), and keep a table of id → pointer in the Pebble program's .bss. With the same header, alignment and split rules as heap.FirstFit, the high-water mark should match heap.py's exactly; any difference is a bug in one of them. The emulator runs about a million instructions a second, so the replay takes a few seconds.

  6. ★ Research: define the allocation model before comparing bounds. State the live-storage bound, minimum allocation unit, maximum block size, online information and whether live blocks may move. Compare Robson's 1971/1974 general bounds with his 1977 policy-specific first-fit/best-fit results. What does the chapter's eight-phase trace actually establish?

    Worked guidance. The replay establishes measured behavior for two particular implementations on one trace. Its curve is not a proof of a universal finite formula. Enumerate tiny legal traces while checking live-storage limits, block disjointness and units; a counterexample can disprove a proposed upper bound, while an apparent pattern still needs proof. Separate general lower bounds from policy-specific upper bounds and account for finite-size corrections. Moving or fragmented allocation and constrained lifetimes change the model.

Notes and sources

Glossary

源代码 source code · 编译器 compiler · 汇编器 assembler · 链接器 linker · 装载器 loader · 进程 process · 字节序 endianness · 大端 / 小端 big-endian / little-endian · 对齐 alignment · 填充 padding · 行主序 row-major order · 指针运算 pointer arithmetic · 跳转表 jump table · 调用约定 calling convention · 调用者保存 / 被调用者保存 caller-saved / callee-saved · 栈帧 stack frame · 活动记录 activation record · 序言 / 尾声 prologue / epilogue · 尾调用 tail call · 保护页 guard page · 堆 heap · 空闲链表 free list · 边界标签 boundary tag · 合并 coalescing · 首次适配 first fit · 下次适配 next fit · 最佳适配 best fit · 分离适配 segregated fits · 伙伴系统 buddy system · 内部碎片 / 外部碎片 internal / external fragmentation · 五十百分比法则 fifty-percent rule · 目标文件 object file · 节 section · 符号表 symbol table · 重定位 relocation · 强符号 / 弱符号 strong / weak symbol · 静态链接 / 动态链接 static / dynamic linking · 位置无关代码 position-independent code · 全局偏移表 GOT · 过程链接表 PLT · 延迟绑定 lazy binding · 插桩替换 interposition · 地址空间 address space · 地址空间布局随机化 ASLR · 未定义行为 undefined behaviour · 栈溢出攻击 stack smashing · 栈金丝雀 stack canary · 不可执行栈 no-execute stack · 返回导向编程 return-oriented programming · 能力 capability · 指针来源 pointer provenance

Sources

Canon. Books: Bryant & O'Hallaron, Computer Systems: A Programmer's Perspective, 3rd ed., ch. 3, 7, 9; Levine, Linkers and Loaders (2000); Knuth, The Art of Computer Programming, vol. 1, §2.5 (dynamic storage allocation, boundary tags, the fifty-percent rule); the System V Application Binary Interface with its x86-64 and RISC-V supplements; the ISO C standard (undefined behaviour, annex J).

Papers: Knowlton, "A fast storage allocator" (1965); Robson, "An estimate of the store size necessary for dynamic storage allocation" (1971) and "Bounds for some functions concerning dynamic storage allocation" (1974); Robson, "Worst case fragmentation of first fit and best fit storage allocation strategies" (1977); Cohen, "On holy wars and a plea for peace" (1980); Gingell, Lee, Dang & Weeks, "Shared libraries in SunOS" (1987); Spafford, "The Internet worm program: an analysis" (1988); Wilson, Johnstone, Neely & Boles, "Dynamic storage allocation: a survey and critical review" (1995); Aleph One, "Smashing the stack for fun and profit", Phrack 49 (1996); Johnstone & Wilson, "The memory fragmentation problem: solved?" (1998); Shacham, "The geometry of innocent flesh on the bone: return-into-libc without function calls" (2007).

Recent. Leroy, "Formal verification of a realistic compiler", CACM (2009); Wang, Zeldovich, Kaashoek & Solar-Lezama, "Towards optimization-safe systems: analyzing the impact of undefined behavior" (2013); Watson et al., "CHERI: a hybrid capability-system architecture for scalable software compartmentalization", IEEE S&P (2015); Memarian et al., "Into the depths of C: elaborating the de facto standards", PLDI (2016) and "Exploring C semantics and pointer provenance", POPL (2019); Arm, the Morello prototype (2022).

About this partfrom its README

Part 11 of a sixty-one-part course in computer science (see the series plan and the syllabus), the first part of Act III, Speaking to the Machine. One program, followed from source text to a running process: how its data becomes bytes, its control flow branches, its calls a stack and its names addresses; how the heap is managed; how object files are linked and loaded; and how one unchecked copy turns input into code. Pebble gains an object-file format, a linker and a loader (explainer/cs/pebble/link.py), a heap simulator with five allocators (heap.py), the Job rewritten as four linked files with frames and a heap list (jobv1.py), and a stack-smash demonstration with its defences (smash.py), all tested in tests/test_cs11_link.py and tests/test_cs11_running.py. This machine's side is measured by compiling small C programs and reading them with readelf; every number is computed in compute.py.

  • From text to a running process. The Job as four object files with 16 holes, linked into 864 bytes, printing the same twenty words as Part 6's program; a greeting program that prints "pwned" when given 81 chosen bytes.
  • 1. A program's life. Compiler, assembler, linker, loader; one call lookup followed from source to a patched jump.
  • 2. Data in memory. Endianness measured (0d 0c 0b 0a), Cohen (1980); alignment and padding compiled here (12 bytes against 8 for the same fields; the Job's node 24 bytes on x86-64, 16 on Pebble); row-major arrays; pointer arithmetic.
  • 3. Control flow. Ifs and loops as branches, the unsigned range test; a dense switch compiled by gcc -O2 into a jump table, each case a tail call through the PLT.
  • 4. The call stack. Pebble's calling convention (a0–a5, ra, caller-saved t0–t3, callee-saved s0–s2, 16-byte sp); lookup's frame; fact(10) frame by frame on the emulator (10 frames, 160 bytes); gdb's backtrace of a C factorial on this machine, its frames 32 bytes apart and their saved return addresses.
  • 5. Recursion, depth and tail calls. Ackermann on Pebble: A(3, 6) = 509 in 172,233 calls, 511 frames deep; a tail call made a jump (1,616 bytes of stack and 1,013 instructions against 0 and 409); guard pages and limits.
  • 6. The heap. malloc and free; free lists, Knuth's boundary tags, coalescing; a real trace: Perl counting Pride and Prejudice, 146,336 allocations recorded with an LD_PRELOAD interposer, nearly all of 16 bytes or less, peaking near 2 MB live.
  • 7. Five allocators. First fit, next fit, best fit, segregated fits and the buddy system on that trace: fragmentation 1.13, 1.14, 1.13, 1.13 and 1.79; 3.3, 16.7, 2.1, 0.9 and 2.2 blocks examined per request; the buddy system (Knowlton 1965); ptmalloc, jemalloc, tcmalloc, mimalloc.
  • 8. Knuth's rule and Robson's bounds. Derive the approximate hole-count relation under stationary, uniformly random deletion and immediate coalescing, neglecting boundary/growth effects. The stored p uses the full run while hole averages use the post-warm-up window. Replay an eight-phase adversarial trace on first fit and best fit: total block sizes 32–4,096 bytes (ratio 128), heap/M 1–4.5. The matching reference curve is an illustration, not an exact finite universal theorem or a proof against every allocator.
  • 9. Object files. ELF sections, symbols and relocations of two C files compiled here; gcc turning a counting loop into strlen; strong and weak symbols; the linker's errors.
  • 10. Linking, step by step. Pebble's linker on the Job: resolution, layout (text, data, 384 KB of bss), the 16 relocations patched; static archives and link order (main.o libjob.a takes only count.o, 16 KB against 112 KB; libjob.a main.o fails with an undefined reference).
  • 11. Dynamic linking. This host's hello binaries occupy 741 KiB static and 16 KiB dynamic. Recorded best batch-average launches are 0.63 and 0.90 ms, including process creation/execution; the difference does not isolate linking. PIC includes PC-relative references and GOT indirection. The PLT diagram illustrates optional lazy binding; eager binding and compiler/linker options change it. Interposition records the Perl trace.
  • 12. Loading and the address space. /proc/self/maps; ASLR across three PIE runs; setarch -R is rejected in this environment, so no fixed-address result is claimed; argv and argc on the stack, as Pebble's loader builds them.
  • 13. Undefined behaviour. x + 1 > x folded to 1; a wrapping loop running 3 times at -O0 and 2 at -O2; a null check deleted at -O2; the 2009 Linux TUN bug; UBSan and AddressSanitizer catching an overflow, a heap overrun, a use after free and a stack overrun; red zones, quarantine and shadow memory; workload-specific overhead measured here. The shadow check handles partial groups; the standard ASan runtime is a testing tool, not a production-hardened security runtime.
  • 14. Smashing the stack. The frame; an 81-byte toy Pebble input (72 code bytes, padding, a saved address and newline); the Morris worm (1988), Aleph One (1996); a canary, a no-execute stack, randomization, bounds; return-oriented programming.
  • 15. The Job, linked. Version 1 against version 0: identical output; +4% on a paragraph, −6% on chapter 1, −11% on 20,000 bytes; 320 bytes of stack at most.
  • 16. Frontier: bounds, semantics, capabilities. A CHERI-style capability machine traps the attack on its 65th byte; CompCert, Cerberus and pointer provenance; open questions about allocators' worst cases and use-after-free.
  • Recap, where this comes back, in practice, problems.
What is computed and builtInterpretation and measurement scope

The numerical cache is a recorded experiment, not a cross-platform promise. All twenty original JSON payloads are preserved during this polish. Binary sizes are KiB (1,024 bytes); heap charts use decimal MB. Host instruction selection, addresses, launch/sanitizer times and ABI layout belong to the recorded compiler/platform. ASLR is not a bounds check. The capability model is a small spatial check, not complete CHERI or temporal revocation. CompCert's semantic-preservation theorem has a supported language, verified passes and trusted boundaries.

Heap ratio means peak heap / peak requested live bytes, including headers, alignment, rounding and holes; the two peaks need not be simultaneous. Blocks examined per allocation are simulated operations, not elapsed speed. Boundary tags are a conceptual design; the Python simulator uses dictionaries/lists and does not charge a literal footer. Buddy payload requests include the 8-byte header and 16-byte alignment before power-of-two rounding: 16 bytes needs a 32-byte block, while 25 or 30 bytes needs 64. The diagrams and narration now agree.

The startup stack drawing intentionally omits Linux environment pointers and auxiliary-vector details. The GOT/PLT view shows one lazy-binding path. Runtime, compiler, library and defense behavior depends on configuration; passing a finite simulator or sanitizer run is not a proof of correctness for all programs.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. A program's life: compiler, assembler, linker, loader, process; one call followed from source to a patched jump.
  2. Data in memory: bytes and words; endianness (Cohen 1980, after Swift), measured here; alignment and padding (struct sizes measured); row-major arrays; pointers and pointer arithmetic.
  3. Control flow in machine code: conditionals and loops as branches (the unsigned range test); a switch compiled by gcc into a jump table, its cases ending in tail calls.
  4. Procedures: the call stack, activation records, Pebble's calling convention (caller- and callee-saved registers); fact(10)'s stack depth traced instruction by instruction; gdb's backtrace walking the same frames on this machine.
  5. Recursion: Ackermann's function on Pebble (A(3, 6): 172,233 calls, 511 frames); tail calls (1,616 bytes of stack against none); guard pages, recursion limits, mutual recursion.
  6. The heap: malloc and free; free lists, boundary tags (Knuth 1968), coalescing; a real trace (Perl counting Pride and Prejudice, 146,336 allocations, recorded through LD_PRELOAD).
  7. Five allocators replayed on that trace: first, next and best fit, segregated fits, buddies (Knowlton 1965); fragmentation and search cost; internal against external fragmentation; ptmalloc, jemalloc, tcmalloc, mimalloc.
  8. Knuth's fifty-percent rule, proved by counting and checked by simulation; Robson's worst-case bound (1971, 1974), with its adversary run against first fit.
  9. Object files: ELF sections (.text, .data, .bss, relocations), symbol tables, strong and weak symbols, read from real object files with readelf; the linker's rules.
  10. Linking, step by step with Pebble's linker: symbol resolution, layout, relocation; static archives and why link order matters (measured).
  11. Static against dynamic linking (measured); position-independent code (GOT and PLT, lazy binding); shared libraries; interposition.
  12. Loading: /proc/self/maps, ASLR measured over three runs, _start, argv on the stack.
  13. Undefined behaviour: why it exists, and what optimizers do with it (signed overflow; a deleted null check, the 2009 TUN driver); sanitizers (UBSan, AddressSanitizer) catching four bugs, shadow memory, and their cost measured.
  14. The stack smash (the Morris worm 1988; Aleph One 1996) on our Pebble stack, and four defences built and run: canary, no-execute stack, randomization, bounds. Part 55 picks this up.
  15. The Job, version 1: four assembly files linked by Pebble's linker, frames and a heap list, against Part 6's single file.
  16. Frontier: bounds, semantics, capabilities. CHERI capabilities (Watson et al. 2015; Arm Morello 2022), with a miniature on Pebble trapping the smash at the 65th byte; CompCert (Leroy 2006 onward), Cerberus (Memarian et al. 2016) and pointer provenance; the exact worst case of first and best fit, why real programs fragment so little (Johnstone and Wilson 1998), use-after-free defences.
  17. Outro. (Exceptional control flow, previewed in the original plan, moves wholly to Part 31.)

Computed: Pebble's linker and loader; first-fit, best-fit and segregated allocators on traces, with fragmentation; stack-depth traces. Visuals: memory as a tall strip, the stack growing down and the heap up; frames pushing and popping; relocation arrows patching addresses; free lists as chains. In practice: debugging with gdb and lldb, reading compiler output, ABI and linker errors, the exploit mitigations every binary ships with. Reading: Bryant & O'Hallaron ch. 3, 7, 9; Levine, Linkers and Loaders; Wilson et al. 1995 (the allocation survey); Knuth, TAOCP 1 §2.5; Aleph One 1996; the System V ABI.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 填充。 在 x86-64 上,struct { char a; double b; short c; char d; } 有多大?重排字段使它尽可能小。

    解答

    a 在 0,七个字节的填充,b 在 8,c 在 16,d 在 18,再填充到 8 的倍数:24 字节。按从大到小排, { double b; short c; char a; char d; }:8 + 2 + 1 + 1 = 12,填充到 16。

  2. 一个栈帧。 写出一个调用了别的函数、并使用 s0 和 s1 的 Pebble 函数的序言和尾声。它的帧有多大?

    解答

    它必须保存 ra(调用会覆盖它)和两个 s 寄存器:12 字节,为保持 sp 16 字节对齐向上取整:16 字节。 代码见上面英文部分。

  3. 空洞。 一个首次适配的堆里有 1,000 个块,80% 的分配会切开它的空洞。大约有多少个空洞?

    解答

    克努特法则:½ p N = ½ × 0.8 × 1,000 = 约 400,前提是均匀选择释放、近似平稳,且忽略边界与堆扩展。它估计空洞个数而非浪费字节;399 是该负载下的有限样本均值。

  4. 一次重定位。 sym 在 0x12345 时,la t0, sym 的立即数变成什么?

    解答

    0x12345 = 74,565。lui 取高 22 位,74,565 >> 10 = 72(0x48);ori 取低 10 位,74,565 & 1023 = 837(0x345)。验算:72 × 1024 + 837 = 74,565。

  5. 动手:Pebble 上的分配器。 用 Pebble 汇编写出带边界标签的首次适配 malloc 和 free,在模拟器上重放 Perl 的 前 10,000 个事件,并与 heap.py 比较。

    解答

    解答提要。 把每个块的大小(最低位作为在用标志)放在头部字和尾部字里;空闲块按地址顺序串成双向链表(next 和 prev 指针放在空闲块的载荷里)。malloc 从表头开始走,剩余至少 32 字节时切开;free 读自己头部之前的尾部字找到前一个块, 读自己末尾之后的头部字找到后一个块,空闲就合并。用事件带驱动它:把 heap.events(...)[:10000] 生成 32 位记录 (操作、编号、大小)的带子,在 Pebble 程序的 .bss 里放一张编号 → 指针的表。头部、对齐和切分规则与 heap.FirstFit 相同的话,最高水位应当与 heap.py 完全一致;任何差别都是其中一方的错误。

  6. ★ 研究:比较界之前先定义分配模型。 明确活动存储上限、最小分配单位、最大块大小、在线信息, 以及是否允许移动活动块。比较罗布森1971/1974年的一般界与1977年的首次适配、最佳适配专门结果。 本章八阶段轨迹实际证明了什么?

    解答

    解答指导。 重放只确立两种具体实现对一条轨迹的测量,不是普遍有限公式的证明。枚举微小合法轨迹, 检查活动存储上限、块不重叠及单位。反例能推翻候选上界,而观察到规律仍需证明。区分一般下界与特定策略 上界,并计入有限大小修正。允许移动、允许请求分片或限制生命周期,都会改变模型。

Build the film

python -m videos.cs.cs11.compute        # the part's numbers, into .cache/cs11
python tools/build.py cs11                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs11 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs11. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs11.compute           # every number in the part (about a minute; needs gcc, readelf, perl)
python tools/build.py cs11 -q l            # a 480p preview
python tools/build.py cs11                 # 1080p

The measurements (layout, switch, elf, dynamic, aslr, maps, ub) belong to the computer and compiler that run them; heap records its trace once into .cache/cs11/perl.mtrace and replays it.