indicogniBuild a VMM

Contents

Chapter 03 · Part I

A guest of your own, and what an exit costs

Needs a Mac Runs in browser ~3.5 h Lab: Linker map
4 of 26

Course progress: chapter 03 is 4 of the 26 chapters written so far (numbering starts at 00)

Warm-up: three questions from earlier chapters

Answer each one in your head or on paper before you open its answer. They change on each visit.

  1. From chapter 02: An exception, one level up: your first VM exit

    A VM exit reports the syndrome 0x5a00002a. Which instruction stopped the guest, and what number did it carry?

    Show answer

    The exception class is 0x5a00002a >> 26 = 0x16: an hvc from 64-bit code. For an hvc, the low 16 bits of the syndrome hold its immediate, so the guest ran hvc #0x2a.

  2. From chapter 00: Two kernels, one Mac: what a virtual machine is

    A guest runs 1,000 instructions under trap-and-emulate; 6 of them are privileged or touch the console. Roughly how many instructions does the VMM handle for it, and what does the processor do with the rest?

    Show answer

    About 6, one per trap. The other 994 run natively on the real processor, unseen by the VMM; only an emulator handles every instruction.

  3. From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI

    Your doctor prints hv_vm_create: HV_BUSY (0xfae94002). What is the most likely cause in your own code?

    Show answer

    A VM already exists in this process: Hypervisor.framework allows one per process. Usually an earlier Vm is still alive, or was dropped without Drop calling hv_vm_destroy.

Concepts you'll need

Chapters before this one: chapter 02, An exception, one level up: your first VM exit.

  • Core, taught here: a bare-metal program (an entry point, a stack, zeroing the BSS, no_std, no_main, a panic handler); loading a flat binary with --raw FILE@ADDR; a run loop; the two debug hypercalls as vendor-specific hypervisor fast calls of the SMC calling convention (SMCCC); --timeout and the virtual machine monitor's (VMM's) exit codes 0, 2, 5 and 6; the first exit trace; the cost of one exit, measured.
  • Core, from earlier: the VM exit, the syndrome and its exception class, and the call-versus-retry rule for the PC (chapter 02); Vcpu, OwnedMapping and VBAR_EL1 (chapter 02).
  • Primers (read first): bare-metal-rust (no_std, no_main, sections, the linker script, load versus run address, the memory management unit (MMU), why nothing gives you a stack); smccc (function IDs, owners, fast calls).
  • Primers (review): aarch64-reading (registers, post-index stores, bl, mrs and msr); host-concurrency (threads, recv_timeout, an atomic flag).
  • Pointers: the rustc book's aarch64-unknown-none page (an Aside); the os-basics primer (exit status) and the ELF primer.
  • Forward definitions: ELF; PSCI and its power-off call; the device tree; MPIDR_EL1; CPACR_EL1; wfe; CNTVCT_EL0; the kick that stops a running vCPU; an address size fault. Each is defined at first use.

This chapter's guest prints hello from guest the way the simplest hardware does: one VM exit per character. Is that a problem? A function call on your Mac costs about a nanosecond. A VM exit stops a CPU mid-program, switches exception level, returns from hv_vcpu_run to a thread in your process, runs your Rust and switches all the way back. That round trip is a world switch. How many nanoseconds is that?

Predict Before you run exit-bench at the end of this chapter: does one hvc round trip, guest to monitor and back, cost nanoseconds (it is a call, like a function call) or microseconds (it is a world switch)? Write a number.

Write your estimate and one sentence of reasoning under ## Predict in your journal.

This chapter measures row 8 of chapter 00's problem ledger, cheap bulk input and output, without solving it yet: your number is the argument for the second half of the course.

Objectives: by the end you can

  • Build a no_std, no_main Rust program for aarch64-unknown-none with a linker script that puts _start at 0x4008_0000, and turn it into a flat binary.
  • Explain each group of lines of the guest's _start: pick a stack, enable floating point, zero the BSS, install the vectors, call main.
  • Implement the debug hypercalls DEBUG_PUTC (x0 = 0xC600_4D01, x1 = byte) and DEBUG_EXIT (x0 = 0xC600_4D02, x1 = code), and decode their IDs as SMCCC vendor-specific hypervisor fast calls.
  • Write a run loop that handles exits repeatedly, a --timeout that stops a hung guest with exit code 5, and the first exit trace (records with t_ns, pc, ec and imm).
  • Measure the cost of one hvc round trip with exit-bench, and compare it with one store instruction timed by the same counter.

Before you start. Run scripts/learner start 03 from the repository root; it copies this chapter's journal to learner/journal/03.md. The monitor parts go into your workspace, learner/. The guests live in guests/, because every later checkpoint runs them against your monitor; when you change them on purpose, git restore guests/ and scripts/build-guests.sh put them back.

Two programs, from now on

From now on there are two Rust programs. The guest runs inside the virtual machine (VM), with no operating system under it. The monitor is our virtual machine monitor (VMM), macvmm, an ordinary macOS program.

The guestThe monitor
Directoryguests/ (its own Cargo workspace)crates/ (yours: learner/crates/)
Target tripleaarch64-unknown-noneaarch64-apple-darwin
Built byscripts/build-guests.sh, then llvm-objcopy to a flat .bincargo build
Runsinside the VM, at EL1, with the MMU offin your terminal, as a macOS process at EL0
Hasno OS, no heap, no std, no main in the usual senseeverything a Mac program has

Aside

aarch64-unknown-none means 64-bit Arm with no operating system, so std does not exist for it; the rustc book's platform page lists what it assumes.

Build the guests from the repository root:

