indicogniBuild a VMM

Contents

Chapter 04 · Part II

Guest memory: the only safe access is a copy

Needs a Mac Runs in browser ~3.5 h Lab: Guest address translator
5 of 26

Course progress: chapter 04 is 5 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 03: A guest of your own, and what an exit costs

    A guest prints ok and a newline through DEBUG_PUTC, then powers off. How many records with "ec":"0x16" does --trace exits:t.jsonl:hvc write, and why?

    Show answer

    Four. Each printed byte is one hvc (three bytes: o, k, newline), and the power-off call is one more hvc. Every one is an exception of class 0x16.

  2. 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.

  3. 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.

Concepts you'll need

Chapters before this one: chapter 03, A guest of your own, and what an exit costs.

  • Core, taught here: guest RAM as host memory lent to the guest; the region table and its construction rules; GuestAddress; checked arithmetic (checked_add) and wrapping overflow as an attack; the GuestMemory contract (read, write, check_range, the little-endian helpers, read_obj), one region per access; copy-only access, and why there is no get_slice (what a &[u8] promises the compiler); volatile element copies versus copy_nonoverlapping, and what volatile does not give; the memory-hash debug call.
  • Core, from earlier: hv_vm_allocate, hv_vm_map, the IPA (intermediate physical address) and the 16 KiB host page (chapter 02); the run loop, the debug calls and the --raw loader (chapter 03).
  • Primers (read first): page-granules (what a granule is; why the stage 2 of HVF, Hypervisor.framework, uses 16 KiB on a Mac by default while a guest may use 4 KiB).
  • Primers (review): bare-metal-rust (the MMU, memory management unit, in one paragraph); aarch64-reading (byte order; registers and the zero register; AAPCS64, who puts arguments where; reading a disassembly); host-concurrency (its section "Rust refuses to compile the race": what a Rust reference promises, and what a data race is).
  • Pointers: the caches primer, from an optional Under the hood; the memory-ordering primer, for ordering between threads (required from chapter 16); rust-vmm's vm-memory crate, in a Production note.
  • Forward definitions: DMA, direct memory access (chapter 15); TOCTOU, time of check to time of use (chapter 16); the ordered accessors of GuestMemoryOrdered (chapter 16); flash and RomRegion (chapter 21); the IPA size (chapter 05). Each is defined at first use.

A guest hands your virtual machine monitor (VMM) two numbers, "hash the 8 bytes at 0xFFFF_FFFF_FFFF_FFFC for me", and your VMM checks them the obvious way, in 64-bit unsigned arithmetic as C would: is addr at or above the start of guest RAM, and is addr + len at or below its end? RAM is 0x4000_0000 to 0x4400_0000. Work it out on paper before reading on: does the check say yes or no, and if yes, which bytes would you hash?

The answer is yes, and the bytes are not in guest RAM at all. This chapter explains why, and builds the one component that every device, loader and debug call in the rest of the course uses to touch the guest's memory, so that this mistake can be made in exactly one place and is not made there. It closes half of row 2 of chapter 00's problem ledger, memory: our VMM owns the guest's RAM and every access to it. The other half, translation, is chapter 05.

Objectives: by the end you can

  • Allocate guest RAM with hv_vm_allocate and map it with hv_vm_map in 16 KiB pieces, and explain from the Predict run why 16 KiB: with HVF's default granule, hv_vm_map refuses anything smaller, stage-2 permissions come per 16 KiB, and the guest's own page size is a separate matter.
  • Implement the GuestMemory contract: read, write and check_range, with the little-endian helpers and read_obj on top, where checked_add and a one-region rule refuse every out-of-range or overflowing access, and every copy is made of volatile element accesses.
  • Explain, with the generated machine code as evidence, why guest RAM is read only with volatile copies: any ordinary read, through a slice or a raw pointer, lets the optimiser assume nobody else writes, and a &[u8] makes that promise for its whole lifetime, which is why the contract has no get_slice.
  • Explain with one concrete overflow attack why a VMM never forms a host pointer from a guest address without a checked range test, and predict what each wrong fix (wrapping, panicking) does.

Before you start. From the repository root, run scripts/learner start 04. It copies this chapter's journal and the five files of the memory module (learner/crates/vmm/src/memory/) into your workspace. The files are complete except for three holes marked // LEARNER:, each a todo!(): the bounds checks this chapter is about. You write those; the rest you read along with the lesson, and then "Putting it to work" wires the module into your chapter 03 code, one numbered step at a time.

Guest RAM is your memory, lent out

In chapter 02 you gave a guest one 16 KiB page holding three instructions. Chapter 03's guests got more, but the idea did not change: our VMM allocates ordinary host memory, then asks Hypervisor.framework (HVF) to make it appear in the guest at a guest-physical address, an IPA (intermediate physical address). From then on there is one set of bytes with two names:

        guest (EL1)                    |              our VMM (a macOS process)                                       |  str x1, [x0]   x0 = 0x4100_0000      |    ram.read(GuestAddress(0x4100_0000), &mut buf)        |                              |               |        | translated by stage 2 (HVF)  |               | looked up in our region table        v                              |               v  IPA 0x4100_0000 ---------------> host bytes at host_base + 0x0100_0000                                       |                 trust boundary: every number on the left is the guest's choice

One allocation, reached from both sides. The guest's store and our read land on the same bytes.

That picture has two consequences, and they are this chapter. First, every address that arrives from the left, in a register, in a request, in a file the guest wrote, is a number an adversary chose, and we turn it into a host pointer. Second, the guest can change those bytes at any time, including while we are reading them.

Before either, one question about the mapping itself. Chapter 02 always mapped a whole 16 KiB. What if a guest only needs 4 KiB?

Predict Chapter 02's first-exit maps 16 KiB at 0x4000_0000. Change it to ask hv_vm_map for 4 KiB at the 4 KiB-aligned address 0x4000_1000. Will the call succeed, fail with an error, or succeed but quietly round the size or the address?

Write your answer and one sentence of reasoning under ## Predict in your journal, then make the experiment below and run it.

The experiment is two edits in your workspace, learner/. It is its own git repository, so commit your chapter 03 work first if you have not; afterwards git diff shows exactly what you changed and git restore crates/ undoes it.

  1. In crates/macvmm/src/first_exit.rs, the OwnedMapping::new call: the address becomes RAM_BASE + 0x1000, the length 0x1000.
  2. In crates/hvf/src/vm.rs, OwnedMapping::new: keep allocating a whole 16 KiB host page (hv_vm_allocate refuses anything else), but pass the caller's 4 KiB length to hv_vm_map.

Then, from inside learner/, run cargo run -q -p macvmm -- first-exit. Our run, on a real Mac:

TerminalReal output
cargo run -q -p macvmm -- first-exitexit: 1--- stderr ---first-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The Predict experiment: chapter 02's first-exit asks hv_vm_map for 4 KiB (0x1000 bytes) at the 4 KiB-aligned IPA 0x40001000.
  • Two edits in a copy of the reference: first_exit.rs maps (RAM_BASE + 0x1000, 0x1000); OwnedMapping::new (crates/hvf/src/vm.rs) still allocates a whole 16 KiB host page and passes the 4 KiB length to hv_vm_map.
course/captures/04-map-4k.txt

An error, HV_BAD_ARGUMENT, and nothing mapped. No rounding happens behind your back, which is the kind of failure you want: loud and early.

