Chapter 04 · Part II
Guest memory: the only safe access is a copy
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.
From chapter 03: A guest of your own, and what an exit costs
A guest prints
okand a newline through DEBUG_PUTC, then powers off. How many records with"ec":"0x16"does--trace exits:t.jsonl:hvcwrite, and why?Show answer
Four. Each printed byte is one
hvc(three bytes:o,k, newline), and the power-off call is one morehvc. Every one is an exception of class0x16.From chapter 03: A guest of your own, and what an exit costs
Decode the hypercall ID
0xC600_4D02field by field.Show answer
Bit 31 = 1, a fast call; bit 30 = 1, the 64-bit convention; bits 29 to 24 =
0x06, owner 6, vendor-specific hypervisor service; low 16 bits =0x4D02, the function. In macvmm that is DEBUG_EXIT, with the exit code inx1.From chapter 03: A guest of your own, and what an exit costs
A guest calls DEBUG_EXIT with
x1 = 3. What exit status doesmacvmmreturn to the shell, and what would it return forx1 = 0?Show answer
6 for any non-zero guest code (and it prints
guest exit code 3); 0 for code 0. The guest's own number and the monitor's exit status are different things.From chapter 03: A guest of your own, and what an exit costs
The flat binary of a guest is 11,866 bytes, and its linker map puts
__bss_startat0x40082e60with the image linked at0x40080000. After--raw guest.bin@0x40080000, what does a zero-initialised static at0x40082e60contain before_startruns?Show answer
Whatever that RAM held before: the file ends at offset 11,866 and
0x2e60is 11,872, so no byte of the file lands there. It reads 0 only if the monitor happened to hand over fresh, zeroed memory;_startmust zero the BSS itself.From chapter 03: A guest of your own, and what an exit costs
Your loader checks
addr + len <= ram_endwith a plain+. A user passes a 0x2000-byte file at address0xffff_ffff_ffff_f000. What goes wrong, and what is the fix?Show answer
With Rust's default release settings the sum wraps to
0x1000, which is below the end of RAM, so the check passes and the copy runs off the top of memory (withoverflow-checkson, as in our workspace, it panics instead: a crash, still not a clean refusal). Usechecked_addand refuse the file, exit code 2, when it returnsNone.From chapter 03: A guest of your own, and what an exit costs
exit-benchreports 3,600,000 ticks for 100,000 calls on a 24 MHz counter. What is one round trip in nanoseconds?Show answer
3,600,000 / 24,000,000 s = 0.15 s; divided by 100,000 that is 1.5 µs, 1,500 ns per round trip.
From chapter 03: A guest of your own, and what an exit costs
Why can a single store instruction not be timed with
CNTVCT_EL0, and what doesexit-bench's method do instead?Show answer
The counter ticks at 24 MHz, once every 41.7 ns, while a store takes a fraction of a nanosecond, so one store almost never spans a tick. Timing a loop of a million stores and dividing by a million gives the average.
From chapter 03: A guest of your own, and what an exit costs
A guest spins in
b .and you run it with--timeout 1. Why can the vCPU's own thread not notice the timeout, and what exit status do you get?Show answer
The thread is blocked inside
hv_vcpu_run, which does not return while the guest runs without exiting, so it cannot look at a clock. Another thread must notice the deadline and stop it (the reference kicks the vCPU; ending the process also works). The exit status is 5.From chapter 03: A guest of your own, and what an exit costs
After a DEBUG_PUTC exit, your run loop adds 4 to the PC before resuming. What happens to the guest?
Show answer
It skips the instruction after the
hvc. The hardware already saved the PC past thehvc(a call continues after itself), so the extra 4 jumps over code the guest meant to run; anhvcexit must resume with the PC unchanged.From chapter 03: A guest of your own, and what an exit costs
You delete
mov sp, x10from_start. The run prints nothing and the trace's only record iscanceledatpc=0x40080a00, with the guest's vectors at0x40080800. Where was the CPU, and why did no exit report the fault?Show answer
In the guest's own vector entry at
VBAR_EL1 + 0x200, for an exception taken at EL1 itself. Withsp= 0, the first stack store used an address no memory could have, so the fault was taken by the guest's own level, not forwarded to EL2; the handler then faulted on the same bad stack, again and again, until the timeout's kick stopped it.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
Vmis still alive, or was dropped withoutDropcallinghv_vm_destroy.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
hv_vm_createreturns0xfae94009, a code yourHvErrordoes not list. What shouldHvError::from_codereturn, and why not a generic "unknown error"?Show answer
HvError::Unknown(0xfae94009). The exact value is the evidence a bug report needs, and a newer macOS may add codes;Displaystill prints it in full.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A freshly built
macvmm, run without the signing runner, getsHV_DENIED (0xfae94007). Is that a link problem? What fixes it?Show answer
No: the program linked and started; the kernel refused at the call because the signature has no
com.apple.security.hypervisor. Run it throughcargo run(the runner signs a copy first) or sign it withscripts/sign.sh.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest stores a byte to
0x0900_0000, where nothing is mapped. Which layer decides that this access leaves the guest, and which decides what it means?Show answer
The macOS kernel's EL2 part decides it stops the guest and forwards it (a VM exit); our VMM, an ordinary EL0 process, decides what it means, by playing the device at that address.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Inside an
unsafeblock you index a slice out of bounds. What happens, and what does that tell you aboutunsafe?Show answer
It still panics: bounds checks on safe indexing stay on, as do type and borrow checks.
unsafeonly allows a few extra operations (such as calling an FFI function); the invariants those operations need become yours.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
The header declares
hv_return_t hv_vm_get_max_vcpu_count(uint32_t *max_vcpu_count);. What is the Rust parameter type, and who owns the memory it points to?Show answer
*mut u32. It is an out-pointer: the caller owns a live, writableu32(for example a local variable) and passes its address; the function writes the answer there and returns only an error code.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Why does
hv_vm_destroytake no argument at all?Show answer
There is no handle to pass: the VM belongs to the whole process, and there can be only one, so "destroy the VM" is unambiguous.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
At which exception level does
macvmmitself run, and at which does the guest kernel run?Show answer
macvmmruns at EL0, like any app. The guest kernel runs natively at EL1. The level above both, EL2, belongs to part of the macOS kernel.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest reads the clock counter with
mrs x0, CNTVCT_EL0a million times. How many of those reads reach our VMM?Show answer
None: the hardware virtualizes the counter, so the read completes inside the guest without any exit.
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.
From chapter 00: Two kernels, one Mac: what a virtual machine is
An instruction reads the current privilege mode and, in user mode, answers "user" without trapping. Is it sensitive, privileged, both or neither, and why does that break trap-and-emulate?
Show answer
Sensitive (it reads state the VMM must control) but not privileged (it does not trap). Nothing traps, so the VMM never gets a turn to supply the virtual answer "kernel", and the guest kernel acts on the truth: it is in user mode.
From chapter 00: Two kernels, one Mac: what a virtual machine is
You must run an unmodified guest on a processor that has sensitive, unprivileged instructions and no hardware assist. Which strategies are open to you, and which is not?
Show answer
Interpretation (slow but correct) and binary translation (rewrite the bad instructions just before they run). Paravirtualization is not: it needs the guest's source changed.
From chapter 00: Two kernels, one Mac: what a virtual machine is
A kernel copied into an ordinary process stores to the console's address. Which ledger row is that, and what does a VMM using trap-and-emulate do to make it work?
Show answer
Row 3, devices at fixed addresses. The VMM leaves the address unmapped, so the store traps; the VMM plays the device's part (prints the character) and resumes the guest after the store.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Under hardware assist, why does the guest kernel's "am I in kernel mode?" check pass, when it failed under plain trap-and-emulate?
Show answer
The guest kernel now runs in a real kernel mode, below a new, more privileged level that the VMM's side controls, so the honest answer is "kernel". The level above traps only what it was told to watch.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Before hardware help for memory, how did a VMM stop a guest kernel from mapping memory that is not its own, and what did that cost?
Show answer
With shadow page tables: real tables the VMM keeps, mapping guest addresses straight to host memory, kept in step by trapping every guest write to its own page tables. Every such write cost a trap; a second hardware translation stage removed them.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Someone says "QEMU is a hypervisor". How does this course say the same thing, and which part of a Mac is the course's "hypervisor"?
Show answer
QEMU is a VMM (with its own emulator when no hardware assist is used). In this course the hypervisor is only the part at a level more privileged than the kernel's that controls the processor's support for virtual machines; on a Mac, a part of macOS, not our program.
From chapter 00: Two kernels, one Mac: what a virtual machine is
scripts/doctor.shprintsdoctor: hv_vm_create: OK. What has this proved about the Mac and the probe process?Show answer
The processor has the hardware-assisted level, macOS offers it, and this process (signed with the one permission it needs) was allowed to create a virtual machine.
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; theGuestMemorycontract (read,write,check_range, the little-endian helpers,read_obj), one region per access; copy-only access, and why there is noget_slice(what a&[u8]promises the compiler); volatile element copies versuscopy_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--rawloader (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-memorycrate, 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 andRomRegion(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_allocateand map it withhv_vm_mapin 16 KiB pieces, and explain from the Predict run why 16 KiB: with HVF's default granule,hv_vm_maprefuses anything smaller, stage-2 permissions come per 16 KiB, and the guest's own page size is a separate matter. - Implement the
GuestMemorycontract:read,writeandcheck_range, with the little-endian helpers andread_objon top, wherechecked_addand 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 noget_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 choiceOne 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.
- In
crates/macvmm/src/first_exit.rs, theOwnedMapping::newcall: the address becomesRAM_BASE + 0x1000, the length0x1000. - In
crates/hvf/src/vm.rs,OwnedMapping::new: keep allocating a whole 16 KiB host page (hv_vm_allocaterefuses anything else), but pass the caller's 4 KiB length tohv_vm_map.
Then, from inside learner/, run cargo run -q -p macvmm -- first-exit. Our run, on a real Mac:
cargo run -q -p macvmm -- first-exitfirst-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)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:
/// 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).
cargo run -q -p macvmm -- first-exitfirst-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)cargo run -q -p macvmm -- first-exitfirst-exit: hv_vm_map: HV_BAD_ARGUMENT (0xfae94003)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:
/// 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:
/// 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:
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:
/// `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:
/// 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,}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):
/// 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:
/// 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:
/// 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.
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 translatorIf 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_0004The reference's loader for --raw already does this right; you met its placement check in chapter 03:
/// 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 })}/// 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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0xfffffffffffffff0 --timeout 10macvmm: cannot load the guest: --raw blob 0 (0x2d9a bytes at 0xfffffffffffffff0) does not fit inside guest RAM0xffff_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:
cargo run -q -p macvmm -- run --mem 64M --raw target/guests/aarch64-unknown-none/release/hello.bin@0x43fffff0 --timeout 10macvmm: cannot load the guest: --raw blob 0 (0x2d9a bytes at 0x43fffff0) does not fit inside guest RAMWrite the safe version yourself: the first LEARNER hole is the body of GuestAddress::checked_add. Then compare:
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:
/// 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:
/// 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:
/// 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:
/// 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:
/// 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.
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 8_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 retLook 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:
/// 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:
/// 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:
/// 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:
/// 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;}/// 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:
/// 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, })}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:
/// 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:
// 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:
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:
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:
/// 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:
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.
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:
cargo run -q -p macvmm -- run --mem 64M --raw $G/memtest.bin@0x40080000 --timeout 10; echo "exit status $?"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"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:
scripts/checkpoint.sh 04checkpoint: 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 FAILWhat 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:
CARGO_PROFILE_DEV_OVERFLOW_CHECKS=false CARGO_PROFILE_TEST_OVERFLOW_CHECKS=false scripts/checkpoint.sh 04checkpoint: 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 FAILRead 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:
- The three
LEARNERholes are filled, and thecontractline ofscripts/checkpoint.sh 04(from the repository root) passes.cargo test -p vmminlearner/should pass too, but it runs only your crate's own tests. - The
memtestrun above prints all ten lines andexit status 0. - 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 MacRun this from the repository root:
scripts/checkpoint.sh 04You should see, as the last line:
CHECKPOINT 04 PASSIt 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:
scripts/checkpoint.sh 04checkpoint: 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 PASSWhat 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 abovehv_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.hshows 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 fromhv_vm_allocatefit 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 ourCargo.tomlchanges that?