TerminalReal output
scripts/build-guests.sh; ls target/guests/aarch64-unknown-none/release/*.bin | wc -lexit: 0--- stdout ---built 27 guests      27--- stderr ---warning: unknown and unstable feature specified for `-Ctarget-feature`: `strict-align`  |  = note: it is still passed through to the codegen backend, but use of this feature might be unsound and the behavior of this feature can change in the future  = help: consider filing a feature requestwarning: `macvmm-guests` (lib) generated 1 warningwarning: `macvmm-guests` (bin "self-fault") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "regcheck") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "psci-probe") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "mmio-probe") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "mmio-poke") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "memtest") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "isv0-probe") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-reset") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "irq") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-mmio") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-isv0") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-vq") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-flood") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-tty") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hello") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-sysreg") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "flood") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "hostile-smp") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "exit-bench") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "dtb-reader") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "virtio-probe") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "uart-echo") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "tty-hygiene") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "timer-nogic") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "timer") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "sysreg-probe") generated 1 warning (1 duplicate)warning: `macvmm-guests` (bin "smp-race") generated 1 warning (1 duplicate)    Finished `release` profile [optimized + debuginfo] target(s) in 0.01s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run from the repository root; cargo's progress lines on stderr are shown as they came.
course/captures/03-build-guests.txt

This chapter uses hello and exit-bench. With the MMU off an unaligned access faults, so the guests forbid one with strict-align; rustc warns only because it calls that flag unstable, not about your code. Each guest exists twice. ELF (Executable and Linkable Format) is the container the linker writes, the program's pieces with the addresses they want (ELF primer; chapter 13 loads it). Until then we use the .bin, a flat binary: the bytes of memory, in address order, nothing else.

Where the guest's bytes go

The bare-metal-rust primer built a linker script for a toy program. The guests share one. Guest, guests/common/link.ld:

guests/common/link.ldlines 16-57
ENTRY(_start)EXTERN(_start)SECTIONS{  . = 0x40080000;  __image_start = .;  .text : {    KEEP(*(.text.boot))    . = ALIGN(2048);    KEEP(*(.vectors))    *(.text .text.*)  }  .rodata : ALIGN(16) {    *(.rodata .rodata.*)  }  .data : ALIGN(16) {    *(.data .data.*)  }  .bss (NOLOAD) : ALIGN(16) {    __bss_start = .;    *(.bss .bss.*)    *(COMMON)    . = ALIGN(16);    __stacks_start = .;    . += 8 * 0x10000;    __stacks_end = .;    __bss_end = .;  }  __image_end = .;  /DISCARD/ : {    *(.comment)    *(.note .note.*)    *(.eh_frame .eh_frame_hdr)  }}

Three lines matter today. . = 0x40080000 is the link address: RAM starts at 0x4000_0000 in the memory map we borrow from QEMU's virt machine (chapter 05), and the first 512 KiB are kept for the device tree, a description of the machine that the monitor writes into RAM as a DTB (device tree blob), chapter 10. KEEP(*(.text.boot)) comes first, so _start is the flat binary's first byte: with no header naming an entry, the monitor starts the CPU at the load address. And .bss (NOLOAD) holds the variables that start at zero, plus eight 64 KiB stacks, without a byte in the file.

The BSS (from an old assembler's "block started by symbol") is easiest to see with one variable, the console's choice of output device. Guest, guests/common/console.rs:

guests/common/console.rsline 28
static BACKEND: AtomicU8 = AtomicU8::new(Backend::Hvc as u8);

Backend::Hvc is 0, so this lives in .bss. We added static COUNTER: AtomicU32 = AtomicU32::new(0); to a copy of hello and asked where things went:

TerminalReal output
"$LLVM/llvm-nm" -n -C $G/hello | grep -e COUNTER -e BACKEND -e __bss; wc -c < $G/hello.binexit: 0--- stdout ---0000000040082e60 b hello::COUNTER (.0)0000000040082e60 B __bss_start0000000040082e80 b guest::console::BACKEND (.0)0000000040102e90 B __bss_end   11866
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Variant: guests/hello/main.rs gained static COUNTER: AtomicU32 = AtomicU32::new(0), read and printed once (then stored back plus one, so the compiler cannot fold it to a constant); built in a copy of the guests. LLVM is the rustup llvm-tools directory from the bare-metal-rust primer.
course/captures/03-bss-nm.txt

b means a local symbol in the BSS; capital B is a global one, like the linker's __bss_start; (.0) is the field inside the atomic wrapper. The BSS starts at 0x40082e60, 11,872 bytes after _start; the flat binary is 11,866 bytes long. So after the monitor copies the file, COUNTER, BACKEND and all eight stacks hold whatever the RAM held before:

guest RAM after --raw hello.bin@0x400800000x40080000  .text: _start first, vectors at 0x40080800   copied from the file            .rodata, .data                               (11,866 bytes)0x40082e5a  ---------------------------- end of the file0x40082e60  .bss: COUNTER, BACKEND, ...                   NOT in the file:            eight 64 KiB stacks                           old contents of RAM0x40102e90  __bss_end

Nothing in the file says these bytes should be zero. _start has to make them zero.

In the linker-map lab, pick the program "Chapter 03's hello guest, with COUNTER" and check that the symbols show __bss_start at 0x40082e60 and the file ending at 11,866 bytes. Then move .bss above .text and watch where _start goes and what a raw load at 0x40080000 would now get wrong:

Lab

Linker map

Move sections, change the start address and the stack, and watch the symbol addresses, the program headers (filesz versus memsz) and the exact bytes of the flat binary change together.

Runs in browserOpen full page: Linker map
Linker map: the primer's program, from ELF to flat binary to guest memory The default layout. The linker places .text (56 bytes, _start first) at 0x4008_0000, .rodata (GREETING, 6 bytes) at 0x4008_0038, .data (BOOTS, 4 bytes) at 0x4008_0040, and .bss (COUNTER plus a 16 KiB stack, 16,400 bytes, NOLOAD) at 0x4008_0050 up to __stack_top at 0x4008_4060. Three PT_LOAD headers: read-execute 56 bytes, read-only 6 bytes, and read-write with FileSize 4 and MemSize 16,416. objcopy -O binary writes 68 bytes: the code, the text hello and a newline, two bytes of padding, and the value 7. The BSS is not in the file; after --raw bare.bin@0x40080000, everything above byte 68 holds whatever RAM held before, so _start must zero it. bare: where the linker puts every byte (default layout) ELF program headers PT_LOAD R X 0x4008_0000 filesz 56 memsz 56 PT_LOAD R 0x4008_0038 filesz 6 memsz 6 PT_LOAD R W 0x4008_0040 filesz 4 memsz 16,416 bare.bin: 68 bytes 0x00 .text _start, 14 instructions 0x38 .rodata "hello\n" 0x3e padding (2 bytes) 0x40 .data 07 00 00 00 (BOOTS) Guest memory after --raw bare.bin@0x40080000 copied from the file (68 B) gap .bss + stack (16,400 B): old contents of RAM. Zero it yourself! 0x4008_0000 0x4008_0044 0x4008_0050 0x4008_4060 With JavaScript, the lab lets you move sections, add .far, store a pointer and change the load address.

_start: the first instructions of the guest

When the vCPU starts at 0x4008_0000, there is no stack, no zeroed BSS, no vector table. Every general-purpose register, and sp, is zero apart from x0 (and the PC and PSTATE the monitor sets); system registers hold their reset values, for example MPIDR_EL1 = 0x80000000 on the first CPU. Compiled Rust assumes a stack from its first instruction, so the first code is assembly, which global_asm! pastes into the guest crate. Guest, guests/common/start.rs:

guests/common/start.rslines 44-81
global_asm!(    r#"    .section .text.boot, "ax"    .global _start_start:    mrs     x9, mpidr_el1    and     x9, x9, #0xff    cmp     x9, #8    b.hs    .Lpark    adrp    x10, __stacks_start    add     x10, x10, :lo12:__stacks_start    add     x11, x9, #1    lsl     x11, x11, #16    add     x10, x10, x11    mov     sp, x10    mov     x10, #(3 << 20)    msr     cpacr_el1, x10    isb    cbnz    x9, .Lpark    adrp    x10, __bss_start    add     x10, x10, :lo12:__bss_start    adrp    x11, __bss_end    add     x11, x11, :lo12:__bss_end1:  cmp     x10, x11    b.hs    2f    str     xzr, [x10], #8    b       1b2:  adrp    x10, guest_vectors    add     x10, x10, :lo12:guest_vectors    msr     vbar_el1, x10    isb    bl      guest_main    bl      guest_power_off.Lpark:    wfe    b       .Lpark"#);

This notation is new since the aarch64-reading primer:

WrittenMeaning
.section, .globaldirectives: put the code in .text.boot, and export _start to the linker
.Lnamea label private to this file (the assembler drops it)
and a, b, #nbitwise AND: and x9, x9, #0xff keeps the low eight bits
cmp a, bcompare: compute a - b, keep only the condition flags
b.hs Lbranch to L if the last cmp found a >= b, unsigned ("higher or same")
cbnz x, Lbranch to L if register x is not zero
lsl a, b, #nshift b left by n bits into a
#(3 << 20)a constant the assembler computes: 3 shifted left 20, 0x30_0000
1:, 1b, 2fnumbered local labels: 1b is the nearest 1: backwards, 2f the nearest 2: forwards
isbfinish applying system-register changes before the next instruction

Read it in five groups.

  1. Which CPU am I? mrs x9, mpidr_el1 reads MPIDR_EL1, this CPU's identity number; its low eight bits are 0 for the first CPU. A CPU numbered 8 or more parks at .Lpark, where wfe (wait for event) waits in a low-power state, forever.
  2. The stack. adrp and add :lo12: form the address of __stacks_start relative to the PC (the primer says why). x11 = (cpu + 1) << 16 adds 64 KiB per CPU, so x10 is the top of this CPU's stack; stacks grow down. mov sp, x10 matters most in this chapter.
  3. Floating point. The compiler uses the floating-point registers even in ordinary code; until CPACR_EL1, which controls access to them, has its FPEN bits (20 and 21) set, any such instruction traps.
  4. The BSS. cbnz x9, .Lpark sends every CPU but the first away. In chapter 20 the others start at a separate entry, _secondary_start, which picks its own stack the same way; hence eight stacks. Then from __bss_start to __bss_end, str xzr, [x10], #8 stores the zero register and moves x10 on by 8, so both ends must be multiples of 8. The linker script uses 16, because the stacks live in the BSS too and Arm's calling convention requires sp to be a multiple of 16.
  5. Vectors, then Rust. Writing VBAR_EL1 sends a fault inside the guest to a handler that prints a message, not to 0 + 0x200 as in chapter 02. Then bl guest_main calls Rust; if it returns, bl guest_power_off turns the machine off.

A macro gives each guest exactly one guest_main, the symbol the assembly calls. Guest, guests/common/start.rs:

guests/common/start.rslines 168-183
/// Define the guest's entry function: `guest::entry!(main);` with `fn main(x0: u64)`.////// `_start` calls the symbol `guest_main` with the boot argument in `x0` (AAPCS64: the first/// integer argument). The macro gives each guest binary exactly one such symbol, so the/// assembly never depends on the name a guest chose.#[macro_export]macro_rules! entry {    ($main:path) => {        /// The symbol `_start` branches to (common/start.rs).        #[unsafe(no_mangle)]        pub extern "C" fn guest_main(x0: u64) {            let f: fn(u64) = $main;            f(x0)        }    };}

And here is a whole guest. Guest, guests/hello/main.rs:

guests/hello/main.rslines 8-18
#![no_std]#![no_main]use guest::println;guest::entry!(main);fn main(x0: u64) {    println!("hello from guest, x0={x0:#x}");    println!("guest done");}

#![no_std] drops the standard library; #![no_main] drops Rust's usual start-up code. println! is the guests' own macro, one hvc per byte.

A panic needs somewhere to go

On macOS, a panic prints and the process exits. Here there is no process, so the guest writes its own handler. Guest, guests/common/lib.rs:

guests/common/lib.rslines 40-52
#[panic_handler]fn panic(info: &core::panic::PanicInfo<'_>) -> ! {    match info.location() {        Some(loc) => println!(            "guest panic: {} at {}:{}",            info.message(),            loc.file(),            loc.line()        ),        None => println!("guest panic: {}", info.message()),    }    hvc::debug_exit(1)}

It prints where it panicked, then calls DEBUG_EXIT ("stop with this code", next section) with code 1, which the monitor turns into its exit status 6, so a script can tell "the guest failed" from "the monitor failed".

Two hypercalls, numbered by a convention

Before any device exists, the guest needs two services, print a byte and stop with a verdict, each an hvc with the request in registers: the debug hypercalls. Guest, guests/common/hvc.rs:

guests/common/hvc.rslines 20-23
/// `DEBUG_PUTC(x1 = byte)`: one byte to the serial sink, through the VMM's `AnsiFilter`.pub const DEBUG_PUTC: u64 = 0xC600_4D01;/// `DEBUG_EXIT(x1 = code)`: stop the VM; code 0 → macvmm exits 0, anything else → exit 6.pub const DEBUG_EXIT: u64 = 0xC600_4D02;

Read 0xC600_4D01 with the smccc primer's field diagram:

  • bit 31 = 1: a fast call, which runs to completion, unlike a yielding call, which may pause part-way and be resumed;
  • bit 30 = 1: the 64-bit convention, so all of x1 is read, not only its 32-bit w1 half;
  • bits 29 to 24 = 0x06: owner 6, "vendor-specific hypervisor service", for whatever hypervisor is running;
  • bits 23 to 16 = 0: reserved in a fast call (the primer has the one optional exception, bit 16);
  • bits 15 to 0 = 0x4D01: function 0x4D01 of that owner (0x4D is the letter M).

Following the SMC calling convention (SMCCC, after smc, the secure monitor call) means a real kernel, which makes its own requests the same way (chapter 08), never mistakes our call for one of its own. Any function number in owner 6 would do, but one block is taken: on macOS 27 we measured that Hypervisor.framework answers 0xC600_0000 to 0xC600_001F itself, so they never become VM exits. Apple does not document this, so we stay well clear, at 0x4D (M, for macvmm); a Try it below repeats the measurement.

The call puts the ID in x0 and the argument in x1, executes hvc #0, and reads the results back from x0 to x3. SMCCC lets the callee change x4 to x17, so the asm! block tells the compiler those registers hold garbage afterwards (lateout(...) _); DEBUG_MEMHASH in its comment is a later debug call (chapter 04). Guest, guests/common/hvc.rs:

guests/common/hvc.rslines 36-55
/// Make one SMCCC call through `hvc #0` and return `x0..x3`.#[inline(always)]pub fn hvc_call(x0: u64, x1: u64, x2: u64, x3: u64) -> [u64; 4] {    let (mut r0, mut r1, mut r2, mut r3) = (x0, x1, x2, x3);    // SAFETY: `hvc #0` traps to the VMM, which reads and writes only x0..x3 (declared inout)    // and may clobber x4..x17 (declared lateout). It is not `nomem`: DEBUG_MEMHASH reads guest    // memory and DEBUG_PUTC has an effect, so the compiler must not move stores across it.    unsafe {        asm!(            "hvc #0",            inout("x0") r0, inout("x1") r1, inout("x2") r2, inout("x3") r3,            lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,            lateout("x8") _, lateout("x9") _, lateout("x10") _, lateout("x11") _,            lateout("x12") _, lateout("x13") _, lateout("x14") _, lateout("x15") _,            lateout("x16") _, lateout("x17") _,            options(nostack),        );    }    [r0, r1, r2, r3]}
guests/common/hvc.rslines 59-62
/// Print one byte through the VMM (`hvc #0` with `x0 = 0xC600_4D01`, `x1 = byte`).pub fn debug_putc(byte: u8) {    hvc_call(DEBUG_PUTC, u64::from(byte), 0, 0);}
guests/common/hvc.rslines 66-70
/// Stop the VM with `code` (0 = success). Never returns: if the VMM ignored the call, spin.pub fn debug_exit(code: u32) -> ! {    hvc_call(DEBUG_EXIT, u64::from(code), 0, 0);    crate::psci::halt()}

debug_exit never returns: if the monitor ignored the call, the guest halts.

Good place to stop. The guest side is read; the rest of the chapter builds the monitor side in your workspace and needs your Mac.

A run command

Now the monitor. Every later checkpoint drives it through the subcommand run, so its command line is an interface with exact rules. Write it with std::env::args and a match on each flag, no crate (the reference: crates/macvmm/src/cli.rs).

FlagAcceptsRefused
--mem SIZEa number, optionally with a K, M or G suffix: 64M (the reference also takes KiB and similar; yours may be stricter)no digits, another suffix, a product that overflows 64 bits
--raw FILE@0xADDRa file, @, a hex address with 0x (_ separators allowed, as in Rust: 0x4008_0000); split at the last @, because a file name may itself contain oneno @, an empty file name, no 0x, not hex, more than 64 bits
--timeout SECSa whole number of seconds, at least 10, fractions, anything else
--trace exits:FILE[:hvc]a file for the exit trace; :hvc keeps only hvc exitsno exits: prefix, no file name, the flag given twice

Any refusal, and any flag not in the table, is a usage error: print a one-line reason on standard error and exit with status 2 before creating a VM. The reference has more flags; yours need not.

From here on, commands run in one of two places, with $G pointing at the built guests (set it again in a new terminal):

Shell
G=target/guests/aarch64-unknown-none/release      # at the repository root: the reference monitorG=../target/guests/aarch64-unknown-none/release   # in learner/: your monitor

Three refusals from the reference monitor, at the repository root, each printing only the first line of its error (the full usage text follows it):

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@40080000 2>err.txt; echo "exit status $?"; head -n 1 err.txtexit: 0--- stdout ---exit status 2macvmm: --raw FILE@ADDR: ADDR needs a 0x prefix
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor at the repository root, G=target/guests/aarch64-unknown-none/release, in zsh, the default macOS shell; bash gives the same output. An address without 0x. The usage text after the first line of standard error is cut by head -n 1.
course/captures/03-usage-no-0x.txt
TerminalReal output
cargo run -q -p macvmm -- run --memory 64M 2>err.txt; echo "exit status $?"; head -n 1 err.txtexit: 0--- stdout ---exit status 2macvmm: run: unknown flag "--memory"
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor at the repository root, G=target/guests/aarch64-unknown-none/release, in zsh, the default macOS shell; bash gives the same output. A flag that does not exist. The usage text after the first line of standard error is cut by head -n 1.
course/captures/03-usage-unknown-flag.txt
TerminalReal output
cargo run -q -p macvmm -- run --mem 64Q 2>err.txt; echo "exit status $?"; head -n 1 err.txtexit: 0--- stdout ---exit status 2macvmm: --mem: invalid size "64Q": use a number with K, M or G
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor at the repository root, G=target/guests/aarch64-unknown-none/release, in zsh, the default macOS shell; bash gives the same output. A size with an unknown suffix. The usage text after the first line of standard error is cut by head -n 1.
course/captures/03-usage-bad-size.txt

Loading a flat binary

--raw FILE@ADDR copies a file's bytes to guest address ADDR. The string comes from the user, so it is parsed strictly. Monitor, crates/vmm/src/loader/raw.rs:

crates/vmm/src/loader/raw.rslines 54-75
/// Parse `FILE@0xADDR` (module docs).pub fn parse_spec(s: &str) -> Result<RawSpec, RawSpecError> {    let (path, addr) = s.rsplit_once('@').ok_or(RawSpecError::MissingAt)?;    if path.is_empty() {        return Err(RawSpecError::EmptyPath);    }    let hex = addr        .strip_prefix("0x")        .or_else(|| addr.strip_prefix("0X"))        .ok_or(RawSpecError::MissingHexPrefix)?;    // `_` separators are allowed (`0x4008_0000`), like Rust literals; nothing else is.    let digits: String = hex.chars().filter(|&c| c != '_').collect();    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {        return Err(RawSpecError::BadAddress);    }    // `from_str_radix` fails on overflow: more than 64 bits is an error, never a wrap.    let addr = u64::from_str_radix(&digits, 16).map_err(|_| RawSpecError::BadAddress)?;    Ok(RawSpec {        path: PathBuf::from(path),        addr,    })}

F@40080000 is refused, not guessed at. Then the whole file must land inside guest RAM. Monitor, crates/vmm/src/loader/raw.rs and crates/vmm/src/loader/mod.rs:

crates/vmm/src/loader/raw.rslines 79-91
/// Check that `len` bytes at `addr` fit inside guest RAM, and describe the placement.pub fn check_placement(    ram: RamRange,    index: usize,    addr: u64,    len: u64,) -> Result<Placement, LoaderError> {    let what = format!("--raw blob {index}");    if !ram.contains(addr, len) {        return Err(LoaderError::OutsideRam { what, addr, len });    }    Ok(Placement { what, addr, len })}
crates/vmm/src/loader/mod.rslines 75-91
/// The guest RAM the loaders may write: `[base, base + size)`.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct RamRange {    pub base: u64,    pub size: u64,}impl RamRange {    /// True if `[addr, addr + len)` lies inside RAM (`len > 0`, no overflow).    pub fn contains(&self, addr: u64, len: u64) -> bool {        let (Some(end), Some(ram_end)) = (addr.checked_add(len), self.base.checked_add(self.size))        else {            return false;        };        len > 0 && addr >= self.base && end <= ram_end    }}

Security

The file and the address are untrusted input, so contains uses checked_add, never +. In a default release build 0xffff_ffff_ffff_f000 + 0x2000 wraps to 0x1000, passes an "end is below the end of RAM" test, and the copy runs off the top of memory. With overflow-checks on, as in our workspace, it panics instead; checked_add gives a clean refusal, exit code 2.

Planning more than one blob

--raw may be given more than once, so the loader plans all the blobs, then copies. Monitor, crates/vmm/src/loader/plan.rs and crates/vmm/src/loader/mod.rs:

crates/vmm/src/loader/plan.rslines 271-289
for (index, (addr, bytes)) in inputs.raw.iter().enumerate() {    let len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);    let p = raw::check_placement(ram, index, *addr, len)?;    if overlaps(p.addr, p.len, dtb.addr, dtb.len) {        return Err(LoaderError::OverlapsDtb { what: p.what });    }    if let Some(other) = images        .iter()        .find(|o| overlaps(p.addr, p.len, o.addr, o.len))    {        return Err(LoaderError::Overlap {            a: p.what,            b: other.what.clone(),        });    }    entry = entry.or(Some(p.addr));    images.push(p);}let entry = entry.ok_or(LoaderError::NoImage)?;
crates/vmm/src/loader/mod.rslines 95-101
/// Half-open ranges `[a, a + alen)` and `[b, b + blen)` intersect (both assumed in RAM, so/// the ends do not overflow; an overflowing end is treated as reaching `u64::MAX`).pub fn overlaps(a: u64, alen: u64, b: u64, blen: u64) -> bool {    let a_end = a.saturating_add(alen);    let b_end = b.saturating_add(blen);    a < b_end && b < a_end}

Three rules, each a usage error: no blob may overlap another; no blob may touch the first 512 KiB of RAM, the device tree's slot (dtb in the code, OverlapsDtb); and the first blob is the entry point, so with no blob there is nothing to run (NoImage).

The checkpoint's contract tests call your code by these names, and compare whole results with assert_eq!:

ModuleItemMust have
vmm::loader::rawparse_spec, returning RawSpec { path: PathBuf, addr }Debug, PartialEq
RawSpecError: MissingAt, EmptyPath, MissingHexPrefix, BadAddressDebug, PartialEq
check_placement
vmm::loader::planplan(ram, &inputs), returning a BootPlan whose entry says where to startDebug, PartialEq
BootInputs { kernel: Option<&[u8]>, raw: &[(u64, Arc<[u8]>)] }; kernel is None until chapter 13Default
vmm::loaderRamRange
LoaderError: at least OutsideRam, OverlapsDtb, Overlap, NoImageDebug, PartialEq

For guest RAM, map 64 MiB at 0x4000_0000 with chapter 02's OwnedMapping (chapter 04 replaces it). Copy each blob in with OwnedMapping::write(ADDR - 0x4000_0000, bytes), an offset into the mapping, not a guest address. Then set the PC to the entry, PSTATE to 0x3c5 as in chapter 02, and x0 to 0x4000_0000 (the checkpoint accepts any value).

A loop that answers exit after exit

A guest that prints hello from guest needs one answer per byte, so the run becomes a run loop: run, decode, handle, decide whether to go back in. Here is the reference's, which later chapters extend. Monitor, crates/vmm/src/vcpu/run_loop.rs:

crates/vmm/src/vcpu/run_loop.rslines 66-123
/// Run `vcpu` until the VM stops. Every outcome, including a framework error, ends in/// `ctl.request_stop`, so the control thread always learns why.pub fn run(vcpu: &mut Vcpu<'_>, env: &ExitEnv<'_>, obs: &Observe<'_>, log: &mut VcpuLog) {    let ctl = env.ctl;    loop {        if ctl.is_stopping() {            return;        }        let raw = match vcpu.run() {            Ok(raw) => raw,            Err(e) => {                ctl.request_stop(StopReason::Vmm(e));                return;            }        };        let exit = Exit::from_hv(raw.reason, raw.esr);        log.stats            .record(&exit, raw.esr, raw.reason == hvf::ExitReason::Exception);        let t_ns = obs.clock.now_ns();        let mut rec = ExitRecord::new(            t_ns,            vcpu.index,            env.generation,            &raw,            &exit,            vcpu.pc().ok(),        );        let action = exit::handle_watched(vcpu, env, &exit, &raw, &mut rec);        if let Some(trace) = obs.trace {            trace.record(&rec);        }        log.ring.push(rec);        let step = match action {            Ok(ExitAction::Resume { advance_pc: true }) => vcpu.advance_pc(),            Ok(ExitAction::Resume { advance_pc: false }) => Ok(()),            Ok(ExitAction::Stop(StopReason::GuestFatal(mut g))) => {                g.last_exits = log.ring.last(FATAL_LAST_EXITS);                ctl.request_stop(StopReason::GuestFatal(g));                return;            }            Ok(ExitAction::Stop(reason)) => {                ctl.request_stop(reason);                return;            }            // A vCPU that powered itself off (chapter 20): park outside `hv_vcpu_run` until it is            // powered on again or the VM stops.            Ok(ExitAction::CpuOff) => match park(vcpu, ctl) {                Some(on) => vcpu.power_on(&on),                None => return,            },            Err(e) => Err(e),        };        if let Err(e) = step {            ctl.request_stop(StopReason::Vmm(e));            return;        }    }}

You need its skeleton: vcpu.run(), decode the syndrome as chapter 02 did (Exit::from_hv), handle the exit, then resume or stop: the loop with its first match, the Exit::from_hv line, and the match action arms Resume and Stop. Skip the rest for now: ring (chapter 07), stats (chapter 11), generation (chapter 21), GuestFatal (chapter 06), CpuOff (chapter 20), and obs.trace (next section). The stop flag at the top is an atomic boolean another thread sets to ask the vCPU to stop; your monitor gains it in chapter 09.

An hvc exit is an SMCCC call: read x0 to x3, dispatch on the ID, write back the results. Monitor, crates/vmm/src/vcpu/exit.rs:

crates/vmm/src/vcpu/exit.rslines 272-309
fn smccc_call(    regs: &mut dyn VcpuRegs,    env: &ExitEnv<'_>,    conduit: Conduit,    imm: u16,    rec: &mut ExitRecord,) -> Result<ExitAction> {    let x = [regs.x(0)?, regs.x(1)?, regs.x(2)?, regs.x(3)?];    let [x0, ..] = x;    rec.func = smccc::function_name(x0);    rec.action = Some(if smccc::is_psci(x0) {        Action::Psci    } else {        Action::Smccc    });    let ctx = smccc::Ctx {        mem: env.mem,        serial: env.serial,        ctl: env.ctl,        vcpu: regs.index(),        generation: env.generation,        debug_calls: env.debug_calls,    };    match smccc::dispatch(&ctx, &smccc::Call { conduit, imm, x }) {        smccc::Outcome::Stop(r) => Ok(ExitAction::Stop(r)),        smccc::Outcome::CpuOff => Ok(ExitAction::CpuOff),        smccc::Outcome::Return(values) => {            for (n, v) in (0u8..).zip(values) {                if let Some(v) = v {                    regs.set_x(n, v)?;                }            }            Ok(ExitAction::Resume {                advance_pc: conduit == Conduit::Smc,            })        }    }}

Its last lines hold the call rule: advance_pc: conduit == Conduit::Smc. An smc must be stepped past; an hvc must not, because the hardware already moved the PC (chapter 02). debug_calls is true only for test guests loaded with --raw, so a real kernel never gets the debug calls (chapter 08); your first version can answer them unconditionally. Only the first two matter today. Monitor, crates/vmm/src/smccc.rs:

crates/vmm/src/smccc.rslines 319-338
fn debug_call(ctx: &Ctx<'_>, fid: u32, x: [u64; 4]) -> Outcome {    let [_, x1, x2, _] = x;    match fid {        DEBUG_PUTC => {            let [byte, ..] = x1.to_le_bytes(); // the low byte; the rest of x1 is ignored            ctx.serial.write_guest(&[byte]);            ret(0)        }        // A code that does not fit in 32 bits saturates, so it can never read as 0 (success).        DEBUG_EXIT => Outcome::Stop(StopReason::DebugExit(u32::try_from(x1).unwrap_or(u32::MAX))),        DEBUG_MEMHASH => match memhash(ctx.mem, x1, x2, ctx.ctl) {            Some(h) => Outcome::Return([Some(0), Some(h), None, None]),            None => ret(INVALID_PARAMETERS),        },        DEBUG_BOOT_COUNT => Outcome::Return([Some(0), Some(ctx.generation), None, None]),        _ => ret(NOT_SUPPORTED),    }}

DEBUG_PUTC writes the low byte of x1 to standard output and returns 0. DEBUG_EXIT stops the VM with the guest's code. _start ends with a third, guest_power_off: SYSTEM_OFF, ID 0x8400_0008, the standard Arm power-off call of the Power State Coordination Interface (PSCI, chapter 08). Every other ID answers -1, NOT_SUPPORTED (u64::MAX in x0); log unknown IDs, but limit how many. Your first version is a match with four arms: DEBUG_PUTC, DEBUG_EXIT, SYSTEM_OFF (stop, exit 0), and everything else (-1).

Security

DEBUG_PUTC's bytes come from the guest, and an escape sequence can repaint or reprogram your terminal. The reference filters them through write_guest, the AnsiFilter its comments name; chapter 09 builds that filter. For now, write any byte outside printable ASCII and newline as ?.

Run hello with your monitor, from learner/:

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor at the repository root, where G=target/guests/aarch64-unknown-none/release (built by scripts/build-guests.sh).
course/captures/03-first-hello.txt

Two lines, exit status 0, from the power-off call. x0=0x40000000 is where the device tree will go (chapter 10); printing it proves that a register you set arrives.

Counting exits: the first trace

You can now count exits instead of believing in them, with an exit trace. With --trace exits:FILE:hvc, the monitor writes one line of JSON (JavaScript Object Notation) per hvc exit: numbers and names from fixed tables, never bytes the guest chose. Monitor, crates/vmm/src/trace.rs:

crates/vmm/src/trace.rslines 141-195
/// One exit, as the trace and the ring keep it. Numbers and static names only, so no byte the/// guest chose can reach a terminal or a log.#[derive(Clone, Debug, Default, PartialEq, Eq)]pub struct ExitRecord {    pub t_ns: u64,    pub vcpu: u32,    pub reason: TraceReason,    pub ec: Option<u8>,    pub pc: Option<u64>,    pub ipa: Option<u64>,    pub wnr: Option<bool>,    pub size: Option<u8>,    pub reg: Option<u8>,    pub value: Option<u64>,    pub imm: Option<u16>,    pub sysreg: Option<&'static str>,    /// The trapped register's `hv_sys_reg_t` encoding (EC 0x18): a number, so the rule holds.    pub sysreg_enc: Option<u16>,    pub func: Option<&'static str>,    pub action: Option<Action>,    pub isv: Option<bool>,    pub boot: Option<u64>,}impl ExitRecord {    /// The fields known before the exit is handled. Handlers add `wnr`..`value`, `fn`,    /// `sysreg`, `action`.    pub fn new(        t_ns: u64,        vcpu: usize,        generation: u64,        raw: &hvf::VcpuExit,        exit: &Exit,        pc: Option<u64>,    ) -> ExitRecord {        let reason = TraceReason::from_hv(raw.reason);        let exception = reason == TraceReason::Exception;        let (imm, ipa) = match *exit {            Exit::Hvc { imm } | Exit::Smc { imm } | Exit::Brk { imm } => (Some(imm), None),            Exit::DataAbort(_) | Exit::InstructionAbort { .. } => (None, Some(raw.ipa)),            _ => (None, None),        };        ExitRecord {            t_ns,            vcpu: u32::try_from(vcpu).unwrap_or(u32::MAX),            reason,            ec: exception.then_some(crate::arch::esr::esr_ec(raw.esr)),            pc,            ipa,            imm,            boot: (generation > 0).then_some(generation),            ..ExitRecord::default()        }    }}

Your first version writes eight of those fields by hand with format!. The checkpoint parses the lines and searches them for exact text, so match this record's keys, their order and its punctuation exactly; your t_ns and pc will differ.

format:{"t_ns":232541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008117c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"}

No spaces. t_ns (nanoseconds since the VM started: std::time::Instant, or mach_absolute_time as in the reference), vcpu and imm are plain numbers; reason is "exception"; ec and pc are hex strings written with {:#x}. fn (func in Rust, where fn is a keyword) names the call (DEBUG_PUTC, DEBUG_EXIT, PSCI_SYSTEM_OFF); action is smccc for the debug calls and psci for the power-off. The checkpoint looks for the exact text "reason":"exception","ec":"0x16" and "fn":"PSCI_SYSTEM_OFF","action":"psci", and counts lines containing "ec":"0x16".

Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --trace exits:h.jsonl:hvc --timeout 10grep -c '"ec":"0x16"' h.jsonl
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --trace exits:h.jsonl:hvc --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor, G=target/guests/aarch64-unknown-none/release; the trace file h.jsonl is written to the current directory.
course/captures/03-hello-trace-run.txt
TerminalReal output
grep -c '"ec":"0x16"' h.jsonl; head -n 2 h.jsonl; tail -n 1 h.jsonlexit: 0--- stdout ---44{"t_ns":232541,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008117c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"}{"t_ns":248750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x4008117c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"}{"t_ns":423416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810ac","imm":0,"fn":"PSCI_SYSTEM_OFF","action":"psci"}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Reads the trace file written by the run in 03-hello-trace-run.txt.
course/captures/03-trace-count.txt

44 records: the output is 43 bytes (31 characters, a newline, 10 characters, a newline), plus the power-off. The DEBUG_PUTC records' pc, 0x4008117c, is the instruction after an hvc in the console's print routine. The output took about 190 µs, 4.4 µs per exit, terminal and trace file included.

Try it

Watch Hypervisor.framework answer a call before your monitor sees it. In guests/common/hvc.rs, change DEBUG_PUTC to 0xC600_0001 and run scripts/build-guests.sh. Then run the command below with the reference monitor at the repository root. Look for: no output, and a trace with only the power-off record. Afterwards: git restore guests/, then scripts/build-guests.sh.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --trace exits:id1.jsonl:hvc --timeout 10; cat id1.jsonlexit: 0--- stdout ---{"t_ns":209458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400810ac","imm":0,"fn":"PSCI_SYSTEM_OFF","action":"psci"}
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it variant: DEBUG_PUTC changed from 0xC600_4D01 to 0xC600_0001 in guests/common/hvc.rs (the number first planned for it); built in a copy of the guests, run with the reference monitor.
course/captures/03-putc-0001.txt

Nothing printed, and the trace holds only the power-off: Hypervisor.framework answered 43 hvc instructions inside macOS.

When the guest never calls: --timeout

Chapter 02's break 1 left you pressing Ctrl-C: a guest in b . never exits, so hv_vcpu_run never returns. The vCPU's thread is stuck inside it, so the reference's main thread waits for "the VM stopped" or the deadline, whichever comes first. Monitor, crates/vmm/src/vcpu/manager.rs:

crates/vmm/src/vcpu/manager.rslines 252-254
if !ctl.wait_until(deadline) {    ctl.request_stop(StopReason::Timeout);}

request_stop(Timeout) sets the stop flag, then kicks the vCPU: hv_vcpus_exit makes a running hv_vcpu_run return with the reason CANCELED (chapter 09). Yours can be simpler. Spawn a thread and create the vCPU inside it: a vCPU belongs to the thread that created it (chapter 02), which is why your Vcpu is not Send. Move the plan's entry point into the closure, run the loop there, and send the stop reason (power-off, or DEBUG_EXIT's code) back over a channel. The main thread calls recv_timeout(Duration::from_secs(n)); if the deadline wins, it prints a message containing timeout to standard error (the checkpoint looks for it) and exits with status 5, which ends the vCPU too.

Now make a hung guest on purpose, b . as four bytes, 0x14000000 stored little-endian (printf escapes are octal: \024 is 0x14), and run it with your monitor from learner/ (the output below is the reference's; yours should say the same):

Shell
printf '\000\000\000\024' > spin.bincargo run -q -p macvmm -- run --mem 64M --raw spin.bin@0x40080000 --timeout 1; echo "exit status $?"
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw spin.bin@0x40080000 --timeout 1; echo "exit status $?"exit: 0--- stdout ---exit status 5--- stderr ---macvmm: timeout: the guest was still running after --timeout 1s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor; spin.bin is the four bytes 00 00 00 14 made by the printf command in the lesson.
course/captures/03-spin-timeout.txt

The monitor's exit status is now part of its interface. Monitor, crates/vmm/src/control.rs:

crates/vmm/src/control.rslines 144-154
pub fn exit_code(&self) -> i32 {    match self {        StopReason::PowerOff | StopReason::DebugExit(0) => 0,        StopReason::Vmm(e) => e.exit_code(),        StopReason::GuestFatal(_) => 3,        StopReason::Reset => 4,        StopReason::Timeout => 5,        StopReason::DebugExit(_) => 6,        StopReason::UserQuit => 130,    }}

This chapter meets 0 (power-off, or DEBUG_EXIT with 0), 2 (a usage error), 5 (timeout) and 6 (DEBUG_EXIT with any other code); the reference card lists the rest.

Breaking it on purpose

Two breaks in the guest's start-up code. Unless a step says your monitor, run from the repository root with the reference monitor, and rebuild the guests after every edit.

Deliberate breakage 1: delete the BSS-zeroing loop. In guests/common/start.rs, delete the eight lines from adrp x10, __bss_start to b 1b, and on the next line remove only the 2: prefix (keep adrp x10, guest_vectors). Then, in guests/hello/main.rs:

  1. Import AtomicU32 and Ordering from core::sync::atomic, and add the COUNTER static from earlier at the top level.
  2. In main, read it with COUNTER.load(Ordering::Relaxed) and print it with println!("hello: COUNTER = {:#x}", ...).
  3. Store it back plus one, so the compiler cannot treat it as a constant.

Rebuild and run.

Predict Nothing sets COUNTER to zero any more. Will it print 0?

Run it before you read on.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000hello: COUNTER = 0x0guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: the BSS-zeroing loop (the eight lines from adrp x10, __bss_start to b 1b) deleted from _start in guests/common/start.rs, and hello given the COUNTER static of 03-bss-nm.txt; built in a copy of the guests, run with the unmodified reference monitor.
course/captures/03-bss-nozero.txt

It prints 0. Now break the monitor too: in your raw loader, fill guest RAM from the load address to its end with 0xA5 before copying the file, like RAM left by a previous program. Run the same guest with your monitor (we made the same change in a copy of the reference's loader).

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000hello: COUNTER = 0xa5a5a5a5guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage, second half: the same guest as 03-bss-nozero.txt (no BSS zeroing), run by a copy of the monitor whose raw loader first fills guest RAM from the load address to the end of RAM with the byte 0xA5, then copies the file (two added lines in crates/vmm/src/loader/plan.rs).
course/captures/03-bss-a5.txt

0xa5a5a5a5. Put the zeroing loop back, keep the 0xA5 fill, and run again:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000hello: COUNTER = 0x0guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The fix: the BSS-zeroing loop restored (hello still has COUNTER), run by the same 0xA5-filling copy of the monitor as 03-bss-a5.txt.
course/captures/03-bss-a5-fixed.txt

What you saw: a zero that came from fresh memory, not from the program. The misconception: "a static that starts at zero is zero by itself". On macOS the loader and the kernel's zero pages do it; bare metal has neither, so _start must. The tool: poison fresh memory with an implausible pattern, then look for it.

Deliberate breakage 2: delete the stack setup. Restore the guests, delete the line mov sp, x10 from _start, and rebuild. Run it with the reference monitor, which can kick a hung vCPU and record that in a full trace (no :hvc filter); yours gains the kick in chapter 09.

Predict What does sp hold when guest_main starts, and what will you see?

Write it under Q2 in your journal, then run it.

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --trace exits:nosp.jsonl --timeout 2; echo "exit status $?"; cat nosp.jsonlexit: 0--- stdout ---exit status 5{"t_ns":2002196583,"vcpu":0,"reason":"canceled","pc":"0x40080a00"}--- stderr ---macvmm: timeout: the guest was still running after --timeout 2s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: the one instruction mov sp, x10 deleted from _start in guests/common/start.rs (the stack pointer is never set); built in a copy of the guests, run with the unmodified reference monitor from the repository root, every exit traced.
course/captures/03-no-stack.txt

No output, exit status 5, and one trace record: canceled, the timeout's kick, with the guest's PC at 0x40080a00. What was sp? We added eight instructions at the top of _start that print one character through DEBUG_PUTC: A if sp is exactly 0, ? otherwise:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/hello.bin@0x40080000 --timeout 2exit: 5--- stdout ---A--- stderr ---macvmm: timeout: the guest was still running after --timeout 2s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Probe: the guest of 03-no-stack.txt (no mov sp, x10) with eight instructions added at the very top of _start: mov x1, sp; mov x2, #0x41; cbz x1, 3f; mov x2, #0x3f; 3: mov x1, x2; then x0 = 0xC6004D01 (DEBUG_PUTC) and hvc #0. It prints A if sp is exactly 0 and ? otherwise.
  • Built in a copy of the guests (G points at that copy's release directory); run with the reference monitor at the repository root.
course/captures/03-sp-probe.txt

sp was 0: Hypervisor.framework starts it there, like every general-purpose register. Now the code that ran:

TerminalReal output
"$LLVM/llvm-objdump" -d $G/hello | grep -A2 -e "<guest_main>:" -e "^40080a00"exit: 0--- stdout ---40080a00: d10483ff     	sub	sp, sp, #0x12040080a04: a90007e0     	stp	x0, x1, [sp]40080a08: d2800080     	mov	x0, #0x4                // =4--0000000040081040 <guest_main>:40081040: d10083ff     	sub	sp, sp, #0x2040081044: a90103fe     	stp	x30, x0, [sp, #0x10]
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Disassembly of the guest built for 03-no-stack.txt; LLVM is the rustup llvm-tools directory from the bare-metal-rust primer.
course/captures/03-no-stack-disasm.txt

guest_main starts with sub sp, sp, #0x20: 0 - 0x20 wraps to 0xffff_ffff_ffff_ffe0, and its next store goes far above any memory. With the MMU off, an address too large to be physical is an address size fault, taken at the guest's own level, EL1.

In chapter 02, 0x200 was a plausible address with no memory behind it, so the monitor heard about it. 0xffff_ffff_ffff_ffe0 is too wide to be an address at all, so the CPU rejects it inside the guest; EL2 has nothing to forward. The CPU went to the guest's handler at VBAR_EL1 + 0x200, 0x40080a00, which stores through the same bad stack and faults again, forever, without a VM exit.

What you saw: a hang in the guest's own exception handler. The misconception: that the CPU or the monitor provides a stack; nothing does, and even the fault handler needs one. The tool: --timeout plus the trace, whose last record says where the vCPU was.

Before going on: git restore guests/, then scripts/build-guests.sh, and remove the 0xA5 fill from your loader (or keep it behind a debug flag; it is a useful poison).

What one exit costs

Back to the opening question. exit-bench makes 100,000 calls with an ID nobody implements, 0xC600_00FF, above Hypervisor.framework's block, so every call is a real exit. The monitor does very little work: decode, dispatch, answer -1, plus the bookkeeping every exit gets (statistics, the exit ring, a rate-limited warning). Guest, guests/exit-bench/main.rs:

guests/exit-bench/main.rslines 24-32
let t0 = guest::cntvct();let mut bad = 0u64;for _ in 0..N {    let r = guest::hvc::hvc_call(UNKNOWN_FN, 0, 0, 0);    if r[0] != u64::MAX {        bad += 1; // the VMM must answer NOT_SUPPORTED (-1)    }}let ticks = guest::cntvct().wrapping_sub(t0);

The clock is CNTVCT_EL0, the CPU's virtual counter, which counts up at a fixed rate (chapter 11 builds timers on it). Guest, guests/common/lib.rs:

guests/common/lib.rslines 56-64
/// Read the virtual counter `CNTVCT_EL0` (ARM ARM, CNTVCT_EL0 register description). The `isb`/// stops the read from being taken early, out of program order (ARM ARM, "Reading the/// counter" in the Generic Timer chapter).pub fn cntvct() -> u64 {    let v: u64;    // SAFETY: reads a counter register; no memory access, no side effects.    unsafe { core::arch::asm!("isb", "mrs {}, cntvct_el0", out(reg) v, options(nomem, nostack)) };    v}
Shell
cargo run -q -p macvmm -- run --mem 64M --raw $G/exit-bench.bin@0x40080000 --timeout 30
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/exit-bench.bin@0x40080000 --timeout 30exit: 0--- stdout ---exit-bench: 100000 hvc in 3433366 ticks, 1430 ns/exit--- stderr ---macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (989 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)macvmm: warn: [vcpu0] guest: unknown SMCCC function 0xc60000ff; returning -1 (999 similar messages suppressed)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Run with the reference monitor at the repository root, G=target/guests/aarch64-unknown-none/release.
course/captures/03-exit-bench-run.txt

The guest divides by the frequency in CNTFRQ_EL0. Check: 3,433,366 ticks / 100,000 is 34.3 ticks per exit, and 1,430 ns / 34.3 is 41.7 ns per tick, a 24 MHz counter. Two runs on our Mac gave 1,430 and 1,415 ns (the second is below). Load and power state move it: on an idle Mac on AC power expect roughly 1.3 to 2 µs. In that time the CPU leaves the guest, enters EL2, returns to macOS, wakes our thread, runs our Rust, and goes all the way back.

hello's 4.4 µs included tracing, formatting and cold caches. Use your number to estimate how long 4 KiB through DEBUG_PUTC takes, and write it under Q1 before reading on.

The 110 warn lines report the unknown ID: ten in full, then one per thousand. A guest decides how often it calls, so even our complaints are limited.

Now compare with one store instruction. A tick is too coarse to time one store, but a million can be timed. This step is part of the measurement, not optional:

  1. In guests/exit-bench/main.rs, after the final println!, read guest::cntvct(), then for i from 0 to 1,000,000 store i into a local u64 with core::ptr::write_volatile(&mut local, i), then read the counter again.
  2. Compute picoseconds per store in u128: ticks * 1_000_000_000_000 / freq / 1_000_000. Print it as exit-bench: 1000000 stores in {ticks} ticks, {ps} ps/store.
  3. Run scripts/build-guests.sh. Then run the command below with the reference monitor at the repository root; --log error, a reference flag your monitor does not have, hides the 110 warnings.
  4. Undo the change and rebuild: git restore guests/, then scripts/build-guests.sh.
TerminalReal output
cargo run -q -p macvmm -- --log error run --mem 64M --raw $G/exit-bench.bin@0x40080000 --timeout 30exit: 0--- stdout ---exit-bench: 100000 hvc in 3398102 ticks, 1415 ns/exitexit-bench: 1000000 stores in 5606 ticks, 233 ps/store
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Store-loop step: guests/exit-bench/main.rs gained a second loop that times 1,000,000 volatile 8-byte stores to a local variable with the same counter and prints ps (picoseconds) per store; built in a copy of the guests (G points at that copy's release directory), run with the reference monitor at the repository root.
  • --log error hides the 110 rate-limited warnings shown in 03-exit-bench-run.txt.
course/captures/03-store-loop.txt

233 picoseconds per store, loop included: about one store per cycle. (Every store goes to the same stack slot, and the guest never has to stop for any of them. Don't read much into the absolute number; the point is the ratio.) One exit costs about six thousand stores: the exit cost. A disk delivering 4 KiB a byte at a time would cost 4,096 exits. That is ledger row 8, measured: from chapter 15 on, devices stop talking byte by byte and share memory instead.

Your turn

Your workspace now has run with four flags, a loop with four answers, and exit codes 0, 2, 5 and 6. Check, from inside learner/:

  1. hello prints two lines and exits 0; with --trace, the trace has 44 hvc records.
  2. spin.bin with --timeout 1 prints timeout on standard error and exits 5.
  3. exit-bench prints its line; your number goes in your journal.
  4. Your journal has answers under Predict and Q1 to Q3 (Q1 needs your exit-bench number; Q3 is the open question below).

Stuck? scripts/learner hint 03 gives four hints, from a nudge to the exact reference file.

Checkpoint

From the repository root:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 03

You should see, as the last line:

CHECKPOINT 03 PASS

It runs the contract tests for your raw loader, then your monitor four times: hello; hello traced, with hvc records numbering the printed bytes plus 1; the b . blob with --timeout 1 (exit 5); and exit-bench (format only). Then it checks your journal. Against an unmodified copy of the reference:

TerminalReal output
scripts/checkpoint.sh 03exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   raw_loader (6 tests)[PASS] runs on your Mac hello: 2/2 serial markers, exit 0 in 0.07s[PASS] runs on your Mac hello-trace: 2/2 serial markers, 2/2 trace markers, 44 "ec":"0x16" records = 43 stdout bytes + 1, exit 0 in 0.01s[PASS] runs on your Mac timeout: 1/1 serial markers, exit 5 in 1.01s[PASS] runs on your Mac exit-bench: 1/1 serial markers, exit 0 in 0.15s[INFO] journal          not checked (not a learner tree)CHECKPOINT 03 PASS
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The chapter's checkpoint, run against an unmodified copy of the reference (scripts/checkpoint.sh 03 --impl <tree>): what a finished chapter 03 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/03-checkpoint.txt

What now works:

  • a Rust program with no operating system runs in your VM, with its own stack, BSS and panic handler;
  • your monitor loads a flat binary safely, answers exit after exit, stops a hung guest, and reports why in its exit status;
  • you can count a guest's exits, and you know what one costs.

The next chapter starts from this state (the reference at the end of chapter 03).

What's next

So far guest RAM is one OwnedMapping and a write method. Chapter 04 asks what it means to share memory with a guest that may be changing it at the same instant, and why the only safe way to touch it is a bounds-checked copy.

Open question

hello printed 43 bytes through DEBUG_PUTC, and your monitor wrote every one to your terminal. A guest you did not write sends a million bytes, or a billion, as fast as it can. What does your monitor do with them, and which limit would you add?

Spec hunt

  • Arm's SMC Calling Convention (document DEN 0028), the section on function identifiers and its table of owning entity numbers: which owner would a call to a trusted operating system use, and why can no PSCI call ever equal 0xC600_4D01?
  • ARM ARM (DDI 0487), register pages CNTVCT_EL0 and CNTFRQ_EL0: who writes the frequency, and why does exit-bench read it instead of assuming 24 MHz?
  • Procedure Call Standard for the Arm 64-bit Architecture (AAPCS64), the universal stack constraints: what must be true of sp at all times, and which line of link.ld keeps _start's stacks honest?
Progress is stored only in this browser.