← TextbooksCortex-M Replay: Beginner Textbook
Contents
Beginner textbook / embedded systems lab notebook

Deterministic Cortex-M Replay

Start with the byte. Follow one firmware race from C, through a host emulator and checked trace bytes, into a synchronous FIFO, then learn why clock-domain crossing and physical hardware require stronger evidence. Claims stay bound to the model, simulation, P&R, or board evidence that supports them.

ordered path: observe → record → validate → replay → capture → verify → hand off

Start here: the mental model

This is a small experiment, not a whole-chip simulator. Firmware is compiled into an ELF. Unicorn executes one host-controlled instruction at a time. The recorder applies an event at point n, steps once, and stores a selected 17-field snapshot. A DTRC stream carries events. RTL transports opaque bytes; it does not parse the trace.

Prerequisites

You need only C variables and loops, binary/hex arithmetic, functions, and the idea of a clock edge. The book introduces valid/ready, FIFO pointers, Gray code, and SystemVerilog before using them. ARM exception names and CRCs are explained when needed.

Vocabulary

Model is executable software abstraction. Simulation runs RTL behavior in a testbench. Synthesis maps RTL to device resources. P&R places and routes that mapping and estimates timing. Hardware evidence is a board/measurement result. None silently upgrades into the next level.

Learning order

  1. Read the race in main.c.
  2. Trace one host step and one event.
  3. Decode and validate DTRC bytes.
  4. Replay and locate first divergence.
  5. Master synchronous capture_fifo.
  6. Pair DDR nibbles, then cross clocks with async FIFO/CDC.
  7. Read the benches as stimulus plus checks.
  8. Classify evidence and state the ceiling.

First principle: a valid byte is not necessarily accepted. In a ready/valid interface, transfer happens only when both are high on the active clock edge.

Computer engineering concepts: from bits to a board

This chapter supplies the vocabulary used by the code tour. Read it before the implementation sections, then follow their evidence links for exact code. A computer is a state machine: it stores bits, transforms them according to an instruction set, and changes state at defined events such as a clock edge or a recorded host step.

Bits, bytes, fields, and addresses

A bit is 0 or 1. Four bits make a nibble; eight bits make a byte; a 32-bit word has four bytes. Hexadecimal is shorthand for binary: each hex digit represents one nibble, so 0x5a5a5a5a is 32 bits. A mask selects bits (x & 0xF keeps the low nibble); shifts move fields (x >> 1 or x << 1). The emulator masks insn & 0xF000 to identify a Thumb branch family. An address is a number naming a byte in memory; a load combines bytes according to byte order.

TermBeginner meaningProject connection
fieldA bit range with a defined meaning.Instruction opcode and immediate bits.
registerFast storage inside the CPU.Selected replay snapshot.
addressA numbered memory location.Vector table and firmware data.

CPU state, C, and invariants

Cortex-M has general registers R0-R12; SP is stack pointer, LR the link/return register, PC the program counter, and xPSR status and condition flags. This project records those 17 fields as a selected boundary, not complete machine state. In C, volatile makes each access observable to the compiler; it does not make multiple accesses atomic, provide a lock, or establish ordering. The firmware invariant commutation[1] == (commutation[0] ^ 0x5a5a5a5a) can be false between its two stores. A race lets a reader observe that intermediate state; atomicity means an operation appears indivisible.

Thumb, ISA, branches, and interrupts

An ISA is the software/CPU contract: encodings, registers, operations, and effects. Thumb instructions are commonly 16 or 32 bits and halfword-aligned. A conditional branch contains a signed immediate: sign extension preserves negative offsets, shifting accounts for alignment, and the architectural target uses PC + 4, not the raw current address. The host decoder intentionally supports selected forms and leaves others unresolved; see Host model. An interrupt diverts execution to a handler through the vector table; Cortex-M exception entry saves an exception frame including commonly R0-R3, R12, LR, PC, xPSR. This recorder's IRQ shim models a scheduling boundary, not native NVIC or silicon behavior.

ELF, traces, and defensive binary parsing

ELF is a binary executable format containing headers, code, and data. The recorder hashes the complete ELF with SHA-256; its build ID binds replay to those input bytes but does not prove hardware behavior. DTRC uses headers, tagged events, lengths, varints, and CRC32. A varint stores seven payload bits per byte with the high bit meaning “more follows”; 300 = ac 02. Delta encoding stores a change from the previous point. Defensive parsing checks magic, version, lengths, known tags, canonical varints, bounds, truncation, event count, and CRC. CRC detects accidental corruption, not forgery. See Trace bytes.

