Free to Learn · Time-travel debuggerLesson 08 of 13

08 · A machine worth debugging

Your Lesson 07 JavaScript debugger can rewind a small teaching machine. Lob is a compiled artillery game with 131,072 memory bytes and runs of about a million instructions in WebAssembly (portable machine code that runs in browsers and in Node). Predict what happens before game_init starts the game when r_px reads the shell's horizontal position through an uninitialized pointer (a stored byte address pointing to another place in memory, the program's byte array): intuition expects a crash or missing-field error, yet cold zeroed bytes make r_px dereference address zero and quietly return 0 after exactly four instructions. Build the WebAssembly interpreter your debugger must pause and restore: code that performs one numbered operation, an instruction, per step.

Start

Terminal command
node examples/step-getter.mjs
Select code to copy. Scroll horizontally if needed.

Node 22 runs this JavaScript probe. A value stack holds temporary numbers. i32.const pushes a 32-bit integer; i32.load reads one; f32.load reads a 32-bit decimal. begin requests one function run; tick counts finished instructions; running marks an active request; returned holds its result.

The command executes the real game's r_px getter one instruction at a time. The game has not been initialized: its pointer and the bytes read through that pointer are zero. This is a probe of the interpreter, not a moving shell yet.

Four instructions through cold memoryexamples/getter-output.txt
begin: tick=0, running=true
1 i32.const stack=[0]
2 i32.load stack=[0]
3 f32.load stack=[0]
4 end stack=[]
returned=0; this is cold memory, before game_init
Select code to copy. Scroll horizontally if needed.

begin leaves the instruction count, called a tick, at zero. The final end returns the value and empties the stack.

Continue in the same project/ from Lesson 07. It contains your own solution.mjs debugger and the blank machine.mjs created when you began the course. Run its baseline now:

Terminal command
node lab.mjs check project 08 --help-used "continuing Lesson 07 project; Machine regions unfinished"
Select code to copy. Scroll horizontally if needed.

The blank machine fails with not written yet. That red result is the baseline you will repair. Later attempts remain under project/attempts/.

Keep every // region: NAME marker. Replace only the text between a matching pair. The six regions appear in this order:

123456
initial-statecall-entrystep-startreturn-framebranchmemory

Recovery routes

Use these only if you do not have the cumulative Lesson 07 project or need a disposable comparison. Every setup command refuses an existing path, so none can overwrite your attempt.

NeedCommandWhat you receive
Type in six marked regionsnode examples/start-chapter.mjs project08-write writestarter/machine-build.mjs with supporting instruction cases
Inspect a working checkpointnode examples/start-chapter.mjs project08-supplied suppliedA working implementation saved at this lesson boundary
Begin the 13-lesson course herenode lab.mjs start projectBoth the JavaScript debugger and WebAssembly machine starters; using the fallback debugger is recorded assistance

If you use AI, begin with the write route. Share one marked region at a time, inspect its state changes, and record the help used. A supplied-route baseline passes; a write-route baseline fails with not written yet.

What you are given

Lob was written in C and compiled to WebAssembly, a machine code that runs in browsers and in Node. You get the compiled file, targets/lob.wasm, and the same file decoded into a JSON listing, programs/lob.json. Decoding is taught in the Sightline course. Here you start from the listing. API.md ends with a table of all 62 instructions Lob and Lob II use.

The game is played through calls from outside: game_init(seed, mode) starts it, where the seed is a starting number that reproduces the same round. game_key(code) presses a key, and each call to game_tick() is one game frame, 1/60 of a second. The mode is a sum of four defence switches, optional game rules worth 1, 2, 4 and 8 that API.md describes under "public/sessions.mjs"; mode 0 enables none. Between calls, exported functions called getters, such as r_px below, each return one value of the game.

A WebAssembly global is a module-wide mutable or constant variable. Global 0 holds the C stack pointer, the address marking the top of compiled C's working stack, starting at byte 65,536. The pointer g, stored at address 78,112, points to Lob's game-state record.