Why 16 KiB. Apple silicon Macs use 16 KiB memory pages, and HVF's stage-2 table, the one that maps guest memory to ours, uses the same page size by default, so mappings and their permissions come in 16 KiB pieces. The guest's own page tables are separate and may use 4 KiB pages. The page-granules primer calls such a page size a granule, "the page size a translation table uses". The host page size is a fact we read at run time rather than hard-code:

crates/hvf/src/caps.rslines 111-117
/// The host page size. `sysconf` cannot fail for `_SC_PAGESIZE` on Darwin; a nonsensical/// answer is reported as 0 rather than trusted.pub fn host_page_size() -> usize {    // SAFETY: `sysconf` takes an integer and has no memory-safety preconditions.    let raw = unsafe { ffi::sysconf(ffi::_SC_PAGESIZE) };    usize::try_from(raw).unwrap_or(0)}

"By default" matters: macOS 26 added hv_vm_config_set_ipa_granule, which opts one virtual machine (VM) into a 4 KiB stage-2 granule, and then 4 KiB maps at 4 KiB-aligned addresses succeed. We keep the 16 KiB default, as the page-granules primer explains; our captures all use it, because first-exit creates its VM without a configuration.

Try it

The SDK (software development kit) header hv_vm.h documents hv_vm_map's guest address as "page aligned" and its size as "a multiple of the page size" (and asks the same alignment of the host address, which hv_vm_allocate always hands out page-aligned). Which of your two changes does HVF object to? Make them one at a time, with the same edit-run-restore routine: a whole 16 KiB page at 0x4000_1000 (only the address change of edit 1), then 4 KiB at 0x4000_0000 (only the length change of edit 1, plus edit 2).

TerminalReal output
cargo run -q -p macvmm -- first-exitexit: 1--- stderr ---first-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it, first half: a whole 16 KiB page, but at the 4 KiB-aligned IPA 0x40001000. One edit in a copy of the reference: first_exit.rs maps (RAM_BASE + 0x1000, PAGE).
course/captures/04-map-ipa-4k.txt
TerminalReal output
cargo run -q -p macvmm -- first-exitexit: 1--- stderr ---first-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Try it, second half: 4 KiB (0x1000 bytes) at the 16 KiB-aligned IPA 0x40000000. Two edits in a copy of the reference: first_exit.rs maps (RAM_BASE, 0x1000);
  • OwnedMapping::new (crates/hvf/src/vm.rs) still allocates a whole 16 KiB host page and passes the 4 KiB length to hv_vm_map.
course/captures/04-map-len-4k.txt

Both fail the same way: the guest address and the size are each held to the page size on their own. So HVF works in whole host pages, while a Linux guest will happily work in 4 KiB pages inside them: two translations, two owners, two granules. Chapter 05 draws both stages.

The region table: rules for the shape of RAM

Guest RAM may come in more than one piece, a region: a base IPA and a size. Our VMM keeps the pieces in a region table, and the table is pure arithmetic, with no pointers and no HVF, so it can be tested on any computer. Its constants:

crates/vmm/src/memory/region.rslines 37-42
/// Alignment of every region base and size: the default 16 KiB stage-2 granule.pub const REGION_ALIGN: u64 = 16 * 1024;/// The most regions one table may hold (a named cap, never a guest value). The `virt` machine uses one RAM/// region; the rest is headroom (high RAM, hotplug experiments).pub const MAX_REGIONS: usize = 16;

One more input needs a sentence first. A VM's guest-physical address space has a fixed size, set when the VM is created, given as a number of address bits, ipa_bits: with 36 bits the guest can reach IPAs below 2 to the 36th, 64 GiB. A region that ends above that limit could never be mapped. Chapter 05 explains how to choose the number (it is the IPA size); today 36 is enough, HVF's default when a VM is created without a configuration, as yours was.

The constructor has one rule per failure it has to prevent. First the rules for the table and for each region on its own; read the module comment beside it in your copy of region.rs, which gives the reason for each:

crates/vmm/src/memory/region.rslines 139-178
/// Validate `regions` (`(base, size)` pairs, any order) for a VM with `ipa_bits` of IPA/// space. The result is sorted by base.pub fn new(regions: &[(GuestAddress, u64)], ipa_bits: u32) -> Result<RegionTable, RegionError> {    if regions.is_empty() {        return Err(RegionError::Empty);    }    if regions.len() > MAX_REGIONS {        return Err(RegionError::TooMany {            count: regions.len(),        });    }    if !(MIN_IPA_BITS..=MAX_IPA_BITS).contains(&ipa_bits) {        return Err(RegionError::BadIpaBits { bits: ipa_bits });    }    // `ipa_bits <= 52`, so the shift cannot overflow; `checked_shl` keeps the lint quiet    // without an `allow`.    let limit = 1u64        .checked_shl(ipa_bits)        .ok_or(RegionError::BadIpaBits { bits: ipa_bits })?;    let mut spans = Vec::with_capacity(regions.len());    for &(base, size) in regions {        let b = base.0;        if size == 0 {            return Err(RegionError::ZeroSize { base: b });        }        if !b.is_multiple_of(REGION_ALIGN) || !size.is_multiple_of(REGION_ALIGN) {            return Err(RegionError::Unaligned { base: b, size });        }        let end = b            .checked_add(size)            .ok_or(RegionError::Overflow { base: b, size })?;        if end > limit {            return Err(RegionError::AboveIpaLimit {                base: b,                size,                ipa_bits,            });        }        spans.push(Span { base, size, end });    }

Then one rule across regions:

crates/vmm/src/memory/region.rslines 181-192
spans.sort_by_key(|s| s.base);for pair in spans.windows(2) {    if let [a, b] = pair        && b.base.0 < a.end    {        return Err(RegionError::Overlap {            first: a.base.0,            second: b.base.0,        });    }}Ok(RegionTable { spans })

The cheap rules first: an empty table, too many regions, an ipa_bits outside what HVF supports, and a zero-size region are each refused before any arithmetic. Then four rules deserve a sentence. Alignment is the Predict, caught here with a clear error instead of HV_BAD_ARGUMENT from deep inside setup. No base + size overflow: a region near the top of the address space whose end wraps to a small number would appear to contain low memory. Below the IPA limit: as above. No overlap: one guest-physical byte must have exactly one host home.

One block per region

Why not a Vec<u8> for guest RAM? HVF maps only whole host pages that start on a page boundary, and a Vec promises neither. hv_vm_allocate is the call made for this: its header calls the result "anonymous memory suitable to be mapped as guest memory", it hands back page-aligned memory of a size that must be a page multiple, and it must be given back with hv_vm_deallocate. Chapter 02's Allocation was a stand-in for this wrapper; here is the real one, which checks the size before asking:

crates/hvf/src/host.rslines 213-235
/// `hv_vm_allocate(len)`. `len` must be a non-zero multiple of the host page size; that is/// checked here first (reported as `hv_vm_allocate: HV_BAD_ARGUMENT`), because the header only/// promises behaviour for page multiples.pub fn allocate(len: usize) -> Result<Allocation, CallError> {    let page = crate::caps::host_page_size();    if len == 0 || page == 0 || !len.is_multiple_of(page) {        return Err(CallError {            call: "hv_vm_allocate",            error: HvError::BadArgument,        });    }    let mut ptr: *mut c_void = core::ptr::null_mut();    // SAFETY: `ptr` is a live out-parameter; `len` is a non-zero page multiple; flags are the    // documented default.    check("hv_vm_allocate", unsafe {        ffi::hv_vm_allocate(&mut ptr, len, ffi::HV_ALLOCATE_DEFAULT)    })?;    let ptr = NonNull::new(ptr.cast::<u8>()).ok_or(CallError {        call: "hv_vm_allocate",        error: HvError::NoResources,    })?;    Ok(Allocation { ptr, len })}