Emulation, RTL, and evidence

Emulation is software imitating selected CPU behavior. RTL simulation runs a SystemVerilog hardware model in a testbench. Synthesis maps RTL to device resources; P&R places/routes them and estimates timing; physical hardware measures a board. Each layer supports only its own claims. Determinism means the same declared inputs and ordering reproduce the same result. Logical event points make record-replay comparable and useful for first divergence, but do not upgrade emulation into silicon equivalence.

RTL time, flow control, and FIFO invariants

SystemVerilog RTL describes hardware. Combinational logic has no stored state (assign); sequential logic updates at clock edges (always_ff @(posedge clk)). Nonblocking assignment (<=) evaluates right sides from old state and commits together. A clock is the repeating timing reference; reset initializes state, while reset release must still be coordinated per domain.

In valid-ready flow control, transfer occurs only when both are high on the active edge; low ready creates backpressure. The synchronous FIFO in Sync FIFO is circular memory plus pointers and count. Its invariants are 0 <= count <= DEPTH and ordered output. It handles simultaneous push/pop, including full-and-pop, and latches overflow when valid input is refused. DDR pairs rise then fall nibbles as {fall,rise}. For CDC, an async FIFO uses binary pointers for addressing, Gray pointers via (b >> 1) ^ b for cross-domain synchronization, and full/empty comparisons after synchronizers. Gray code reduces ambiguity because adjacent values change one bit; it does not eliminate metastability. Independent clocks, reset, synchronizer timing, power-of-two depth, and memory behavior remain assumptions. See Async/CDC and Benches.

Invariant checklist: state what must remain true, name the event that can interrupt it, and test the boundary. Passing evidence is bounded evidence.

First-run walkthrough

From the repository root, install the prerequisites before running the demo. You need Python 3.10+, ARM GCC (the arm-none-eabi-gcc command), and the repository requirements. Create the virtual environment and install dependencies with this copy/paste setup:

python3 -m venv .venv
.venv/bin/pip install -r requirements.txt

Then run make demo to demonstrate the deterministic host path. make check and the RTL tests additionally require Verilator on your PATH. macOS package instructions are in docs/macos-setup.md; other platforms need the equivalent Python, ARM GCC, and Verilator packages. Read the output as evidence, not as a claim larger than the command tests. For source navigation, start at firmware/src/main.c, then recorder/emulator.py, trace/format.py, replay/engine.py, and the gateway RTL.

One byte, end to end

A rise nibble is remembered. The next valid fall nibble forms {fall,rise}. The byte enters a FIFO only if byte_valid && byte_ready. A host consumer removes it only if out_valid && out_ready. The same discipline appears in the recorder: events are applied, one host step runs, then a snapshot is captured.

Evidence boundary: commands and paths above are repository facts; measured numbers belong to README.md and verification.md.

1. Firmware: a two-word invariant

volatile uint32_t commutation[2];
uint32_t next = commutation[0] + 1;
commutation[0] = next;
commutation[1] = next ^ 0x5a5a5a5a;

Line by line. The array has two 32-bit words shared with an interrupt. next reads word zero and increments it. The first store publishes the new counter; the second publishes its derived partner. Each volatile access occurs, but the pair is not one transaction. If an IRQ reads between the stores, it can observe a mixed pair. This is an ownership/order race, not a torn 32-bit access.

uint32_t first = commutation[0];
uint32_t second = commutation[1];
if (second != (first ^ 0x5a5a5a5a))
    corruptions++;

The reader copies both words, computes the invariant, and counts a mismatch. The deterministic schedule makes the intermittent-looking failure reproducible. Volatile does not provide atomicity or a lock.

Exact excerpt: firmware/src/main.c:3,8-10,17-21. Canonical race discussion: firmware-race.md.

2. Host model: one controlled step

self.count = 0
self.build_id = hashlib.sha256(Path(elf).read_bytes()).digest()
...
self.pc = int.from_bytes(self.uc.mem_read(4, 4), "little") & ~1

The recorder owns a step counter, binds the run to the full ELF hash, and reads the reset vector from memory. The hash is identity, not proof of hardware behavior. Unicorn is the instruction engine; the narrow IRQ shim is a model boundary.