Lob's memory after game_init(5, 1), not to scale: the C stack below 65,536, the 281-byte data segment at 65,536, then the 12,288 bytes game_init clears, holding the state at g = 65,904 and the three texts, and at 78,112 the pointer that holds g.

The game-state record that g points to sits with three texts in a stretch game_init clears to zero. The C stack, below 65,536, is where compiled C keeps some variables of its own, and the data segment is text the listing gives the machine to copy in before anything runs. The addresses of g and the texts depend on the seed.

The game keeps three text buffers:

BufferExample or purpose
Status lineAngle, power, wind and score
Message lineROUND 1, HIT!, SHORT BY 10
Help textControl rules and scoring distance

Angle runs from 5 through 85, power from 10 through 100, and a shell within 12 paces scores. The N key starts a new round with a new flag and wind.

Lob II, the second game, was written separately and compiled the same way. Its file is targets/lob2.wasm, and its listing programs/lob2.json. It takes the same calls and keys and keeps the same three texts in memory, and its help text gives the same rules. Its eight getters, g0 to g7, are deliberately named so they don't say what they hold, because Sightline asks its learners to work that out, and none of them returns the help text's address. Your machine runs both games, and one build in lesson 13 is a build of Lob II.

The listing has one entry per function. Here is the whole of function 14, the getter r_px, which returns the shell's horizontal position:

WebAssembly instructions and stack trace
0  ["i32.const", 0]
1  ["i32.load", 2, 78112]
2  ["f32.load", 2, 40]
3  ["end"]
Select code to copy. Scroll horizontally if needed.

Each instruction is a name followed by its immediates, the numbers written into the code. A load's two immediates are an alignment hint, which you can ignore, and an offset.

WebAssembly is a stack machine. Instructions take their operands from the top of a value stack and push their results back on it. Trace r_px by hand, writing the stack after each instruction, top on the right:

WebAssembly instructions and stack trace
0  i32.const 0           [0]
1  i32.load offset 78112 [g]          reads 4 bytes at 0 + 78112
2  f32.load offset 40    [px]         reads 4 bytes at g + 40
3  end                   the function returns px
Select code to copy. Scroll horizontally if needed.

i32.load pops an address, adds its offset, and pushes the 32-bit integer stored there: the pointer g from the figure. f32.load pops that pointer, adds 40 and pushes the 32-bit float stored there, the shell's position. At end the function returns what is left on the stack.

Function 12, r_target_x, returns the flag's position. The game keeps that position combined by exclusive or (i32.xor, below) with a key at g + 92, and the key is 0 unless mode 4 is on. Then f32.reinterpret_i32 reinterprets a 32-bit integer's raw bits as a 32-bit float without numeric conversion. It has one local variable, local 0:

WebAssembly instructions and stack trace
0  ["i32.const", 0]
1  ["i32.load", 2, 78112]
2  ["local.tee", 0]
3  ["i32.load", 2, 92]
4  ["local.get", 0]
5  ["i32.load", 2, 16]
6  ["i32.xor"]
7  ["f32.reinterpret_i32"]
8  ["end"]
Select code to copy. Scroll horizontally if needed.

local.get 0 pushes local 0's value. local.tee 0 stores the top of the stack in local 0 and leaves it on the stack. i32.xor pops two integers and pushes their bitwise exclusive or.

Question 08a: how many values are on the stack after instruction 4 of r_target_x has run? Commit your answer before reading on:

Terminal command
node lab.mjs predict project 08a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

One plain object

Your machine keeps all changing data in machine.state.

FieldMeaning
memoryThe guest's bytes; guest means the WebAssembly program running inside this JavaScript interpreter
globalsProgram-wide variables initialized from the listing
stackTemporary values
framesFunction calls in progress
tick, callsCompleted instructions and calls begun

A frame holds the running function in func, its next instruction in at, its local values and its return data.