The reference keeps each piece of guest RAM in a Block: one such allocation, the IPA where it will appear, and a small state machine that remembers whether it is mapped. This is memory/host.rs, the only file of the vmm crate allowed to contain unsafe:

crates/vmm/src/memory/host.rslines 86-95
/// One `hv_vm_allocate` block and where it is (or will be) mapped.#[derive(Debug)]struct Block {    /// The IPA of byte 0.    ipa: u64,    /// `Some` until `Drop` frees or leaks it.    alloc: Option<Allocation>,    len: usize,    state: AtomicU8,}
crates/vmm/src/memory/host.rslines 100-112
fn new(ipa: u64, size: u64) -> Result<Block> {    let len = usize::try_from(size).map_err(|_| Error::Config(format!("{size:#x} bytes")))?;    let alloc = hvf::host::allocate(len).map_err(|err| Error::Hv {        op: "allocate guest memory",        err,    })?;    Ok(Block {        ipa,        alloc: Some(alloc),        len,        state: AtomicU8::new(NOT_MAPPED),    })}

Mapping is chapter 02's vm.map call with one addition: the block records that it is mapped, because memory the guest can still reach must never be freed (if an unmap fails, the block is leaked on purpose; the comment at the top of host.rs gives the whole teardown rule):

crates/vmm/src/memory/host.rslines 135-164
/// Map the block at its IPA with `flags`. A block maps at most once at a time.fn map(&self, vm: &Vm, flags: MemFlags) -> Result<()> {    if self        .state        .compare_exchange(NOT_MAPPED, MAPPED, Ordering::SeqCst, Ordering::SeqCst)        .is_err()    {        return Err(Error::Internal("guest memory block mapped twice"));    }    let ptr = self        .alloc        .as_ref()        .map(Allocation::as_ptr)        .ok_or(Error::Internal("guest memory block already released"))?;    // SAFETY: (the `Vm::map` contract) `ptr..ptr+len` is one live `hv_vm_allocate` block owned    // by this `Block`. It stays allocated until the mapping is gone, because `Drop` frees a    // block only in state NOT_MAPPED (reached again only after a successful unmap) and    // otherwise leaks it. No Rust reference to it is ever created: all access is through the    // volatile copies and the atomic accessors below.    // The block is never handed out as ordinary Rust memory.    let mapped = unsafe { vm.map(ptr, self.ipa, self.len, flags) };    if let Err(err) = mapped {        self.state.store(NOT_MAPPED, Ordering::SeqCst);        return Err(Error::Hv {            op: "map guest memory",            err,        });    }    Ok(())}

GuestRam is a region table plus one block per region. Building one validates the table first, so a bad layout allocates nothing:

crates/vmm/src/memory/host.rslines 300-313
/// Allocate (but do not map) RAM for `regions` in a VM with `ipa_bits` of IPA space. The/// region-table rules (no overlap, no zero size, 16 KiB alignment) are checked first, so nothing is allocated for a bad layout.pub fn new(regions: &[(GuestAddress, u64)], ipa_bits: u32) -> Result<GuestRam> {    let table = RegionTable::new(regions, ipa_bits)?;    let mut blocks = Vec::with_capacity(table.spans().len());    for span in table.spans() {        blocks.push(Block::new(span.base.0, span.size)?);    }    Ok(GuestRam {        table,        blocks,        leak_on_drop: AtomicBool::new(false),    })}

A guest address is a number the guest chose

Guest addresses get a type of their own, so that a guest-physical address cannot be passed where a host pointer or a guest-virtual address was meant:

crates/vmm/src/memory/address.rslines 19-21
/// A guest-physical address (IPA).#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct GuestAddress(pub u64);

Now back to the opening puzzle. In 64-bit arithmetic, 0xFFFF_FFFF_FFFF_FFFC + 8 is 0x1_0000_0000_0000_0004, which needs 65 bits. That event is an integer overflow, and Rust offers three answers for the missing bit: with overflow checks off (its default for release builds) the sum silently wraps to 0x4; with them on, the program panics; and checked_add returns None, an ordinary value you must handle. Only the third, checked arithmetic, is safe.

With the wrapped sum, addr >= 0x4000_0000 holds and 0x4 <= 0x4400_0000 holds, so the check passes. The offset into RAM is addr - 0x4000_0000 = 0xFFFF_FFFF_BFFF_FFFC, and host_base + offset wraps around to host_base - 0x4000_0004: a pointer about 1 GiB below our allocation, into whatever the host keeps there. If the address is in range, is the access safe? Not when "in range" was computed with a sum that wrapped.

Try both versions in the lab: a region table, an address and a length, with an overflow mode that does the arithmetic the wrapping way.

Lab

Guest address translator

Build a region table, hand the VMM a guest address and a length, and see whether it forms a host pointer, refuses, or (with a wrapping addr + len) reaches memory outside guest RAM.

Runs in browserOpen full page: Guest address translator
Guest address translator: the opening puzzle One RAM region from 0x4000_0000 to 0x4400_0000, host base H. Checked: 8 bytes at 0x4000_1000 end at 0x4000_1008, ok, host address H + 0x1000. Checked: 8 bytes at 0xFFFF_FFFF_FFFF_FFFC overflow, checked_add returns None, fault, no host address. Wrapping: the same request sums to 0x4 after wrapping, the check passes, and the VMM forms H - 0x4000_0004, about 1 GiB below its RAM allocation. One region, 0x4000_0000..0x4400_0000, host base H mode addr len addr + len verdict host address checked 0x4000_1000 8 0x4000_1008 ok H + 0x1000 checked 0xFFFF_FFFF_FFFF_FFFC 8 overflow (None) fault none wrapping 0xFFFF_FFFF_FFFF_FFFC 8 0x4 (wrapped) "ok" H - 0x4000_0004 Dashed row: the check passes, but the host pointer lands about 1 GiB below the VMM's RAM allocation.

If the lab does not load, here is what it shows for the opening puzzle (one region, 0x4000_0000 to 0x4400_0000, host base written H):

mode       addr                    len   addr + len               verdict   host addresschecked    0x4000_1000             8     0x4000_1008              ok        H + 0x1000checked    0xFFFF_FFFF_FFFF_FFFC   8     overflow (None)          fault     nonewrapping   0xFFFF_FFFF_FFFF_FFFC   8     0x4 (wrapped)            "ok"      H - 0x4000_0004

The reference's loader for --raw already does this right; you met its placement check in chapter 03:

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    }}

We checked on a real Mac what it says to chapter 03's hello guest placed 16 bytes below the top of the address space:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0xfffffffffffffff0 --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: --raw blob 0 (0x2d9a bytes at 0xfffffffffffffff0) does not fit inside guest RAM
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference's raw loader (unchanged): chapter 03's hello guest placed at 0xfffffffffffffff0, which the loader checks against RAM before copying.
course/captures/04-raw-wrap.txt

0xffff_ffff_ffff_fff0 + 0x2d9a wraps to 0x2d8a; a wrapping check would have let the loader copy 11 KiB of guest image to host_base - 0x4000_0010, 1 GiB and 16 bytes below our allocation. The same check refuses the ordinary mistake too, an image that starts inside RAM and ends past it:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0x43fffff0 --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: --raw blob 0 (0x2d9a bytes at 0x43fffff0) does not fit inside guest RAM
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference's raw loader (unchanged): chapter 03's hello guest placed at 0x43fffff0, which the loader checks against RAM before copying.
course/captures/04-raw-edge.txt