def thumb16_next_pc(pc: int, insn: int, xpsr: int) -> int | None:
    if (insn & 0xF000) == 0xD000:
        ...
        return (pc + 4 + (imm8 << 1)) & 0xFFFFFFFF

Systematic reading: the type annotation permits “unresolved”; the mask selects conditional branch encoding; the architectural Thumb PC base is current address plus four; the signed immediate is shifted left one because instructions are halfword aligned. Untested forms fall back to width-based advancement. This is not “all Thumb.”

Source: thumb16_next_pc in recorder/emulator.py. The source calls the class “Unicorn-backed ... stepper,” so say host step, not universal retirement.

3. Trace bytes: validate at the boundary

def varint(n):
    if not isinstance(n, int) or n < 0 or n > MAX_INSTRUCTIONS:
        raise TraceError("invalid integer")
    out = bytearray()
    while n > 127:
        out.append((n & 127) | 128)
        n >>= 7

A varint stores seven payload bits per byte; the high bit means “more follows.” The loop rejects non-integers, negatives, and values beyond the declared ceiling. For example, 300 is ac 02.

if (event[1] == last and event[0] < last_kind):
    raise TraceError("bad event ordering")
...
return bytes(out) + struct.pack("<I", zlib.crc32(out))

Events must be nondecreasing by point and kind for equal points. Every tag has an exact tuple arity. The CRC detects accidental corruption over preceding bytes; it does not authenticate a producer. Decode checks the header, length, CRC, canonical varints, known tags, field bounds, DMA lengths, event count, and truncation.

Sources: varint, Trace.encode, and Trace.decode in trace/format.py. Canonical wire contract: trace-format.md.

4. Replay: pre-step events and divergence

events = _validate_real_events(trace.build_id, trace.events)
while len(states) < steps:
    for event in _events_at(events, cpu.count):
        apply_real_event(cpu, event)
    states.append(_checked(cpu.step()))

At point n, validated matching events are applied in canonical point/tag order before step(); then one selected snapshot is checked. Real-ELF replay supports supplied IRQ, exact-width one-shot read override, and DMA events (tags 1–3), and rejects model-only tags 4–7. _checked enforces exactly 17 fields. Build-ID equality prevents replaying a trace against another ELF.

if expected[index] != actual[index]:
    return _difference(index, expected[index], actual[index], events)

The first mismatch is more useful than a final checksum: it preserves the earliest field, instruction index, event context, and nearby events. It still cannot prove memory, NVIC, peripheral, pipeline, or silicon equivalence.

Sources: replay, first_divergence, and _difference in replay/engine.py; real event dispatch is in recorder/record.py. Tuple scope is documented in emulator-record-replay.md.

5. Learn synchronous capture_fifo first

Start with one clock. A FIFO is memory plus a write pointer, read pointer, and occupancy count. push = in_valid && in_ready; pop = out_valid && out_ready. Backpressure is the producer seeing in_ready=0.

assign out_valid = (count != 0);
assign pop = out_valid && out_ready;
assign in_ready = ((count < DEPTH) || pop) && !overflow;
assign push = in_valid && in_ready;

Syntax. logic [7:0] is an 8-bit signal; [0:DEPTH-1] is an unpacked memory; assign is combinational; always_ff @(posedge clk) updates state on a rising edge; <= is a nonblocking sequential assignment. The “or pop” permits a same-edge dequeue/enqueue when full.

case ({push, pop})
  2'b10: count <= count + 1;
  2'b01: count <= count - 1;
  default: count <= count;
endcase

The concatenation makes a two-bit case: push only increments, pop only decrements, both or neither preserves count. Reset clears pointers, count, sticky overflow, and accepted_sequence. If valid data arrives while not ready, overflow latches high and freezes further acceptance until reset. It is deliberately fail-closed: later output is not silently called lossless.

Source: gateway/rtl/capture_fifo.sv. This synchronous model is the prerequisite for the CDC design.

6. DDR nibble pairing, async FIFO, and CDC

if (!overflow && valid && !have_rise) begin
    rise_data <= nibble_rise; have_rise <= 1'b1;
end else if (!overflow && valid && have_rise) begin
    byte_data <= {nibble_fall, rise_data};
    byte_valid <= 1'b1; have_rise <= 1'b0;
end