Later lessons copy, hash and restore this object. structuredClone(machine.state) must capture the whole moment, and machine.state = copy must restore it. State kept in a closure (variables captured inside an outer function rather than stored on machine.state) or another field would be missed.

What isn't state stays outside: the program, and anything you compute once from it, such as where each structured control region ends.

A run starts with begin(name, args), which pushes the first frame and runs nothing. step() runs one instruction. Its event reports { tick, func, at, op, writes }: when it ran, where it ran, the instruction name and its memory writes. invoke(name, args) begins a call and steps until it returns. Checks 08.memory-starts and 08.one-step inspect a new machine and its first step.

Allocate the state you will later restore

In project/machine.mjs, replace the initial-state region inside the constructor. The supplied starter prefix defines PAGE as 65,536 bytes, one WebAssembly 64 KiB memory page:

Initialize mutable stateexamples/machine-checkpoint.mjs · initial-state

Replace initial-state inside the constructor.

    const memory = new Uint8Array(this.program.memory.min * PAGE);
    for (const d of this.program.data) memory.set(d.bytes, d.offset);
    this.state = {
      memory,
      globals: this.program.globals.map((g) => g.init),
      stack: [],
      frames: [],
      tick: 0,
      calls: 0,
      result: undefined,
    };
Select code to copy. Scroll horizontally if needed.

A new typed array starts filled with zero. The data segments then install the compiled program's text at exact byte addresses. Globals copy their initial values; the stacks and counters start empty. The constructor's supplied prefix loads the program, matches each structured control region with its end and binds imports. Those facts do not change while the WebAssembly program runs, so they sit outside state.

Separate starting a call from executing it

Replace the whole call-entry region. It contains the running getter and three methods, including begin. The constructor also builds this.prepared, a Map caching each decoded function entry fn by function index, with fn.locals listing extra local types. Two supplied helpers normalize values at the boundary: coerce(type, v) converts a JavaScript number to the target WebAssembly type (such as v | 0 for i32 or Math.fround(v) for f32), and zeroOf(type) returns 0 or 0n for a local's WebAssembly type. A block is a bounded instruction region, and a loop is a repeating one. Inside enter, labels starts as []; this branch-target stack records where a branch exits each enclosing block or repeats each enclosing loop:

Start, enter and finish a callexamples/machine-checkpoint.mjs · call-entry

Replace the complete call-entry region.

  get running() {
    return this.state.frames.length > 0;
  }

  // Start a call to an export. Nothing runs until step().
  begin(name, args = []) {
    if (this.running)
      throw Error(`Machine: ${name} called while another call is unfinished`);
    const e = this.program.exports.find(
      (x) => x.name === name && x.kind === 'func',
    );
    if (!e) throw Error(`Machine: no exported function named ${name}`);
    const type = this.program.typeOf(e.index);
    if (args.length !== type.params.length)
      throw Error(
        `Machine: ${name} takes ${type.params.length} arguments, got ${args.length}`,
      );
    this.state.calls++;
    this.state.result = undefined;
    this.enter(
      e.index,
      args.map((a, i) => coerce(type.params[i], a)),
    );
  }

  // Run a whole export call and return its result.
  invoke(name, args = []) {
    this.begin(name, args);
    while (this.running) this.step();
    return this.state.result;
  }

  enter(index, args) {
    const fn = this.prepared.get(index);
    const locals = [...args, ...fn.locals.map(zeroOf)];
    this.state.frames.push({
      func: index,
      at: 0,
      locals,
      base: this.state.stack.length,
      labels: [],
    });
  }
Select code to copy. Scroll horizontally if needed.

begin checks the export and argument count before entering the call. enter appends a frame whose base remembers the caller's stack height. Arguments lead the locals; declared locals follow, initialized to zero. No instruction has executed yet. invoke is only a convenience loop over the same step that the debugger will use.

Trace begin('r_px'): one frame is added, its next instruction is zero, calls increases once and tick stays unchanged. A nested guest call uses enter, not begin: it must not look like a new call from outside.

Execute exactly one instruction