Write the safe version yourself: the first LEARNER hole is the body of GuestAddress::checked_add. Then compare:

crates/vmm/src/memory/address.rslines 25-49
impl GuestAddress {    /// `self + off`, or `None` if it would pass `u64::MAX`. A guest that hands us    /// `addr = u64::MAX - 3, len = 8` gets `None` here, not a small wrapped address that    /// happens to land inside RAM.    pub fn checked_add(self, off: u64) -> Option<GuestAddress> {        self.0.checked_add(off).map(GuestAddress)    }    /// `self - base`, or `None` if `self` lies below `base`.    pub fn offset_from(self, base: GuestAddress) -> Option<u64> {        self.0.checked_sub(base.0)    }    /// Round up to a multiple of `align`, which must be a power of two (`None` otherwise, and    /// `None` if rounding up would pass `u64::MAX`).    pub fn align_up(self, align: u64) -> Option<GuestAddress> {        if !align.is_power_of_two() {            return None;        }        let mask = align.checked_sub(1)?;        self.0.checked_add(mask).map(|v| GuestAddress(v & !mask))    }}

One access, one region

Why checked_add alone is not enough: two regions that sit next to each other in the guest's address space are two separate host allocations, so a copy that starts in one and ends in the other would run off the end of the first. The rule is that the whole range [addr, addr + len) must lie inside one region. A zero-length range is refused too: otherwise a zero-length access at any address, even far outside RAM, would succeed, and "check_range says yes" could no longer mean "this address is in RAM". Refusing it keeps read succeeding exactly when check_range is true, as the trait's comment promises. Refusals carry the numbers, for the log:

crates/vmm/src/memory/mod.rslines 55-64
/// Why a guest-memory access was refused. Frozen from chapter 4 on.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum MemoryError {    /// `addr + len` passes `u64::MAX`.    Overflow { addr: u64, len: u64 },    /// The range is empty, or not entirely inside one RAM region.    OutOfBounds { addr: u64, len: u64 },    /// An ordered accessor was given an address that is not 2-byte aligned.    Unaligned { addr: u64 },}

The second LEARNER hole is RegionTable::locate, the function that decides. Write it from the rules above (overflow first, then zero length, then "the last region whose base is at or below addr", then the end). Then run the contract tests: from the repository root, scripts/checkpoint.sh 04. Its first line, contract, is the 37 hostile contract tests, which live with the checkpoint, not in your crate; cargo test -p vmm runs only your crate's own unit tests. The later lines fail until "Putting it to work" is done, and that is expected for now. Then compare:

crates/vmm/src/memory/region.rslines 211-239
/// Decide whether `[addr, addr + len)` is one valid access, and where it lands.////// - `addr + len` overflowing `u64` is [`MemoryError::Overflow`];/// - `len == 0`, a range outside every region, or one that crosses a region boundary///   (even into an adjacent region) is [`MemoryError::OutOfBounds`].pub fn locate(&self, addr: GuestAddress, len: u64) -> Result<Located, MemoryError> {    let a = addr.0;    let end = a        .checked_add(len)        .ok_or(MemoryError::Overflow { addr: a, len })?;    let oob = MemoryError::OutOfBounds { addr: a, len };    if len == 0 {        return Err(oob);    }    // The last region whose base is <= addr: the only one that can contain the start.    let index = self        .spans        .partition_point(|s| s.base.0 <= a)        .checked_sub(1)        .ok_or(oob)?;    let span = self.spans.get(index).ok_or(oob)?;    if end > span.end {        return Err(oob);    }    let offset = addr.offset_from(span.base).ok_or(oob)?;    Ok(Located { index, offset })}

Security

The attacker controls addr and len, and both arrive from many directions: the memory-hash call's registers later in this chapter, descriptors in shared memory from chapter 16, headers of files the guest wrote. What breaks without checked_add is the host: a read leaks host memory to the guest, a write corrupts it. That is why the reference checks twice: locate decides, and the code that forms the pointer (Block::ptr, below) checks the block length again, so a bug in one cannot become an out-of-bounds pointer.

Good place to stop. The second sitting is about how to touch the bytes once an access is in bounds, then wires the module into your VMM.

The only safe access is a copy

Once an access is in bounds, how should we touch the bytes? The convenient answer is a slice: fn get_slice(&self, addr, len) -> &[u8], then read whatever you like. The contract forbids it, and here is why.

A shared reference &[u8] tells the compiler: while this reference lives, nobody changes these bytes. Unlike C's const uint8_t *, which only stops you writing, a Rust &[u8] promises that nobody writes (outside an UnsafeCell, a simplification we keep; the host-concurrency primer has the rule). The compiler is allowed to rely on such promises. Here are three functions that wait for the guest to set a flag byte, trying at most limit times. The first reads through a slice:

course/examples/04-hoist.rslines 15-23
/// Through a shared slice: Rust promises that nobody changes `flag` while we hold it.#[unsafe(no_mangle)]pub fn wait_slice(flag: &[u8], limit: u32) -> u32 {    let mut tries = 0;    while tries < limit && flag[0] == 0 {        tries += 1;    }    tries}

The second has no reference at all: a raw pointer, read with an ordinary load:

course/examples/04-hoist.rslines 27-39
/// Through a raw pointer, with an ordinary (non-volatile) load: no reference anywhere.////// # Safety/// `flag` must point at one readable byte for the whole call.#[unsafe(no_mangle)]pub unsafe fn wait_raw(flag: *const u8, limit: u32) -> u32 {    let mut tries = 0;    // SAFETY: the caller promises `flag` is readable for the whole call.    while tries < limit && unsafe { *flag } == 0 {        tries += 1;    }    tries}

The third reads through a raw pointer with a load the compiler must perform every time, exactly as written: a volatile load:

course/examples/04-hoist.rslines 43-55
/// Through a raw pointer, with a volatile load: the compiler must load on every try.////// # Safety/// `flag` must point at one readable byte for the whole call.#[unsafe(no_mangle)]pub unsafe fn wait_volatile(flag: *const u8, limit: u32) -> u32 {    let mut tries = 0;    // SAFETY: the caller promises `flag` is readable for the whole call.    while tries < limit && unsafe { flag.read_volatile() } == 0 {        tries += 1;    }    tries}

Compiled with optimisations, as a release build would be. Arguments arrive in registers (the aarch64-reading primer's section on AAPCS64, the Arm procedure call standard): wait_slice gets the slice's pointer in x0, its length in x1 and limit in w2; the other two get the pointer in x0 and limit in w1. A w register is the 32-bit half of an x register, and wzr reads as zero.

TerminalReal output
rustc --edition 2024 -O --crate-type=lib --emit=asm=- course/examples/04-hoist.rs | grep -E '^(_wait|LBB|[[:space:]]+[a-z])' | grep -vE '^[[:space:]]+[.]' | expand -t 8exit: 0--- stdout ---_wait_raw:        cbz     w1, LBB0_3        ldrb    w8, [x0]        cmp     w8, #0        csel    w0, w1, wzr, eq        retLBB0_3:        mov     w0, #0        ret_wait_slice:        cbz     w2, LBB1_4        cbz     x1, LBB1_5        ldrb    w8, [x0]        cmp     w8, #0        csel    w0, w2, wzr, eq        retLBB1_4:        mov     w0, #0        retLBB1_5:        stp     x29, x30, [sp, #-16]!        mov     x29, sp        adrp    x2, l_anon.7dec077bfb117661c9e36bf72ccc71ec.1@PAGE        add     x2, x2, l_anon.7dec077bfb117661c9e36bf72ccc71ec.1@PAGEOFF        mov     x0, #0        bl      __RNvNtCsjIpoRzUjyHQ_4core9panicking18panic_bounds_check_wait_volatile:        cbz     w1, LBB2_6        mov     x8, x0        mov     w0, #0LBB2_2:        ldrb    w9, [x8]        cbnz    w9, LBB2_5        add     w0, w0, #1        cmp     w1, w0        b.ne    LBB2_2        mov     x0, x1LBB2_5:        retLBB2_6:        mov     w0, #0        ret
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The optimised machine code for course/examples/04-hoist.rs (rustc 1.99.0), with assembler directives filtered out; labels starting LBB are branch targets. The compiler emits the three functions in name order.
course/captures/04-hoist-asm.txt

Look for a loop. wait_volatile has one: the block at LBB2_2 loads the byte (ldrb, load register byte), and if it is still zero (cbnz, compare and branch if not zero), counts and goes round again. wait_slice has none. It loads the byte once, and csel (conditional select) returns limit if the byte was zero, else 0: since the byte "cannot change", the compiler worked out every try's answer from the first.

wait_raw has no loop either, and no reference was involved. What lets the optimiser hoist the load out of the loop is the ordinary, non-volatile read: if another thread could write the byte meanwhile, the program would contain a data race, which Rust's rules say never happens, so the compiler may assume nobody else writes. Only a volatile (or an atomic) access forbids that assumption. The slice adds a stronger promise on top, "unchanged for the whole lifetime of the reference", which no code could keep for guest RAM; that is why the contract has no get_slice. If the guest sets the flag a microsecond later, neither wait_slice nor wait_raw sees it. The compiler did nothing wrong; we lied to it. (The cbz x1 line in wait_slice is flag[0]'s bounds check: an empty slice panics.)

Honest about today. This is not a bug you can trigger yet: there is one vCPU, and it is stopped while we handle its exit, so nothing changes guest RAM while we look at it. It becomes real with device threads (Part VII) and several vCPUs (chapter 20). We set the rule now because retrofitting it later means rewriting every device. Its name, for later: a value that changes between the moment you check it and the moment you use it is a TOCTOU bug (time of check to time of use), and chapter 16 makes one happen on purpose.

What volatile does and does not give you. A volatile access makes the compiler perform every access, in program order relative to other volatile accesses, never assuming the value is unchanged, and at its size for an aligned scalar such as u8 or u64 on arm64 (Rust's documentation calls exact load sizes target-dependent). It gives no atomicity across elements (an 8-byte copy the guest writes into halfway can mix old and new bytes) and no ordering with other threads or the guest (that is what the memory-ordering primer and chapter 16 are for). In C you may have heard volatile means thread-safe. It does not, in C or in Rust.

Rust's own documentation goes further: on ordinary Rust memory, volatile does not make a race defined; volatile accesses behave like non-atomic ones there. Our argument is that guest RAM is not ordinary Rust memory. It comes from hv_vm_allocate, outside any Rust allocation; no reference into it ever exists; and it is changed by an agent outside the program, the guest, which is the memory-mapped I/O case the documentation allows for volatile. rust-vmm makes the same argument. So our copies are volatile, and we validate the copy, never the original.

Why not ptr::copy_nonoverlapping, Rust's memcpy? Because it is an ordinary copy, with the same assumption as wait_raw: nobody else writes. The optimiser may then re-read the guest's bytes later instead of using the copy, the mirror image of the hoisted read above, and a check made on the copy would no longer cover the bytes used. The reference copies element by element, each one volatile. read_volatile on a u64 needs an 8-aligned address, so the head is copied byte by byte until the pointer is aligned, then the middle in u64s (fewer, wider accesses are faster), then the tail byte by byte:

crates/vmm/src/memory/host.rslines 204-235
/// Copy `buf.len()` bytes from guest-shared memory at `src` into `buf`: `u8` loads up to the/// first 8-aligned address, `u64` loads for the middle, `u8` loads for the tail. Every load is/// volatile, so each guest byte is read exactly once and the compiler cannot re-read it.////// # Safety/// `src..src + buf.len()` must lie inside one live allocation, and no Rust reference may point/// into it.unsafe fn volatile_read(src: *const u8, buf: &mut [u8]) {    let head_len = src.align_offset(8).min(buf.len());    let Some((head, rest)) = buf.split_at_mut_checked(head_len) else {        return;    };    let mut p = src;    for out in head {        // SAFETY: `p` walks the caller's in-bounds range one byte per output byte.        *out = unsafe { p.read_volatile() };        p = p.wrapping_add(1);    }    let (words, tail) = rest.as_chunks_mut::<8>();    for chunk in words {        // SAFETY: `p` is 8-aligned here (we consumed `align_offset` bytes) and 8 bytes of the        // caller's range remain, because `chunk` has 8 bytes.        let w = unsafe { p.cast::<u64>().read_volatile() };        *chunk = w.to_ne_bytes();        p = p.wrapping_add(8);    }    for out in tail {        // SAFETY: as for the head: one in-bounds byte per output byte.        *out = unsafe { p.read_volatile() };        p = p.wrapping_add(1);    }}

volatile_write, beside it in host.rs, is its mirror image. This rule, that our VMM reaches guest RAM only by copying into and out of its own buffers, is copy-only access.

The third LEARNER hole is the last line of defence before those copies: Block::ptr, which turns a checked offset into a pointer, and checks once more against the block's real length:

crates/vmm/src/memory/host.rslines 116-131
/// Host address of byte `offset`, if `[offset, offset + len)` is inside the block. This/// re-checks what `RegionTable::locate` already proved, so a bug in a caller cannot turn/// into an out-of-bounds pointer.fn ptr(&self, offset: u64, len: usize) -> Option<*mut u8> {    let alloc = self.alloc.as_ref()?;    let start = usize::try_from(offset).ok()?;    let end = start.checked_add(len)?;    if end > self.len {        return None;    }    // SAFETY: `start <= end <= self.len`, the size of the live allocation, so the result    // stays inside it (or one past its end when `len == 0`, which callers never use).    Some(unsafe { alloc.as_ptr().add(start) })}

The contract

Everything so far fits behind three methods and a few helpers. This is the GuestMemory trait, frozen: its signatures do not change for the rest of the course, so later chapters and the lifelines can rely on them. It is exactly what your checkpoint uses:

crates/vmm/src/memory/mod.rslines 126-166
/// Guest-physical RAM, reachable only by bounds-checked copies. Frozen from chapter 4 on.pub trait GuestMemory: Send + Sync {    /// Copy guest bytes out. The whole `[addr, addr + buf.len())` must lie in ONE RAM region;    /// otherwise nothing is copied and the result is `Err`. An empty `buf` is `Err` too, so    /// that `read` succeeds exactly when `check_range` is true.    fn read(&self, addr: GuestAddress, buf: &mut [u8]) -> Result<(), MemoryError>;    /// Copy bytes into guest RAM (same rule; on `Err` nothing was written). ROM is never    /// writable through this trait.    fn write(&self, addr: GuestAddress, buf: &[u8]) -> Result<(), MemoryError>;    /// True if `[addr, addr + len)` lies in one RAM region. `len == 0` is false.    fn check_range(&self, addr: GuestAddress, len: u64) -> bool;    fn read_u8(&self, addr: GuestAddress) -> Result<u8, MemoryError> {        read_obj_from(self, addr)    }    fn read_u16(&self, addr: GuestAddress) -> Result<u16, MemoryError> {        read_obj_from(self, addr)    }    fn read_u32(&self, addr: GuestAddress) -> Result<u32, MemoryError> {        read_obj_from(self, addr)    }    fn read_u64(&self, addr: GuestAddress) -> Result<u64, MemoryError> {        read_obj_from(self, addr)    }    fn write_u8(&self, addr: GuestAddress, v: u8) -> Result<(), MemoryError> {        self.write(addr, &v.to_le_bytes())    }    fn write_u16(&self, addr: GuestAddress, v: u16) -> Result<(), MemoryError> {        self.write(addr, &v.to_le_bytes())    }    fn write_u32(&self, addr: GuestAddress, v: u32) -> Result<(), MemoryError> {        self.write(addr, &v.to_le_bytes())    }    fn write_u64(&self, addr: GuestAddress, v: u64) -> Result<(), MemoryError> {        self.write(addr, &v.to_le_bytes())    }    // `read_obj::<T>(addr)` is provided for every implementation, and for `dyn GuestMemory`,    // by the blanket extension trait `GuestMemoryExt` below.}

GuestMemory is a trait rather than GuestRam's own methods for two real needs. The checkpoint's contract tests run on any computer, without HVF, against VecMemory, a host test double backed by Vecs that uses the same region table. And if you get stuck later, scripts/learner lifeline can lend you the reference's module, which only works if both sides agree on these exact signatures.

There is a reason beyond tidiness to route every access through it. Real devices read and write RAM by themselves, without the CPU, which is called DMA (direct memory access); our emulated devices will do the same through this API, which is why every device in this course touches guest memory only through GuestMemory. Chapter 15 builds on it.

The helpers are little-endian because the guest is (the aarch64-reading primer's byte-order section): write_u32(a, 0xdead_beef) stores the bytes ef be ad de. read_obj reads a whole structure in one copy, then decodes it; chapter 16 relies on that to read a guest's request once and only once:

crates/vmm/src/memory/mod.rslines 89-98
/// A value that can be decoded from its little-endian bytes, for [`GuestMemoryExt::read_obj`].////// `Bytes` is the exact-size byte array (`[u8; N]`), so the whole object is read with one copy/// (validate the copy, never the guest's original). Virtio descriptors and block headers implement it in their own modules.pub trait FromLeBytes: Sized {    /// `[u8; size_of::<Self>()]` (or the wire size, for a structure).    type Bytes: Default + AsMut<[u8]>;    /// Decode the copied bytes.    fn decode_le(bytes: Self::Bytes) -> Self;}
crates/vmm/src/memory/mod.rslines 114-122
/// Copy `T` out of guest memory once and decode it (the body of `read_obj`).fn read_obj_from<T: FromLeBytes, M: GuestMemory + ?Sized>(    mem: &M,    addr: GuestAddress,) -> Result<T, MemoryError> {    let mut bytes = T::Bytes::default();    mem.read(addr, bytes.as_mut())?;    Ok(T::decode_le(bytes))}

GuestRam implements the trait in a few lines, because the work is done by locate, Block::ptr and the volatile copies:

crates/vmm/src/memory/host.rslines 377-395
/// The block and in-block pointer for an accepted access.fn host_ptr(    &self,    addr: GuestAddress,    len: usize,) -> core::result::Result<*mut u8, MemoryError> {    let len64 = u64::try_from(len).map_err(|_| MemoryError::Overflow {        addr: addr.0,        len: u64::MAX,    })?;    let at = self.table.locate(addr, len64)?;    self.blocks        .get(at.index)        .and_then(|b| b.ptr(at.offset, len))        .ok_or(MemoryError::OutOfBounds {            addr: addr.0,            len: len64,        })}
crates/vmm/src/memory/host.rslines 409-428
impl GuestMemory for GuestRam {    fn read(&self, addr: GuestAddress, buf: &mut [u8]) -> core::result::Result<(), MemoryError> {        let src = self.host_ptr(addr, buf.len())?;        // SAFETY: `host_ptr` proved `[src, src + buf.len())` lies inside one live block        // (see the type's safety argument); `buf` is VMM-owned memory, not guest memory.        unsafe { volatile_read(src, buf) };        Ok(())    }    fn write(&self, addr: GuestAddress, buf: &[u8]) -> core::result::Result<(), MemoryError> {        let dst = self.host_ptr(addr, buf.len())?;        // SAFETY: as in `read`, for the destination range.        unsafe { volatile_write(dst, buf) };        Ok(())    }    fn check_range(&self, addr: GuestAddress, len: u64) -> bool {        self.table.contains(addr, len)    }}

VecMemory resolves every access through the very same locate, so a test that passes against it has exercised your bounds logic:

crates/vmm/src/memory/vec_mem.rslines 151-185
/// Resolve the access, run `op` on the target bytes and log it. Nothing happens on `Err`.fn access(    &self,    addr: GuestAddress,    len: usize,    kind: Kind,    op: impl FnOnce(&mut [u8]),) -> Result<(), MemoryError> {    let len64 = u64::try_from(len).map_err(|_| MemoryError::Overflow {        addr: addr.0,        len: u64::MAX,    })?;    let at = self.table.locate(addr, len64)?;    let oob = MemoryError::OutOfBounds {        addr: addr.0,        len: len64,    };    let start = usize::try_from(at.offset).map_err(|_| oob)?;    let end = start.checked_add(len).ok_or(oob)?;    let mut inner = lock(&self.inner);    let region = inner.regions.get_mut(at.index).ok_or(oob)?;    op(region.get_mut(start..end).ok_or(oob)?);    if kind.logged        && let Some(log) = inner.log.as_mut()    {        log.push(Access {            addr: addr.0,            len: len64,            write: kind.write,            ordered: kind.ordered,            fence: false,        });    }    Ok(())}

Two more items are in your copied files and in the contract tests, and you only need to read them today. GuestMemoryOrdered adds two 16-bit accessors with ordering guarantees, which chapter 16 explains. RomRegion holds firmware in flash, the memory a real board keeps its firmware in, which survives power-off and which the guest may read but not write; it is deliberately not reachable through GuestMemory, and chapter 21 uses it.

Production note

rust-vmm's vm-memory crate, used by Firecracker and Cloud Hypervisor, reaches guest memory through volatile accessors and bounds-checked copies; even its get_slice returns a VolatileSlice, a pointer and length with volatile accessors, never a &[u8]. Ours is smaller and single-purpose, so every line of it fits in this chapter.

Putting it to work

Four steps connect the module to your chapter 03 VMM, each in a file of learner/.

Step 1: declare the module. In crates/vmm/src/lib.rs, add pub mod memory;. Your crate starts with #![deny(unsafe_code)]; memory/host.rs opens with #![allow(unsafe_code)], which lifts that for this one file (a deny can be lifted this way, a forbid could not), so every pointer into guest RAM lives in a single file you can audit.

Step 2: give the module what it uses. The copied files use a few names from the rest of the reference crate: an Error type with a Result alias (crate::error), a warn! logging macro, a lock helper for mutexes (crate::sync), and, from your hvf crate, host::allocate, host::deallocate, host::leaked_bytes and Allocation::leak. cargo build -p vmm names each one your workspace lacks; small versions are enough today, and the reference's are in the same paths for comparison. One more, the InsnRom trait used at the bottom of host.rs, belongs to chapter 06: delete that impl block for now.

Step 3: make guest RAM a GuestRam. Where your run command made chapter 03's OwnedMapping for --mem bytes, build a GuestRam with one region, (GuestAddress(0x4000_0000), mem_bytes), and ipa_bits 36, then call its map method with your Vm. The reference wraps it in an Arc (a reference-counted pointer that several threads can share), because the vCPU thread and, later, device threads all need it:

crates/vmm/src/machine/mod.rslines 342-346
// If allocation fails nothing is mapped yet: dropping the VM destroys it.let ram = Arc::new(GuestRam::new(    &virt::ram_regions(cfg.mem_bytes),    vm::ipa_bits(layout, ram_end),)?);

The --raw loader now writes through the contract, after the placement check you saw refuse the wrapped address:

crates/vmm/src/loader/plan.rslines 408-410
for (addr, bytes) in inputs.raw {    mem.write(GuestAddress(*addr), bytes)?;}

Step 4: answer the memory-hash call. The run loop's debug calls gain a third one, function number 0xC600_4D03, next to chapter 03's two. The guest passes an address in x1 and a length in x2; the VMM answers x0 = 0 and x1 = a hash of those bytes, computed with FNV-1a (the Fowler–Noll–Vo hash, a simple 64-bit checksum), or x0 = -2 ("invalid parameters") for a bad range. The new arm of the reference's match:

crates/vmm/src/smccc.rslines 330-333
DEBUG_MEMHASH => match memhash(ctx.mem, x1, x2, ctx.ctl) {    Some(h) => Outcome::Return([Some(0), Some(h), None, None]),    None => ret(INVALID_PARAMETERS),},

And the function it calls:

crates/vmm/src/smccc.rslines 362-390
/// FNV-1a-64 of guest RAM `[ipa, ipa + len)`, or `None` if the range is empty, longer than/// [`MAX_MEMHASH_LEN`], overflows, or is not entirely in one RAM region (`checked_add`/// inside `check_range`). Also `None` if the VM is stopping mid-hash.pub fn memhash(mem: &dyn GuestMemory, ipa: u64, len: u64, ctl: &VmControl) -> Option<u64> {    if len > MAX_MEMHASH_LEN || !mem.check_range(GuestAddress(ipa), len) {        return None;    }    let mut buf = [0u8; MEMHASH_BOUNCE];    let mut h = FNV_OFFSET;    let (mut addr, mut left, mut since_check) = (ipa, len, 0u64);    while left > 0 {        let n = usize::try_from(left).map_or(MEMHASH_BOUNCE, |l| l.min(MEMHASH_BOUNCE));        let chunk = buf.get_mut(..n)?;        mem.read(GuestAddress(addr), chunk).ok()?;        h = chunk            .iter()            .fold(h, |h, &b| (h ^ u64::from(b)).wrapping_mul(FNV_PRIME));        let n64 = u64::try_from(n).ok()?;        (addr, left) = (addr.checked_add(n64)?, left.saturating_sub(n64));        since_check = since_check.saturating_add(n64);        if since_check >= MEMHASH_STOP_CHUNK {            since_check = 0;            if ctl.is_stopping() {                return None;            }        }    }    Some(h)}

The length cap (MAX_MEMHASH_LEN, 1 GiB) bounds the work, and the stop check, which asks every 64 MiB whether the VM is shutting down (for example because --timeout fired), means even a capped hash cannot delay the stop. If your chapter 03 VMM ends the process at the deadline instead of setting a stop flag, the cap alone is enough for now; fnv1a and the FNV constants are in the reference's smccc.rs.

Note what --mem is: the user's choice of how much host memory the guest may have. The guest cannot change it.

The guest side, guests/memtest, writes eight patterns over a 16 MiB window and reads them back, asks the VMM for the hash of the same window, then asks for a hash of a range whose end overflows:

guests/memtest/main.rslines 69-110
fn main(_x0: u64) {    for p in 1..=8u32 {        for i in 0..WORDS {            // SAFETY: aligned store inside the window (guest RAM).            unsafe { core::ptr::write_volatile(word(i), pattern(p, i)) };        }        for i in 0..WORDS {            // SAFETY: aligned load inside the window (guest RAM).            let got = unsafe { core::ptr::read_volatile(word(i)) };            let want = pattern(p, i);            if got != want {                println!(                    "memtest: pattern {p} FAILED at {:#x}: got {got:#x} want {want:#x}",                    WINDOW + i * 8                );                guest::hvc::debug_exit(2);            }        }        println!("memtest: pattern {p} ok");    }    let mine = fnv1a_window();    match guest::hvc::memhash(WINDOW, WINDOW_LEN) {        Ok(theirs) if theirs == mine => println!("memtest: memhash ok"),        Ok(theirs) => {            println!("memtest: memhash MISMATCH: vmm {theirs:#x} guest {mine:#x}");            guest::hvc::debug_exit(3);        }        Err(e) => {            println!("memtest: memhash error {e}");            guest::hvc::debug_exit(4);        }    }    match guest::hvc::memhash(0xFFFF_FFFF_FFFF_FFF0, 0x20) {        Err(guest::hvc::INVALID_PARAMETER) => println!("memtest: memhash rejects overflow ok"),        other => {            println!("memtest: memhash overflow not rejected: {other:?}");            guest::hvc::debug_exit(5);        }    }}

Run it from inside learner/. If memtest.bin is missing, run scripts/build-guests.sh again from the repository root.

Shell
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/memtest.bin@0x40080000 --timeout 10; echo "exit status $?"

We checked this on a real Mac; the reference prints:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --raw $G/memtest.bin@0x40080000 --timeout 10; echo "exit status $?"exit: 0--- stdout ---memtest: pattern 1 okmemtest: pattern 2 okmemtest: pattern 3 okmemtest: pattern 4 okmemtest: pattern 5 okmemtest: pattern 6 okmemtest: pattern 7 okmemtest: pattern 8 okmemtest: memhash okmemtest: memhash rejects overflow okexit status 0
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/04-memtest-run.txt

"memhash ok" means the bytes the guest wrote are the bytes our VMM read, through two different paths; "rejects overflow ok" means checked_add did its job.

Deliberate breakage 1: replace checked_add with + in locate. In your region.rs, make the end of the range let end = a + len;. Predict: which contract tests fail, and what does the memtest guest do to your VMM? The repository builds with overflow checks on, in debug and in release. From the repository root, run scripts/checkpoint.sh 04:

TerminalReal output
scripts/checkpoint.sh 04exit: 1--- stdout ---checkpoint: implementation <tree>[FAIL] L1 contract  memory_hostile: 6 failed: check_range_at_u64_max_minus_3_len_8_is_false, read_at_u64_max_minus_3_len_8_overflows, ordered_accessors_obey_bounds, read_u64_wrapping_into_ram_is_refused, u64_max_len_1_overflows, write_at_u64_max_minus_3_len_8_overflows    ---- check_range_at_u64_max_minus_3_len_8_is_false stdout ----        thread 'check_range_at_u64_max_minus_3_len_8_is_false' (122676214) panicked at <tree>/crates/vmm/src/memory/region.rs:219:19:    attempt to add with overflow    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace        ---- read_at_u64_max_minus_3_len_8_overflows stdout ----        thread 'read_at_u64_max_minus_3_len_8_overflows' (122676222) panicked at <tree>/crates/vmm/src/memory/region.rs:219:19:    attempt to add with overflow        ---- ordered_accessors_obey_bounds stdout ----[FAIL] L2 run       memtest: expected/memtest.txt:10: stdout marker "memtest: memhash rejects overflow ok" missing (in order) (9/10 serial markers matched before it)    exit 1 (want 0)    stderr (last lines):            thread 'vcpu0' (122677030) panicked at crates/vmm/src/memory/region.rs:219:19:      attempt to add with overflow      note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace      macvmm: error: internal error (a macvmm bug): a vCPU thread panicked[FAIL] L2 run       guest-ram: guest_ram_hostile: 2 failed: guest_ram_agrees_with_vec_memory, guest_ram_refuses_hostile_ranges    ---- guest_ram_agrees_with_vec_memory stdout ----        thread 'guest_ram_agrees_with_vec_memory' (122677404) panicked at <tree>/crates/vmm/src/memory/region.rs:219:19:    attempt to add with overflow    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace        ---- guest_ram_refuses_hostile_ranges stdout ----        thread 'guest_ram_refuses_hostile_ranges' (122677405) panicked at <tree>/crates/vmm/src/memory/region.rs:219:19:    attempt to add with overflow        [INFO] L3 journal   not checked (not a learner tree)CHECKPOINT 04 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1: in RegionTable::locate (crates/vmm/src/memory/region.rs), the end of the range computed as a + len instead of with checked_add.
  • Run against a copy of the reference with that one edit (scripts/checkpoint.sh 04 --impl <tree>); the repository builds with overflow checks on, in debug and release. Line numbers in your own region.rs will differ.
course/captures/04-break-plus.txt

What you saw: every overflow case is now a panic, and the worst line is in the middle. The memtest guest asked for a hash of a range whose end overflows, and the guest crashed your VMM (a vCPU thread panicked, exit 1). The misconception it exposes: "Rust panics on overflow, so it is safe." A panic a guest can trigger at will is a denial of service. Each line of the checkpoint names its stage after the level tag: contract (the contract tests), run (the runs on your Mac) and journal.

With overflow checks off, Rust's release default, the same edit fails differently. Run it with the two settings turned off for this one command:

TerminalReal output
CARGO_PROFILE_DEV_OVERFLOW_CHECKS=false CARGO_PROFILE_TEST_OVERFLOW_CHECKS=false scripts/checkpoint.sh 04exit: 1--- stdout ---checkpoint: implementation <tree>[FAIL] L1 contract  memory_hostile: 5 failed: check_range_at_u64_max_minus_3_len_8_is_false, read_u64_wrapping_into_ram_is_refused, read_at_u64_max_minus_3_len_8_overflows, u64_max_len_1_overflows, write_at_u64_max_minus_3_len_8_overflows    ---- check_range_at_u64_max_minus_3_len_8_is_false stdout ----        thread 'check_range_at_u64_max_minus_3_len_8_is_false' (122690210) panicked at tests/memory_hostile.rs:79:5:    assertion failed: !mem().check_range(ga(u64::MAX - 3), 8)        ---- read_u64_wrapping_into_ram_is_refused stdout ----        thread 'read_u64_wrapping_into_ram_is_refused' (122690227) panicked at tests/memory_hostile.rs:94:5:    assertion failed: !mem().check_range(ga(R0), u64::MAX)        ---- read_at_u64_max_minus_3_len_8_overflows stdout ----    [PASS] L2 run       memtest: 10/10 serial markers, exit 0 in 0.17s[FAIL] L2 run       guest-ram: guest_ram_hostile: 1 failed: guest_ram_refuses_hostile_ranges    ---- guest_ram_refuses_hostile_ranges stdout ----        thread 'guest_ram_refuses_hostile_ranges' (122691975) panicked at tests/guest_ram_hostile.rs:42:5:    assertion failed: !ram.check_range(ga(u64::MAX - 3), 8)    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace            failures:        guest_ram_refuses_hostile_ranges        test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s    [INFO] L3 journal   not checked (not a learner tree)CHECKPOINT 04 FAIL
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage 1 again (a + len in RegionTable::locate), now with overflow checks turned off, Rust's default for release builds, so the sum wraps instead of panicking.
  • Run against the same edited copy of the reference (scripts/checkpoint.sh 04 --impl <tree>) with the two environment variables shown.
course/captures/04-break-wrap.txt

Read the failures as "the test asserted that check_range refuses the attack, and it did not": check_range now says yes to addr = u64::MAX - 3, len = 8. Yet memtest passes. The read itself was still refused, but as OutOfBounds by Block::ptr's second check, not as Overflow by locate, so the guest saw its -2 and was satisfied. A guest-level test cannot tell the two apart; the hostile contract tests, 37 cases that must each come back as the right value and never a panic, can. Undo the edit.

Under the hood

Optional, and safe to skip. Our VMM and the guest look at the same RAM through different settings: the guest has not turned on its MMU (memory management unit, the part of the CPU that applies page tables; the bare-metal-rust primer, and chapter 06 shows the switch), so its data accesses are treated as Device (uncached) memory, while macOS maps ours as normal cacheable memory. They agreed in every test; why that is not automatic is the subject of the caches primer before chapter 13.

Your turn

Before the checkpoint, check:

  1. The three LEARNER holes are filled, and the contract line of scripts/checkpoint.sh 04 (from the repository root) passes. cargo test -p vmm in learner/ should pass too, but it runs only your crate's own tests.
  2. The memtest run above prints all ten lines and exit status 0.
  3. Your journal has the Predict entry, written before the run, and an answer to each question; question 1 is arithmetic, so do it on paper first.

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

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 04

You should see, as the last line:

CHECKPOINT 04 PASS

It runs the 37 contract tests (hostile accesses against VecMemory and your region table, each of which must be refused without a panic, plus the little-endian round trips), runs memtest against your VMM, runs the same hostile cases on real hv_vm_allocate memory, checks your journal, and ends with CHECKPOINT 04 PASS. Against an unmodified copy of the reference it looks like this:

TerminalReal output
scripts/checkpoint.sh 04exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   memory_hostile (37 tests)[PASS] runs on your Mac memtest: 10/10 serial markers, exit 0 in 0.19s[PASS] runs on your Mac guest-ram: HVF contract guest_ram_hostile (4 tests) in 2.24s[INFO] journal          not checked (not a learner tree)CHECKPOINT 04 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 04 --impl <tree>): what a finished chapter 04 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/04-checkpoint.txt

What now works:

  • guest RAM is a validated table of 16 KiB-aligned regions, allocated and mapped through HVF;
  • every access to it, from the loader, the debug calls and, later, every device, is a bounds-checked copy that refuses overflow, zero length and region-crossing ranges without panicking;
  • you can show with machine code why ordinary reads of guest RAM, and a &[u8] above all, make promises you cannot keep, and say what volatile gives and what it does not.

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

What's next

Chapter 05 asks what lives at the addresses that are not RAM. The answer is a device, and a device register cannot be a page of memory, so the guest's memory map gets holes on purpose, and a guest access to one becomes a VM exit (the guest stops and our virtual machine monitor runs) with an address we can decode.

Open question

--mem decides how much host memory the guest can use, and it is the user's choice, not the guest's. Which guest actions could exhaust the host's resources without touching RAM?

Spec hunt

  • The SDK header hv_vm.h, the comment above hv_vm_map: it says "page aligned" and "a multiple of the page size". Which page size does it mean? (Hint: the VM's stage-2 granule, 16 KiB by default; hv_vm_config.h shows how to change it.) How did your Predict run answer what the header leaves unsaid?
  • The Rust standard library documentation for core::ptr::read_volatile: what does it say about concurrent access from several threads, and for which kind of memory does it say volatile is meant? Does guest RAM from hv_vm_allocate fit that description?
  • The Rust Reference, the section on integer overflow in the chapter on operator expressions: when does an overflowing + panic, when does it wrap, and which setting in our Cargo.toml changes that?
Progress is stored only in this browser.