DDR-shaped input supplies rise first and fall second. The first edge stores the low nibble; the second emits fall as high nibble plus the remembered rise. If the output is still valid and not ready, overflow sticks.

function automatic [ADDR_WIDTH:0] bin2gray(input [ADDR_WIDTH:0] b);
    bin2gray = (b >> 1) ^ b;
endfunction
assign wpush = wvalid && wready;
assign rvalid = (rgray != wgray_r2);

The async FIFO assumes power-of-two depth (DEPTH = 1 << ADDR_WIDTH) with ADDR_WIDTH >= 1. Binary pointers address memory; Gray pointers change one bit per adjacent increment, then pass through two registers marked ASYNC_REG into the opposite clock domain. Full compares the next write Gray pointer with synchronized read pointer and inverted wrap bits; empty is equality of read pointer and synchronized write pointer.

CDC ceiling. Coordinated external reset now asserts asynchronously and deasserts through a two-stage synchronizer in each domain. These digital mechanisms and independent-clock simulations reduce identified risks, but they cannot prove metastability behavior or silicon reset timing. CDC constraints, RAM choice, clock/I/O constraints, and hardware timing signoff remain work.

Sources: gateway/rtl/ddr_capture.sv, async_fifo.sv, reset_sync.sv, capture_gate.sv, and gateway_top.sv. The current top ties host and capture clocks together, so it is not physical CDC evidence.

7. Testbenches are stimulus plus checks

tb_capture_fifo drives bytes, checks accepted count, fills depth two, expects in_ready=0, checks sticky overflow, drains ordered bytes, tests simultaneous pop/push, and verifies reset clears state. Its task begins:

task automatic drive_input(input logic [7:0] data);
  @(negedge clk); in_data = data; in_valid = 1'b1;
  if (!in_ready) $fatal(1, "input was not accepted: %h", data);

tb_capture_gate uses distinct capture and host clocks, carries the checked-in 66-byte golden stream in exact order through a depth-two async FIFO, checks wraparound, freezes after sticky overflow, and verifies coordinated and half-byte reset recovery. tb_capture_fifo_stream reads plusargs INFILE, OUTFILE, and COUNT, streams bytes while ready, writes output, and fails on status mismatch. A passing simulation proves only the exercised RTL scenario and assertions.

Sources: gateway/sim/tb_capture_fifo.sv, tb_capture_gate.sv, and tb_capture_fifo_stream.sv. Both primary benches consume examples/golden-demo.dtrc rather than fabricated byte constants.

8. Evidence ladder and ceilings

LayerWhat it can supportWhat it cannot support
Python model/UnicornHost scheduling, selected snapshots, codec behaviorUniversal retirements, native NVIC, silicon timing
RTL simulationStimulus/check behavior for tested clocks and reset schedulesMetastability, pins, sustained physical ingress
SynthesisResource mappingPlaced routing or board behavior
P&RProvisional timing under declared constraintsUnconstrained-I/O signoff or silicon proof
HardwareMeasured board capture under stated setupClaims beyond the measurement

Say the ceiling aloud: selected host and Verilator evidence is real evidence, but it is not physical ETM capture, CDC signoff, sustained bandwidth, native exception fidelity, or universal architectural equivalence.

9. Reasoning quiz

Score: 0/0. Only the first correct answer scores.

10. Retrieval flashcards

11. Exercises

  1. Draw the two firmware stores and place an IRQ between them; explain volatile versus atomicity.
  2. Label point n before event application, one host step, and snapshot capture.
  3. Encode 300 as a varint and list three decoder failures.
  4. Decode a negative Thumb branch target from PC+4.
  5. For a depth-two synchronous FIFO, tabulate count for push/pop combinations.
  6. Show rise/fall nibble pairing and explain why fall is the high nibble.
  7. Draw binary-to-Gray pointers, two synchronizers, full/empty comparisons, and unsafe reset release.
  8. Classify a Verilator pass, synthesis resource report, P&R timing estimate, and board capture by evidence layer.

12. Glossary

CDC
Clock-domain crossing.
FIFO
First-in, first-out buffer.
Gray code
Adjacent values differ by one bit.
DTRC
Deterministic Trace Record Container.
MMIO
Memory-mapped I/O, injected here rather than modeled as a bus.
DMA
Direct memory access, represented here as raw writes.
P&R
Place and route.
ETM
Embedded Trace Macrocell; physical ingress remains future.