Replace the step-start region at the opening of step. In fn, fn.ops is the flat array of decoded numeric instruction codes matching fn.code for dispatch. The supplied switch starts immediately after its closing region marker; leave it in place.

Capture an instruction boundaryexamples/machine-checkpoint.mjs · step-start

Replace step-start; retain the following switch.

  step() {
    const s = this.state;
    const frame = s.frames[s.frames.length - 1];
    if (!frame)
      throw Error('Machine: no call in progress; use begin(name, args) first');
    const fn = this.prepared.get(frame.func);
    const at = frame.at;
    const ins = fn.code[at];
    const op = fn.ops[at];
    const event = {
      tick: s.tick + 1,
      func: frame.func,
      at,
      op: ins[0],
      writes: [],
    };
    const st = s.stack;
    frame.at = at + 1;
Emphasized lines: 2, 3. Select code to copy. Scroll horizontally if needed.

The event identifies the instruction before it executes. Advance frame.at before dispatch: an ordinary instruction then falls through to its successor, and a branch can replace that next position. The supplied tail of step, after the switch, increments s.tick and returns this event. A trap stops execution because an instruction is invalid, such as division by zero. A trapped instruction throws before that tail and is not counted as completed.

Tour the supplied switch now: i32.const pushes its immediate, local.get reads the current frame and end either closes a label or calls leave. Every access uses the s or frame fetched during this step. Holding a frame from an earlier call to step would break restoration when a debugger replaces the whole state.

Replace return-frame, the leave method below branch:

Return to the callerexamples/machine-checkpoint.mjs · return-frame

Replace return-frame with this leave method.

  leave(frame) {
    const s = this.state;
    const type = this.program.typeOf(frame.func);
    const results = type.results.length
      ? s.stack.slice(s.stack.length - type.results.length)
      : [];
    s.stack.length = frame.base;
    s.frames.pop();
    if (s.frames.length) s.stack.push(...results);
    else s.result = results[0];
  }
Select code to copy. Scroll horizontally if needed.

Save the result before cutting the stack back to frame.base. A nested call puts its result on the caller's stack; the outermost call puts it in state.result. On r_px's last instruction the stack holds its one result. That value survives the cut, the last frame disappears and running becomes false.

At this point the type-in route still cannot run the getter: memory is unfinished, and full-game checks also reach the unfinished branch region. A check now should retain those expected failures rather than suggest you broke the call boundary:

Terminal command
node lab.mjs check project 08 --help-used "followed state and call listings"
Select code to copy. Scroll horizontally if needed.

Blocks, loops and branches

WebAssembly has no jump to an arbitrary position. Code is nested in blocks, and a branch names a block by its depth, where 0 is the innermost block around the branch and 1 the one around that.

InstructionEffect
blockOpens a block; a branch lands after its end
loopOpens a loop; a branch lands after loop so it repeats
br NBranches to depth N
br_if NPops an integer and branches when it is nonzero
endCloses the inner block; the function's last end returns

Your machine needs, for each frame, a stack of open blocks: for each one, where a branch to it goes and how tall the value stack was when it opened. A branch cuts the value stack back to that height. A block that leaves a value, written ["block", "i32"], keeps its top value across the cut. Lob's blocks never do, but the checks test it, so here is one traced, top of the stack on the right:

WebAssembly instructions and stack trace
0  i32.const 7           [7]
1  block i32             [7]        the block opens at height 1
2  i32.const 1           [7, 1]
3  i32.const 2           [7, 1, 2]
4  br 0                  [7, 2]     keep the top value, cut to height 1, push it back
5  i32.const 9                      skipped: the branch went past the block's end
6  end                              skipped too
7  ...                   [7, 2]     the block left 2
Select code to copy. Scroll horizontally if needed.

The branch kept one value because the block leaves one. A plain block keeps none, and a branch to a loop keeps none either.

Here is the loop that starts game_init, function 4, shortened. It clears 12,288 bytes of memory, 8 bytes each time round, using i32.store8 to write one byte to memory. local.get, local.set, and local.tee read a local, write a local, or write a local while keeping the value on the stack. In ['loop', null], null says this loop carries no result value when it ends:

WebAssembly instructions and stack trace
0   ["i32.const", -12288]
1   ["local.set", 2]
2   ["loop", null]
3   ["local.get", 2]
4   ["i32.const", 78112]
5   ["i32.add"]
6   ["i32.const", 0]
7   ["i32.store8", 0, 0]
    ... the same five instructions for the next 7 bytes ...
43  ["local.get", 2]
44  ["i32.const", 8]
45  ["i32.add"]
46  ["local.tee", 2]
47  ["br_if", 0]
48  ["end"]
Select code to copy. Scroll horizontally if needed.

Local 2 starts at -12,288 and goes up by 8 each time round. br_if 0 branches back to instruction 3 while local 2 isn't zero, so the loop ends when local 2 reaches 0.

Question 08b: how many times does br_if 0 branch back to instruction 3? Commit before reading on:

Terminal command
node lab.mjs predict project 08b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

This loop is why game_init alone runs more than 70,000 instructions before the game draws anything. Check 08.control runs small programs with nested blocks, loops, branches out of several levels and blocks that leave a value.

Implement the branch destination

Replace branch in project/machine.mjs. Each runtime label records label.height (the value-stack length when the block or loop began), label.loop (true for a loop, false for a block), and label.arity (the count of values, 0 or 1, carried across the branch). For both block and loop, label.end stores the branch-target base index (fn.ends[at] for a block, or at for the loop instruction itself), so label.end + 1 lands just after the closing end of a block or back on the first instruction inside a loop:

Jump without losing the enclosing stateexamples/machine-checkpoint.mjs · branch

Replace the branch region.

  branch(frame, depth) {
    const st = this.state.stack;
    // A branch past every open block targets the function body itself: it returns.
    if (depth === frame.labels.length) {
      this.leave(frame);
      return;
    }
    const label = frame.labels[frame.labels.length - 1 - depth];
    const kept = label.arity ? st.slice(st.length - label.arity) : [];
    st.length = label.height;
    st.push(...kept);
    if (label.loop) {
      frame.labels.length -= depth; // keep the loop's own label
      frame.at = label.end + 1; // back to the first instruction inside the loop
    } else {
      frame.labels.length -= depth + 1;
      frame.at = label.end + 1; // just past the block's end
    }
  }
Select code to copy. Scroll horizontally if needed.

Each label records a destination and the stack height to restore. Save a result before shortening the stack.

TargetLabel after branching
LoopKept for the next iteration
BlockRemoved after execution leaves it
Beyond every open labelReturn from the function

Tour prepare near the bottom of the supplied file. It pairs each block or loop with an end, and dispatch sets label.end to that end for a block or to the loop itself. prepare handles code nesting; frame.labels tracks the nesting active now.

Memory: widths, order and writes

Memory is a Uint8Array of 131,072 bytes, because the listing's memory.min is 2 pages of 65,536. It starts as zeros, with each data segment copied in at its offset: Lob's one segment, 281 bytes, at 65,536.

A load or store adds its offset to an address popped from the stack. The address is unsigned. The 32 bits of -4 mean 4,294,967,292, far outside memory, and an access that reaches past the last byte is a trap. A trap stops the program. Throw an Error whose message starts with trap:.

Values are stored little-endian, lowest byte first. i32.store of 300 writes 2C 01 00 00, since 300 is 0x0000012C. Create a DataView (JavaScript's byte-level reader and writer over raw memory) from state.memory when you use it. A view made in the constructor keeps pointing at old memory after machine.state = copy.

OperationBytesValue
i32.load, i32.store432-bit integer
f32.load, f32.store432-bit float
i32.load8_u1Integer from 0 through 255
i32.store8, i32.store161 or 2Low bytes of an integer
i64.store8i64.const value supplied as a BigInt

Every store reports a write in its event, { address, size, before, after }, with before and after as arrays of byte values. Read before from memory before you store. Lesson 10 rebuilds your Lesson 03 watchpoints, and "who last wrote this address", on these writes, so a store that writes the same value it found still reports a write.

Question 08c: an i32.store with offset 0 pops the value 1,000 and then the address 70,000. What is the byte at address 70,001 afterwards? Commit:

Terminal command
node lab.mjs predict project 08c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Check 08.memory runs loads and stores of every width, offsets, byte order and out-of-bounds traps. 08.writes checks that every store in a run of Lob reports the bytes it wrote, and that nothing else reports a write.

Read the current memory, then report the write

Replace memory, containing both view and store. If an access goes out of bounds, view throws the error returned by the supplied helper trap(message), which halts execution with a WebAssembly runtime error:

Address the restored memoryexamples/machine-checkpoint.mjs · memory

Replace the complete memory region.

  view(base, offset, size) {
    const address = (base >>> 0) + offset;
    const memory = this.state.memory;
    if (address + size > memory.length)
      throw trap(`out of bounds memory access at ${address}`);
    return new DataView(memory.buffer, memory.byteOffset + address, size);
  }

  store(event, base, offset, size, write) {
    const view = this.view(base, offset, size);
    const address = view.byteOffset - this.state.memory.byteOffset;
    const before = Array.from(
      this.state.memory.subarray(address, address + size),
    );
    write(view);
    event.writes.push({
      address,
      size,
      before,
      after: Array.from(this.state.memory.subarray(address, address + size)),
    });
  }
Emphasized lines: 3, 6. Select code to copy. Scroll horizontally if needed.

base >>> 0 changes the reading of its 32 bits, then ordinary addition includes the offset. Do not wrap that sum back to 32 bits: a huge address must trap, not wrap to the beginning of memory. memory.byteOffset matters if the byte array is a view into a larger host buffer, the JavaScript-owned storage behind the guest's memory view. The event's address stays relative to the guest's memory, so store subtracts the host buffer's starting offset again.

before and after are copied arrays, not live views. A later guest write must not rewrite an earlier event's evidence. write(view) is supplied by each opcode case: for example, i32.store pops the value, pops the address, and passes a function that calls setInt32 with the little-endian flag.

All six holes are now filled. Run your file through the same probe as the first win, then the unit's real checks:

Terminal command
node examples/step-getter.mjs project/machine.mjs
# After filling the type-in route's starter from the listings:
node lab.mjs check project 08 --help-used "filled six regions from chapter listings; supplied opcode cases"
# After following the supplied route:
node lab.mjs check project 08 --help-used "supplied Machine checkpoint; followed traces and code tour"
Select code to copy. Scroll horizontally if needed.

Choose the check command matching your route and revise its description to match what you actually did. For AI-assisted changes, identify that assistance rather than claiming you filled the regions from the listings yourself.

The probe should print the earlier four-step trace. All 11 unit checks should pass, including the actual games. If not, follow the named check's first mismatch back to its section; preserve the failure and your explanation before editing. The next sections explain the supplied number and import cases exercised here.

Each check compares one boundary:

CheckBoundary
08.memory-starts, 08.one-stepNew memory and the first game_init steps
08.framesFrames after each call instruction
08.control, 08.memory, 08.numbersSmall programs against Node's engine
08.writesEvery reported store against Node's memory
08.lob-agrees, 08.lob2-agreesResults, getters and memory after every call
08.plain-stateExecution after copied state is restored, including on a new machine
08.speedA long Lob run and its ending memory

Only 08.plain-state assigns machine.state. Every other check runs each machine on from its constructor without replacing its state.

Break a restoration boundary, then repair it

In your project only, make view reuse a memory reference captured during construction. Inside the initial-state region, after the this.state = { ... }; statement and before the // endregion: initial-state line, add this.cachedMemory = this.state.memory;. In view, change const memory = this.state.memory; to const memory = this.cachedMemory;. Leave store as it is.

Question 08f: with this change, how many of unit 08's 11 checks fail? Write in project/report.md which ones you expect to fail and why, then commit the number before you run the check with --help-used describing this prescribed change:

Terminal command
node lab.mjs predict project 08f YOUR_ANSWER
node lab.mjs check project 08 --help-used "prescribed change: view reads memory cached in the constructor"
Select code to copy. Scroll horizontally if needed.

Keep the resulting attempt, and compare the checks that failed with what the lab said after your prediction.

Compare the cached array and machine.state.memory after assigning a structuredClone of the state. They contain equal bytes initially, but are they the same object? Explain why an interpreter can agree with the native engine on an ordinary run yet fail after restoration. Remove the cache, restore the memory lookup and rerun. The repair must preserve the checks, not special-case them. This mutation is guided practice; the new application below asks you to design behavior the walkthrough has not implemented.

Integers and floats

JavaScript stores numbers as 64-bit floats, so the machine must preserve narrower rules.

Guest valueJavaScript rule
i32, a 32-bit integerWrap addition with `0; multiply with Math.imul; read unsigned with >>> 0`
Signed division and remainderBoth trap on zero; only div_s traps on -2,147,483,648 by -1, while rem_s of those gives 0
Shift countUse the low 5 bits, so 33 becomes 1
f32, a 32-bit floatRound every result with Math.fround
f64 used by sin and cosPromote unchanged; demote with Math.fround

For example, f32.add of 0.1 and 0.2 is Math.fround(Math.fround(0.1) + Math.fround(0.2)).

These conversions are easy to get wrong:

Question 08d: what number does f32.convert_i32_u push when it pops -1? Commit:

Terminal command
node lab.mjs predict project 08d YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Check 08.numbers runs these instructions on the cases most likely to go wrong.

Calls and the outside world

call N calls function N. Imports come first, so Lob's functions 0 through 3 are server_round, cos, sin and server_wind. Its own functions start at 4.

Call targetBefore the callAfter the call
Defined functionPop arguments into a new frame's localsPush its result on the caller's stack
Imported functionPop arguments into the matching JavaScript functionPush its result; round an f32 with Math.fround

The caller's at field points after call, where it resumes. Check 08.frames follows game_init calls. Lob asks cos and sin when a shot fires. In mode 1, it asks server_round for each round and server_wind for each airborne game frame. Lesson 09 records those outside answers.

The C stack in the memory figure is that stack of its own, beside your machine's frames. A C variable whose address is taken, such as a small array, can't live in a WebAssembly local, so the compiled code keeps it there. Global 0, which starts at 65,536, is the pointer to its top. Function 6, which writes the status line, keeps number digits there while printing, so every game frame writes a few bytes below 65,536. Lesson 10 counts on this.

The answer key

Node's WebAssembly engine is the answer key. It runs targets/lob.wasm beside your machine with the same calls and outside answers.

After every callCompared evidence
Return valueExact value
Every getterExact value
131,072 memory bytesOne hash

Each machine gets its own makeWorld(seed) from public/world.mjs. Its sin and cos use JavaScript; its server functions use a seed separate from the game's. Try the comparison:

Terminal command
node lab.mjs agree project
node lab.mjs agree project --game lob2 --mode 7
Select code to copy. Scroll horizontally if needed.

A difference names the first call after which the two disagree. Checks 08.lob-agrees and 08.lob2-agrees run several seeds and modes. 08.plain-state copies and restores your state in the middle of a call, and 08.speed times a run of about 900,000 instructions.

Keep the host responsive

Your debugger must eventually let a person pause a guest that takes too long or never returns. Add a budgeted runner in project/run-slice.mjs, which both chapter routes created as a stub. If you chose the original blank-start command, copy starter/run-slice.mjs to that new file first, preserving any file you already wrote. This is required new application: the Machine listings above do not contain the runner, and no finished runner is supplied.

Export synchronous runSlice(machine, budget). The caller has already used machine.begin. A positive safe integer is a whole JavaScript number from 1 through Number.MAX_SAFE_INTEGER, where integer arithmetic remains exact.

CaseRequired result
Budget is not a positive safe integerReject it before changing the machine
Machine is runningCall step() at most budget times; never call invoke or begin
Final instruction uses the last budget slotReturn { executed, stopped: 'returned' }
Machine is already idleReturn { executed: 0, stopped: 'returned' }
Budget ends firstReturn { executed, stopped: 'budget' }
Guest trapsPreserve the exception

Before coding, sketch the order of validation, the idle test, stepping and the final status decision in project/report.md. Work out the exact-boundary case: if the last permitted instruction is end, which status tells the truth? Keep that initial reasoning. Run the unfinished file once, then implement and run again; describe assistance honestly for each attempt:

Terminal command
node examples/check-slice.mjs project --help-used "initial attempt; no runner written"
node examples/check-slice.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The checker snapshots machine.mjs, run-slice.mjs and your report before running.

It testsIt preserves
Invalid input, idle state, resumption, an endless loop and a trapThe exact code and slice-receipt.json under project/attempts/
game_init split into small slicesA comparison with one uninterrupted final state

node lab.mjs status project lists every runner attempt. A failed attempt never replaces an earlier one.

Inspect the endless-loop listing in examples/check-slice.mjs. Explain how the runner can return to its caller while the guest is still running. Then choose a different budget for your own Lob initialization experiment. Report how many slices ran and show that their completed instruction counts add up to the final tick. A pass alone is not your explanation.

The budget has a narrow boundary:

BoundedNot bounded
Guest instructionsTime spent inside an imported JavaScript function

A real interface schedules the next slice after its event loop handles input. As a stretch, build a Run/Pause control and measure several budgets during game_init. Keep scheduling outside Machine so instruction behavior stays unchanged.

The wall

Now measure the wall, the point where copying the whole state on every step stops working. node lab.mjs wall project runs your Lesson 01–07 debugger through public/part-one-vm.mjs. Its execute(program, state) copies all of machine.state with structuredClone, then runs one instruction. Your Lesson 01–07 small machine copied only 8 memory cells per step.

Question 08e: the lab's run is 1,043,331 instructions, and each step copies all 131,072 bytes of memory. How many gigabytes, 10^9 bytes, does one pass over the run copy? Round to a whole number, and commit before you run the lab:

Terminal command
node lab.mjs predict project 08e YOUR_ANSWER
node lab.mjs wall project --part-one project/solution.mjs
# If you began at Lesson 08, use the labelled fallback instead:
node lab.mjs wall project
Select code to copy. Scroll horizontally if needed.

The first command uses the debugger you built in Lessons 01–07. The fallback command is an assisted route for learners who began at Lesson 08. Both write measurements to project/wall.json.

MeasurementHow to read it
Machine timeCost without state copies
Debugger time per stepDivide by machine time to get the slowdown
reverseFind estimateReplays required to find the latest earlier matching byte

Machine timings vary with load, so trust your printed ratio. The README's measured slowdown spans 100 to 800 times. reverseFind compounds that cost: each candidate tick replays from the nearest checkpoint, a saved machine-state copy from which execution can resume. With no checkpoint after tick 0, an answer 1,000 ticks back can require a thousand near-million-step replays, which wall prints as a multi-hour estimate.

Record your numbers and that printed multi-hour reverseFind estimate in project/report.md. Lessons 09 and 10 record once, keep changed-page snapshots, and replay thousands of instructions instead of the whole run.

Optional: your own decoder

If you took Sightline and wrote its wasm.mjs, check it against the supplied listings. This needs that file at that path; without Sightline, skip this section:

Terminal command
# Optional: only if you have Sightline's wasm.mjs at this path
node lab.mjs decoder ../sightline/work/wasm.mjs
Select code to copy. Scroll horizontally if needed.

It compares every instruction of both games, name, immediates and file position, and prints the first difference. When they agree, your decoder produces exactly the listing this course gives you.