indicogniBuild a VMM

Contents

Chapter 13 · Part VI

Loading kernels: arm64 Image, initramfs and ELF

14 of 26

Course progress: chapter 13 is 14 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 12: Why an interrupt controller, and why in the kernel

    A device tree node says interrupts = <0 5 4> under a GICv3. Which INTID will the device's interrupt arrive as, and how is it triggered?

    Show answer

    INTID 37. The first cell 0 means SPI (shared peripheral interrupt), and SPI n is INTID 32 + n, so SPI 5 is INTID 37. The third cell 4 means level-sensitive, active high.

  2. From chapter 10: The Device Tree: the VMM's promise to the guest

    A node's parent says #address-cells = <2> and #size-cells = <1>. The node's reg describes two ranges. How many bytes long is the reg property?

    Show answer

    Each range is 2 + 1 = 3 cells, and a cell is 4 bytes, so one range is 12 bytes and two ranges are 24. The counts come from the parent, not from the node itself.

  3. From chapter 06: vCPU state: registers, PSTATE and reset

    Build the PSTATE value for "EL1, using EL1's own stack pointer, with debug, SError, IRQ and FIQ all masked". Show the three parts you add.

    Show answer

    The four mask bits D, A, I, F are bits 9 to 6: 0x200 + 0x100 + 0x80 + 0x40 = 0x3c0. EL1 in bits 3 to 2 is 1 << 2 = 0x4. The stack-pointer select bit 0 set means SP_EL1: 0x1. Together 0x3c5, the mode EL1h.

Concepts you'll need

Chapters before this one: chapter 12, Why an interrupt controller, and why in the kernel.

  • Core, taught here: placement as a contract, written down as a boot plan (BootPlan); the 64-byte arm64 Image header as hostile input; the Linux boot protocol's entry state; an ELF64 loader (a spec exercise); refusing an EFI (Extensible Firmware Interface) zboot wrapper.
  • Core, from earlier: x0 and /chosen (chapter 10); checked arithmetic and guest memory (chapter 04); layout.rs (chapter 05); PSTATE 0x3c5 (chapter 02) and the virtual CPU (vCPU) reset (chapter 06); the random seeds in /chosen (chapter 10); --raw, hello and exit codes 2 and 5 (chapter 03).
  • Primers (read first): arm64-boot-protocol (header, placement, entry state); elf (program headers, filesz versus memsz); cpio-initramfs (the initramfs); efi-zboot (Alpine's kernel as a UEFI (Unified Extensible Firmware Interface) program in PE/COFF (Portable Executable / Common Object File Format)); caches (cleaning to the Point of Coherency (PoC)).
  • Primers (review): bare-metal-rust (BSS, load versus run address); page-granules (supported page sizes).
  • Pointers: sha256 pinning (an Aside); property-based testing (an Aside); gzip, RFC 1952 (a link). For the curious: the UEFI primer, required in chapter 21.
  • Forward definitions: the Linux boot log and earlycon (chapter 14); kernel address space layout randomisation (KASLR, chapter 14). Each is defined in a sentence where it first appears.

Here are the first 64 bytes of the Linux kernel you will boot in chapter 14. At offset 0x10 sit the bytes 00 00 2a 02 00 00 00 00. Read right to left, because the header is little-endian, they are the number 0x022a_0000: the kernel's own statement of how much memory it needs. Copy the file, overwrite those eight bytes with ff, and hand the copy to your virtual machine monitor (VMM). Who notices first?

TerminalReal output
xxd -l 64 .cache/macvmm/Image-virtexit: 0--- stdout ---00000000: 4d5a 40fa 27b4 5514 0000 0000 0000 0000  MZ@.'.U.........00000010: 0000 2a02 0000 0000 0a00 0000 0000 0000  ..*.............00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000030: 0000 0000 0000 0000 4152 4d64 4000 0000  ........ARMd@...
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference's unwrapped Alpine kernel, first 64 bytes.
course/captures/13-image-header.txt
Predict In a copy of the Image, set the eight bytes at offset 0x10 to ff and run it. (a) Linux starts and fails to boot, with nothing from the VMM, or (b) the VMM refuses the file with a named error before any guest instruction runs?

Write your guess and one sentence of reasoning under ## Predict in your journal. "It is the kernel's problem" is the tempting answer. The section on placing the kernel runs it.

This chapter opens row 10 of the problem ledger, the boot chain: the kernel assumes someone loaded it, so our VMM becomes its bootloader. Chapter 14 closes the row.

Objectives: by the end you can

  • Parse the arm64 Image header field by field, refusing every hostile value with a named error.
  • Recognise Alpine's vmlinuz-virt as an EFI zboot wrapper, refuse it by name, and unwrap it with cargo xtask unzboot.
  • Implement a boot plan you can print and test: device tree at 0x4000_0000, Image at 0x4020_0000 + text_offset, initramfs at align_up(kernel end, 2 MiB), all inside RAM and the protocol's 1 GiB window, with the initramfs range in /chosen.
  • Set the protocol's entry state (x0 = device tree, x1 to x3 = 0, CPSR (current program status register) = 0x3c5, the memory management unit (MMU) off) and explain, with the measurement, why we do no cache maintenance.
  • Write a loader for 64-bit ELF (Executable and Linkable Format) files from their specification, and predict which check a hostile file trips.

Before you start. From the repository root, run scripts/learner start 13 (it copies the journal) and type the code into learner/ as you go. Until "Wire it to the command line" nothing calls your loader, so earlier runs use the reference, from the repository root. After it, run your own code from inside learner/, where the cache is ../.cache/; our captures, made from the root, lack the ../. Fetch the kernel and its initramfs:

Shell
scripts/fetch.sh linux
TerminalReal output
scripts/fetch.sh linuxexit: 0--- stdout ---fetch: cached vmlinuz-virtfetch: cached initramfs-virtfetch: cached config-6.18.60-0-virtfetch: cached Image-virtfetch: built initramfs-test.img sha256=caef97fecea58e6ee29a2dda26fba750ad0e0da1df31f4f170b87f14fed204d4
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, run from the repository root; the download cache was already filled, so nothing was downloaded.
course/captures/13-fetch.txt

The last line builds the course's test initramfs from Alpine's.

Aside

Every download is named in scripts/fetch-manifest.txt with its SHA-256 hash (sha256 pinning); yours must match byte for byte. The script uses HTTPS only and never executes what it downloaded: a kernel is data for the VMM, not a program for your Mac. Chapter 25 writes the threat model behind this rule.

Loading is not copying

The first plan that comes to mind: copy the file to guest RAM, set the program counter (PC) there, run. Chapter 03 did that with --raw hello.bin@0x40080000, and it worked because we wrote that guest.

A Linux kernel was written by someone else, for every machine. It needs five answers, and the file holds only some:

The kernel needs to knowWho decidesWhere it comes from
where it sitsthe kernel, partlya 2 MiB-aligned base plus text_offset from its header
how much room it hasthe kernelimage_size from its header: the file plus the memory it will clear
what machine this isthe VMMthe device tree, with its address in x0 (chapter 10)
where its first files arethe VMMthe initramfs, with its range in /chosen
what state the CPU is inthe protocolbooting.rst, section 4

So loading is a contract between the kernel's header, the boot protocol and the VMM's memory map. We write it down as data, a boot plan, check it, print it, and only then copy bytes.

The 64-byte header, read as hostile input

The kernel format is the arm64 Image: one flat binary whose first 64 bytes form a header for its loader. Read the capture above beside this table; all fields are little-endian.

OffsetFieldAlpine's bytesOur rule
0x00code0, code14d5a 40fa 27b4 5514code, not ours to read
0x08text_offset0a multiple of 4 KiB
0x10image_size0x022a_0000not zero; start plus size inside RAM, without overflow
0x18flags0xa (0b1010)bit 0: 0 = little-endian; bits 1-2: page size (0 unspecified, 1 = 4 KiB, 2 = 16 KiB, 3 = 64 KiB, refused); bit 3: may sit anywhere in RAM
0x20..0x37reservedzerosignored
0x38magic41 52 4d 64, ARM\x64must match
0x3cres50x40ignored
(the file)its length0x022a_0000at most image_size

Alpine's flags say 4 KiB pages, bit 3 set. The CPU lists what it supports in ID_AA64MMFR0_EL1 (AArch64 Memory Model Feature Register 0); the page-granules primer reads ours through Hypervisor.framework: 0x000010000f100022. TGran64 (bits 24 to 27) is 0xF, no 64 KiB pages; BigEnd (bits 8 to 11) is 0, no big-endian mode. Reading the kernel's early boot code, such a kernel would stop before printing anything; we have not run one on a Mac. We refuse both by name. An image_size of 0 is a kernel older than 3.17 that never said how much memory it needs.

Every value came from a file, maybe from a fuzzer. The parser checks the length before reading, the magic before trusting the rest, and every field before using it. Each refusal is a typed LoaderError (exit code 2), never a panic. In learner/crates/vmm/src/loader/image.rs:

crates/vmm/src/loader/image.rslines 115-158
/// Validate an arm64 Image header (booting.rst section 4). Pure: looks at the first 64 bytes/// and the file length only.pub fn parse_header(b: &[u8]) -> Result<ImageHeader, LoaderError> {    let len = u64::try_from(b.len()).unwrap_or(u64::MAX);    if b.len() < IMAGE_HEADER_SIZE {        return Err(LoaderError::ImageTooShort { len });    }    let magic_end = ARM64_IMAGE_MAGIC_OFFSET.saturating_add(4);    if b.get(ARM64_IMAGE_MAGIC_OFFSET..magic_end) != Some(ARM64_IMAGE_MAGIC.as_slice()) {        return Err(LoaderError::ImageBadMagic);    }    let short = || LoaderError::ImageTooShort { len };    let text_offset = le64(b, 8).ok_or_else(short)?;    let image_size = le64(b, 16).ok_or_else(short)?;    let flags = le64(b, 24).ok_or_else(short)?;    if flags & FLAG_BE != 0 {        return Err(LoaderError::ImageBigEndian);    }    let page_size = match (flags >> FLAG_PAGE_SIZE_SHIFT) & FLAG_PAGE_SIZE_MASK {        0 => PageSize::Unspecified,        1 => PageSize::K4,        2 => PageSize::K16,        field => return Err(LoaderError::ImagePageSize { field }),    };    if image_size == 0 {        return Err(LoaderError::ImageZeroSize);    }    if !text_offset.is_multiple_of(TEXT_OFFSET_ALIGN) {        return Err(LoaderError::ImageTextOffset { text_offset });    }    if len > image_size {        return Err(LoaderError::ImageFileTooLong {            file_len: len,            image_size,        });    }    Ok(ImageHeader {        text_offset,        image_size,        flags,        page_size,        phys_anywhere: flags & FLAG_PHYS_ANYWHERE != 0,    })}

The last check, file length at most image_size, is the least expected. The plan puts the initramfs right after image_size bytes, so a longer file would be copied over it. A file that breaks its own promise is malformed.

Lab

Image inspector

Drop a kernel file, or pick one, flip a header byte, and see which of the loader's checks fails first and where everything would go in RAM.

Runs in browserOpen full page: Image inspector

Loading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.

Drop .cache/macvmm/Image-virt on the inspector (nothing is uploaded), flip a byte and watch which check fails first.

Placing the kernel

The protocol: "placed text_offset bytes from a 2MB aligned base address anywhere in usable system RAM", with image_size bytes free. Our first 2 MiB belong to the device tree, so the base is 0x4020_0000. Alpine sets bit 3, so any 2 MiB base would do; we take the lowest, which also serves kernels with bit 3 clear (they must sit as close to the start of RAM as possible). In learner/crates/vmm/src/arch/layout.rs:

crates/vmm/src/arch/layout.rslines 224-242
/// The DTB slot at the start of RAM: 2 MiB for a Linux Image, 512 KiB when a test guest/// (linked at `RAM_BASE + 512 KiB`) is loaded.pub const DTB_MAX: u64 = 2 << 20;pub const DTB_MAX_TEST_GUEST: u64 = 512 << 10;/// Where test guests are linked (chapter 03).pub const TEST_GUEST_BASE: u64 = RAM_BASE + DTB_MAX_TEST_GUEST;/// The 2 MiB-aligned base a Linux arm64 Image is placed at, right after the 2 MiB DTB slot./// The kernel itself starts `text_offset` bytes above it (booting.rst section 4: "placed/// text_offset bytes from a 2MB aligned base address").pub const LINUX_IMAGE_BASE: u64 = RAM_BASE + DTB_MAX;/// The alignment of the Image's base address and of the initrd (booting.rst section 4).pub const LINUX_ALIGN: u64 = 2 << 20;/// booting.rst section 4: the initrd must lie, with the kernel Image, inside one/// 1 GiB-aligned physical window of at most 32 GiB.pub const LINUX_WINDOW_ALIGN: u64 = 1 << 30;pub const LINUX_WINDOW_MAX: u64 = 32 << 30;

Chapter 03's two helpers do the range arithmetic; every loader here reuses them unchanged:

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    }}
crates/vmm/src/loader/mod.rslines 95-101
/// Half-open ranges `[a, a + alen)` and `[b, b + blen)` intersect (both assumed in RAM, so/// the ends do not overflow; an overflowing end is treated as reaching `u64::MAX`).pub fn overlaps(a: u64, alen: u64, b: u64, blen: u64) -> bool {    let a_end = a.saturating_add(alen);    let b_end = b.saturating_add(blen);    a < b_end && b < a_end}

Placing the kernel is two checked additions and one range check over the whole image_size, not the file:

crates/vmm/src/loader/image.rslines 162-188
/// Parse `b` and place it at `LINUX_IMAGE_BASE + text_offset` (module docs). The whole/// `image_size` span, not just the file, must fit in RAM: that is the memory the kernel will/// use before it has parsed the device tree.pub fn place(b: &[u8], ram: RamRange) -> Result<ArmImage, LoaderError> {    let header = parse_header(b)?;    let what = "kernel (arm64 Image)";    let outside = |addr: u64| LoaderError::OutsideRam {        what: what.into(),        addr,        len: header.image_size,    };    let load = LINUX_IMAGE_BASE        .checked_add(header.text_offset)        .ok_or_else(|| outside(u64::MAX))?;    let end = load        .checked_add(header.image_size)        .ok_or_else(|| outside(load))?;    if !ram.contains(load, header.image_size) {        return Err(outside(load));    }    Ok(ArmImage {        header,        load,        end,        file_len: u64::try_from(b.len()).unwrap_or(u64::MAX),    })}

Now run your Predict, on the reference for now. Make the copy in .cache/ch13/ (ignored by git), patch it, and run:

Shell
mkdir -p .cache/ch13cp .cache/macvmm/Image-virt .cache/ch13/Image-hugeprintf '\377\377\377\377\377\377\377\377' | dd of=.cache/ch13/Image-huge bs=1 seek=16 conv=notrunccargo run -q -p macvmm -- run --kernel .cache/ch13/Image-huge --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10

dd reports 8+0 records in; that is expected.

TerminalReal output
cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-huge --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: kernel (arm64 Image) (0xffffffffffffffff bytes at 0x40200000) does not fit inside guest RAM
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The kernel is a copy of .cache/macvmm/Image-virt with the 8 bytes at offset 0x10 (image_size) set to ff (the dd command in the lesson).
course/captures/13-image-size-max.txt

Answer (b): exit code 2, and no virtual machine (VM) was created. The VMM acts on the header before the kernel gets control. With wrapping arithmetic, 0x4020_0000 + 0xFFFF_FFFF_FFFF_FFFF would be 0x401F_FFFF, inside RAM, and a check end <= ram_end would wave it through. checked_add turns the overflow into None, and place() turns that into OutsideRam.

Security

The attacker controls a file: every header field, its length, its format. Without these checks what breaks is the VMM, the process holding the hypervisor entitlement.

Which file is it? Magic numbers

--kernel accepts two formats and recognises a third only to refuse it, by the first bytes, never the file name:

crates/vmm/src/loader/mod.rslines 57-71
/// Classify `bytes` by their magic numbers. Total: any input, including an empty one, gets an/// answer.pub fn detect(bytes: &[u8]) -> ImageKind {    if bytes.starts_with(ELF_MAGIC) {        ImageKind::Elf    } else if bytes.starts_with(b"MZ") && bytes.get(4..8) == Some(b"zimg") {        ImageKind::EfiZboot    } else if bytes.get(ARM64_IMAGE_MAGIC_OFFSET..ARM64_IMAGE_MAGIC_OFFSET.saturating_add(4))        == Some(ARM64_IMAGE_MAGIC.as_slice())    {        ImageKind::ArmImage    } else {        ImageKind::Raw    }}

Alpine ships its kernel as vmlinuz-virt. Its first 64 bytes:

TerminalReal output
xxd -l 64 .cache/macvmm/vmlinuz-virtexit: 0--- stdout ---00000000: 4d5a 0000 7a69 6d67 78ca 0000 4bfb 9d00  MZ..zimgx...K...00000010: 0000 0000 0000 0000 677a 6970 0000 0000  ........gzip....00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................00000030: 0000 0000 0000 0000 cd23 8281 4000 0000  .........#..@...
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The Alpine kernel as downloaded (the EFI zboot wrapper), first 64 bytes.
course/captures/13-zboot-header.txt

MZ at offset 0, zimg at 4, gzip at 0x18, and cd23 8281 where the magic should be. This is an EFI zboot wrapper: a small UEFI program, in the PE/COFF format whose files start with MZ, that decompresses the real Image and jumps to it (the efi-zboot primer).

The unwrapped Image also begins with MZ, because it carries an EFI stub: code that lets UEFI firmware start the kernel directly. The wrapper's mark is zimg at offset 4, which detect checks. We have no UEFI firmware, so the VMM says what it is:

Shell
cargo run -q -p macvmm -- run --kernel .cache/macvmm/vmlinuz-virt
TerminalReal output
cargo run -q -p macvmm -- run --kernel .cache/macvmm/vmlinuz-virtexit: 2--- stderr ---macvmm: cannot load the guest: EFI zboot image; run scripts/fetch.sh linux (unwraps it) or pass the raw Image
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, given the Alpine kernel exactly as downloaded.
course/captures/13-zboot-refused.txt

The payload is gzip (RFC 1952). We unwrap it once, on the host, and check the result against the pinned hash. fetch.sh did this for you; do it yourself once:

Shell
cargo xtask unzboot .cache/macvmm/vmlinuz-virt .cache/ch13/Imageshasum -a 256 .cache/ch13/Image .cache/macvmm/Image-virt
TerminalReal output
cargo xtask unzboot .cache/macvmm/vmlinuz-virt .cache/ch13/Imageexit: 0--- stdout ---unzboot: wrote .cache/ch13/Image
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified; the output went to a private scratch directory, shown as .cache/ch13.
course/captures/13-unzboot.txt
TerminalReal output
shasum -a 256 .cache/ch13/Image .cache/macvmm/Image-virtexit: 0--- stdout ---a2cecb9b6fdbd83e87bd43c8040de67300d5b8dde1fc50c34714faa272888f17  .cache/ch13/Imagea2cecb9b6fdbd83e87bd43c8040de67300d5b8dde1fc50c34714faa272888f17  .cache/macvmm/Image-virt
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Right after the unzboot run; the first file is its output, the second the copy fetch.sh made.
course/captures/13-unzboot-sha.txt

Why not decompress in the VMM at every boot? Decompressors are a classic home of memory-safety bugs, and this one would parse internet bytes in the process that creates VMs. On the host it runs once, against a pinned hash, and the VMM's input stays a format we validate in about 45 lines.

The initramfs: opaque bytes, one rule

The kernel needs files before it has a disk driver: its first program, /init, and what that needs. They arrive as the initramfs, a cpio archive the kernel unpacks into memory. The VMM never parses it; it places it by three rules: outside the kernel's image_size span; with the kernel, inside "a 1 GB aligned physical memory window of up to 32 GB" (booting.rst section 4); and inside RAM. We start it at the kernel's end rounded up to 2 MiB: the protocol asks for no alignment, but this keeps it page-aligned and the numbers readable. align_up(x, a) rounds up to a multiple of the power of two a, or returns None on overflow:

crates/vmm/src/loader/initrd.rslines 34-57
/// Place a `size`-byte initrd above a kernel whose memory ends at `kernel_end` (module docs)./// Returns `[start, end)`.pub fn place(    ram: RamRange,    kernel_start: u64,    kernel_end: u64,    size: u64,) -> Result<(u64, u64), LoaderError> {    if size == 0 {        return Err(LoaderError::InitrdEmpty);    }    let outside = |addr| LoaderError::OutsideRam {        what: "initrd".into(),        addr,        len: size,    };    let start = align_up(kernel_end, LINUX_ALIGN).ok_or_else(|| outside(kernel_end))?;    let end = start.checked_add(size).ok_or_else(|| outside(start))?;    if size > ram.size || !ram.contains(start, size) {        return Err(outside(start));    }    check_window(kernel_start, kernel_end, start, end)?;    Ok((start, end))}

For the window, the best candidate starts at the 1 GiB boundary at or below the lower start (a higher one misses that start, a lower one wastes its 32 GiB), so if it fails every window fails:

crates/vmm/src/loader/initrd.rslines 61-76
/// booting.rst section 4: the kernel `[kstart, kend)` and the initrd `[istart, iend)` must both lie in/// one 1 GiB-aligned window of at most 32 GiB. The best window starts at the 1 GiB boundary at/// or below the lower of the two starts; the rule holds iff the higher end is within 32 GiB of/// it.pub fn check_window(kstart: u64, kend: u64, istart: u64, iend: u64) -> Result<(), LoaderError> {    let low = kstart.min(istart);    let base = low & !(LINUX_WINDOW_ALIGN.wrapping_sub(1));    let high = kend.max(iend);    match high.checked_sub(base) {        Some(span) if span <= LINUX_WINDOW_MAX => Ok(()),        _ => Err(LoaderError::InitrdWindow {            start: istart,            end: iend,        }),    }}

Because the initramfs sits right after the kernel, near our 1 GiB-aligned RAM base, the window fails only for an initramfs of about 32 GiB, which needs --mem above 32G. The contract test one_gib_window_rule builds exactly that case.

Lab

cpio inspector

Drop an initramfs (or pick a sample) and walk it the way Linux does: every member, every newc header field and padding byte, which later entries overwrite earlier ones, the boot-log lines that follow, and what a host cpio tool shows instead.

Runs in browserOpen full page: cpio inspector
cpio inspector: both.cpio, as the kernel and a host tool read it both.cpio is 1,024 bytes: two newc archives of one 512-byte block each. Archive 1 holds init (21 bytes, echo hello): a 110-byte header at 0, the name init and its NUL at 110 to 114, one padding byte, the data at 116 to 136, three padding bytes, then TRAILER!!! at 140, whose next header would start at 264, and zeros to 512. Archive 2 at 512 holds init again (22 bytes, echo second) and its own trailer. A host cpio tool stops at the first TRAILER!!! and lists one init of 21 bytes. The kernel treats each trailer as the end of one member, keeps reading, and the second init replaces the first. both.cpio (1,024 bytes) member 1 at 0: init (21) + TRAILER!!! member 2 at 512: init (22) + TRAILER!!! one entry: header, name, pad, data, pad 0 header (110) 110 init\0 116 data (21 bytes) 140 next host cpio -itv: stops at the first TRAILER!!!, lists one init (21 bytes) kernel: reads both members; /init is member 2's (echo second)

Drop .cache/macvmm/initramfs-test.img on the inspector and find /init.

The kernel learns the range from chapter 10's /chosen node, which gains linux,initrd-start, linux,initrd-end and bootargs, the kernel command line (options such as console=). It keeps chapter 10's two fresh random seeds, for the kernel's random number generator (RNG) and for KASLR, which puts the kernel's code at a random address each boot so an attacker cannot guess it (chapter 14). The kernel needs this randomness before it has any of its own. In learner/crates/vmm/src/fdt/machine.rs:

crates/vmm/src/fdt/machine.rslines 212-239
/// `/chosen` (devicetree specification section 3.6; booting.rst section 2; Linux/// `drivers/of/fdt.c`).fn chosen(w: &mut FdtWriter, layout: &Layout, d: &MachineDesc) -> Result<(), FdtError> {    let n = w.begin_node("chosen")?;    if let Some(args) = &d.bootargs {        // Linux would silently truncate a longer line; a NUL would end it early.        if args.len() > MAX_BOOTARGS || args.as_bytes().contains(&0) {            return Err(bad(format!(                "bootargs must be at most {MAX_BOOTARGS} bytes without NUL"            )));        }        w.prop_str("bootargs", args)?;    }    w.prop_str("stdout-path", &stdout_path(layout)?)?;    if let Some((start, end)) = d.initrd {        if start >= end {            return Err(bad("initrd end must be above its start"));        }        // Two cells each; the end is exclusive (Linux `early_init_dt_check_for_initrd`).        w.prop_u64("linux,initrd-start", start)?;        w.prop_u64("linux,initrd-end", end)?;    }    // Fresh per boot from the host's secure random generator; zeroed in --dtb-out copies, so    // a saved tree never leaks the seeds the guest used.    w.prop_bytes("rng-seed", &d.rng_seed)?;    w.prop_u64("kaslr-seed", d.kaslr_seed)?;    w.end_node(n)}

The plan, printed

All of this is one pure function: bytes and a RAM size in, a BootPlan or a named error out. In learner/crates/vmm/src/loader/plan.rs:

crates/vmm/src/loader/plan.rslines 95-121
/// The complete, validated boot plan.#[derive(Clone, Debug, PartialEq, Eq)]pub struct BootPlan {    pub entry: u64,    pub cpsr: u64,    pub x0: u64,    /// The guest RAM this plan was checked against.    pub ram: RamRange,    /// The device-tree slot: reserved by [`plan`], sized to the blob by    /// [`BootPlan::set_dtb_len`] once the tree is built.    pub dtb: Placement,    /// The largest blob that fits: `min(DTB_MAX, RAM size, lowest image - RAM base)`.    pub dtb_limit: u64,    /// Every image, in load order.    pub images: Vec<Placement>,    /// The parsed kernel ELF, if `--kernel` was an ELF.    pub elf: Option<elf::ElfImage>,    /// The placed arm64 Image, if `--kernel` was one.    pub image: Option<image::ArmImage>,    /// The initrd `[start, end)`, for `/chosen/linux,initrd-{start,end}`.    pub initrd: Option<(u64, u64)>,    /// `/chosen/bootargs`: `--cmdline`, or [`default_cmdline`] for an Image.    pub bootargs: Option<String>,    /// The `--bios` firmware image in flash bank 0 (chapter 21; outside RAM, so not one of    /// `images`).    pub firmware: Option<Placement>,}

Before looking at the kernel, plan() always reserves the first 512 KiB of RAM for the device tree:

crates/vmm/src/loader/plan.rslines 206-210
let dtb = Placement {    what: "device tree (reserved)".into(),    addr: ram.base,    len: DTB_MAX_TEST_GUEST.min(ram.size),};

For an Image, the plan keeps the kernel clear of the device tree's full 2 MiB, makes the PC its first byte, places the initramfs and picks the command line. The default, console=ttyAMA0 earlycon=pl011,0x09000000, names the first PL011 and makes the kernel print through it before its drivers load (chapter 14).

crates/vmm/src/loader/plan.rslines 243-264
ImageKind::ArmImage => {    let img = image::place(bytes, ram)?;    let p = img.placement();    if overlaps(p.addr, p.len, dtb.addr, DTB_MAX.min(ram.size)) {        return Err(LoaderError::OverlapsDtb { what: p.what });    }    // booting.rst section 4: PC = the kernel's first byte (the header's `code0`).    entry = Some(img.load);    images.push(p);    if let Some(rd) = inputs.initrd {        let size = u64::try_from(rd.len()).unwrap_or(u64::MAX);        let (start, end) = initrd::place(ram, img.load, img.end, size)?;        images.push(Placement {            what: "initrd".into(),            addr: start,            len: size,        });        initrd_range = Some((start, end));    }    bootargs = Some(inputs.cmdline.map_or_else(default_cmdline, str::to_owned));    arm_image = Some(img);}

Last, dtb_limit, how far the device tree may actually grow: at most 2 MiB, inside RAM, never into the lowest image:

crates/vmm/src/loader/plan.rslines 292-295
// The DTB may grow up to 2 MiB, but never into the lowest image (images above RAM are// impossible here: every placement was checked against `ram` above).let lowest = images.iter().map(|p| p.addr).min().unwrap_or(u64::MAX);let dtb_limit = DTB_MAX.min(ram.size).min(lowest.saturating_sub(ram.base));

Wire it to the command line

Your plan() has taken a BootInputs since chapter 03, with kernel always None. In learner/crates/macvmm/src/cli.rs, run learns --kernel FILE, refused if given twice:

crates/macvmm/src/cli.rslines 235-240
"--kernel" => {    if cfg.boot.kernel.is_some() {        return Err("--kernel given twice".into());    }    cfg.boot.kernel = Some(PathBuf::from(value()?));}

and the two inputs only an Image may take:

crates/macvmm/src/cli.rslines 244-259
"--initrd" => {    if cfg.boot.initrd.is_some() {        return Err("--initrd given twice".into());    }    let path = value()?;    if path.is_empty() {        return Err("--initrd needs a file name".into());    }    cfg.boot.initrd = Some(PathBuf::from(path));}"--cmdline" => {    if cfg.boot.cmdline.is_some() {        return Err("--cmdline given twice".into());    }    cfg.boot.cmdline = Some(value()?);}

The parser records paths only. Then, in your run command, before any Hypervisor.framework call:

  1. Read each file whole, as your --raw path reads its blob: a regular file, not empty, at most the RAM size. (The reference's is read_input in crates/vmm/src/backend/hostio.rs.)
  2. Hand the bytes to plan() in the kernel, initrd and cmdline fields of BootInputs; plan() calls detect, so the file name never matters.
  3. Print a LoaderError as macvmm: cannot load the guest: and its message, and exit with code 2.
  4. Add --dry-run, a flag with no value (chapter 05 ran only the reference's): print macvmm boot plan (dry run, no VM created) and the plan, exit 0, create no VM.
  5. Until the ELF loader, let the ImageKind::Elf arm return LoaderError::NotAKernel (its "not an ELF file" message is wrong for a real ELF until then).

From here on, run from inside learner/. First, your Predict again, now on your own code:

Shell
cargo run -q -p macvmm -- run --kernel ../.cache/ch13/Image-huge --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 10

It must print the same refusal, with exit code 2.

Because the plan is pure, --dry-run creates no VM. To prove it, use a binary with no hypervisor entitlement. Your workspace builds into ../target/learner; copy the binary and sign the copy with no entitlement. codesign must then print only the Executable= line, no com.apple.security.hypervisor key:

Shell
cargo build -q -p macvmmmkdir -p ../target/ch13cp ../target/learner/debug/macvmm ../target/ch13/macvmm-noent../scripts/sign.sh --no-entitlements ../target/ch13/macvmm-noentcodesign -d --entitlements - ../target/ch13/macvmm-noent
TerminalReal output
cp target/debug/macvmm target/ch13/macvmm-noent && scripts/sign.sh --no-entitlements target/ch13/macvmm-noent && codesign -d --entitlements - target/ch13/macvmm-noentexit: 0--- stderr ---Executable=<repo>/target/ch13/macvmm-noent
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference binary, copied and re-signed WITHOUT any entitlement (sign.sh --no-entitlements); codesign then prints the signature's entitlements: none, only the Executable= line.
course/captures/13-noent-sign.txt

Now the dry run, from that copy:

Shell
../target/ch13/macvmm-noent run --dry-run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M
TerminalReal output
target/ch13/macvmm-noent run --dry-run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512Mexit: 0--- stdout ---macvmm boot plan (dry run, no VM created)ram     0x40000000..0x60000000  512 MiBdtb     0x40000000..0x40000724  device tree (1828 bytes)kernel  0x40200000..0x424a0000  kernel (arm64 Image) (36306944 bytes)initrd  0x42600000..0x42efd8fc  initrd (9427196 bytes)header  text_offset=0x0 image_size=0x22a0000 file=0x22a0000 page_size=K4cmdline "console=ttyAMA0 earlycon=pl011,0x09000000"entry   pc=0x40200000 x0=0x40000000 cpsr=0x3c5memory map (Virt):  0x00000000..0x04000000  flash0       Rom  0x04000000..0x08000000  flash1       Rom  0x08000000..0x08010000  gicd         GicDist  0x08010000..0x08020000  gicv2-cpu    Reserved  0x08020000..0x08030000  gic-v2m      GicMsi  0x08080000..0x080a0000  gic-its      Reserved  0x080a0000..0x09000000  gicr         GicRedist  0x09000000..0x09001000  pl011        Mmio intid 33  0x09010000..0x09011000  pl031        Mmio intid 34  0x09020000..0x09020018  fw-cfg       Reserved  0x09030000..0x09031000  pl061        Reserved intid 39  0x0a000000..0x0a004000  virtio-mmio  Mmio  0x0b000000..0x0b001000  testdev      Mmio  0x0c000000..0x0e000000  probe-hole   Reserved  0x10000000..0x3eff0000  pcie-mmio    Reserved  0x3eff0000..0x3f000000  pcie-pio     Reserved  0x3f000000..0x40000000  pcie-ecam    Reserved  0x40000000..0x60000000  ram          Ramdevice tree: 1828 bytes at 0x40000000 (limit 2097152), 1 vCPU(s), irqchip InKernelGicV3, rng-seed 64 bytes and kaslr-seed (values not shown)  /chosen linux,initrd-start 0x42600000 linux,initrd-end 0x42efd8fcdebug hypercalls: off
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, run as the unentitled copy target/ch13/macvmm-noent (made in the capture 13-noent-sign), so any VM creation would fail.
course/captures/13-dry-run.txt

Exit 0, and every number this chapter set out to produce. Ask the same copy to boot for real:

Shell
../target/ch13/macvmm-noent run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 10
TerminalReal output
target/ch13/macvmm-noent run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10exit: 1--- stderr ---macvmm: create VM: hv_vm_create: HV_DENIED (0xfae94007)hint: HV_DENIED: this binary is not signed with the      com.apple.security.hypervisor entitlement (never signed, or relinked by      a later cargo build). Run it through scripts/sign-and-run.sh (`cargo run      -p macvmm -- run ...` does this) or sign it with scripts/sign.sh.
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The same unentitled copy (target/ch13/macvmm-noent), now asked to really boot.
course/captures/13-no-entitlement.txt

hv_vm_create returns HV_DENIED. So the dry run cannot have created a VM: plan() is a pure function that never reaches the hvf crate.

Try it

The header row says file=0x22a0000, equal to image_size: is the Image padded with zeros? Its last non-zero byte is at 0x1972807 (we searched backwards). tail counts from 1, so +26683401 (echo $((0x1972808 + 1))) starts right after it; cmp compares the rest with zeros.

Shell
xxd -s 0x1972800 -l 16 ../.cache/macvmm/Image-virttail -c +26683401 ../.cache/macvmm/Image-virt | cmp - /dev/zero
TerminalReal output
xxd -s 0x1972800 -l 16 .cache/macvmm/Image-virt; tail -c +26683401 .cache/macvmm/Image-virt | cmp - /dev/zeroexit: 1--- stdout ---01972800: ffff ffff ffff ffff 0000 0000 0000 0000  ................--- stderr ---cmp: EOF on stdin
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference's unwrapped Alpine kernel: the 16 bytes around its last non-zero byte (offset 0x1972807), then a comparison of everything after it with zeros. cmp reaching EOF on its input means every remaining byte, up to image_size (0x22a0000), is zero.
course/captures/13-image-tail.txt

EOF on stdin: the file ran out before any non-zero byte, so its last 9 MiB or so are zeros, standing in for the kernel's BSS and early page tables. Another build may leave them out; only the header says how far the kernel reaches.

Good place to stop. The parser, the plan and --dry-run build and run. The rest needs your Mac, your workspace and about 2 hours.

The entry state, register by register

Chapter 10 set x0 and chapter 06 the reset state. What booting.rst section 4 asks of the registers, for a kernel entered at exception level 1 (EL1):

StateValueWhy
PCthe kernel's first byte, 0x4020_0000the header's first two words are instructions that branch into the kernel; the first is chosen so its bytes also spell MZ and it does nothing (the arm64-boot-protocol primer)
x00x4000_0000, the device treethe kernel's only description of the machine
x1, x2, x30"reserved for future use"; a non-zero value may mean something one day
CPSR (Hypervisor.framework's name for the vCPU's PSTATE, chapter 02)0x3c5EL1h (EL1, using its own stack pointer), with debug, SError (system error), IRQ (interrupt request) and FIQ (fast interrupt request) masked
MMUoff (SCTLR_EL1.M = 0, in the system control register, chapter 06)required: the kernel builds its own page tables
instruction cacheon or offrequired: no stale lines for the Image
SCTLR_EL1.C and .I0our reset's choice, not the protocol's; with the MMU off, data accesses are non-cacheable anyway
the Image's bytescleaned to the Point of Coherency (PoC)below

booting.rst also requires the timer frequency programmed, one counter offset across CPUs, and the interrupt controller's system-register interface enabled: Hypervisor.framework and its Generic Interrupt Controller (GIC, chapter 12) provide these, except the offset, which is ours (chapter 11).

The plan's numbers become the boot parameters, in learner/crates/vmm/src/machine/mod.rs, and chapter 06's reset applies them:

crates/vmm/src/machine/mod.rslines 486-490
let boot = BootParams {    pc: self.plan.entry,    x: [self.plan.x0, 0, 0, 0],    cpsr: self.plan.cpsr,};
crates/vmm/src/vcpu/mod.rslines 179-212
/// Put the vCPU in its boot state (chapter 06: the CPU's *reset state*, as opposed to a/// system reset the guest asks for through PSCI). Only what a guest relies on is set:/// - `PC` = the entry point and `x0..x3` = the boot arguments (booting.rst section 4:///   x0 = the device tree address);/// - `CPSR` = `0x3c5` by default: EL1h, D/A/I/F masked (`arch::regs::Pstate`);/// - `SCTLR_EL1.{M,C,I} = 0`: translation and caches off, the state booting.rst requires;/// - the VM-wide virtual-counter offset (chapter 11: the same value on every vCPU, so the///   guest's counter starts near 0 and agrees across CPUs).////// `MPIDR_EL1` was set by [`Vcpu::create`]. Every other register keeps HVF's default,/// which reads 0 through the API, `SCTLR_EL1` included. A dump still shows `SCTLR_EL1 =/// 0x30000180`: its RES1 bits (7, 8, 28, 29 on this CPU) read as 1 whatever is written/// (verified on a real Mac). Clearing only M, C and I is a defensive habit: change only/// the bits you mean to change.pub fn reset(&self, boot: &BootParams, vtimer_offset: u64) -> Result<()> {    let v = &self.inner;    v.set_reg(Reg::PC, boot.pc).map_err(hv("set PC"))?;    for (i, value) in boot.x.iter().enumerate() {        let reg = u8::try_from(i)            .ok()            .and_then(Reg::x)            .ok_or(Error::Internal("x index"))?;        v.set_reg(reg, *value).map_err(hv("set x0..x3"))?;    }    v.set_reg(Reg::CPSR, boot.cpsr).map_err(hv("set CPSR"))?;    let sctlr = v        .get_sys_reg(SysReg::SCTLR_EL1)        .map_err(hv("get SCTLR_EL1"))?;    v.set_sys_reg(SysReg::SCTLR_EL1, sctlr & !SCTLR_MMU_CACHES)        .map_err(hv("set SCTLR_EL1"))?;    v.set_vtimer_offset(vtimer_offset)        .map_err(hv("set vtimer offset"))?;    Ok(())}

The last row needs the caches primer. With its MMU off, the kernel reads memory around the caches, while our VMM wrote the Image through a cacheable mapping; if our writes still sat in a cache, the kernel would read old RAM. So the protocol asks that the Image be cleaned to the PoC, where every observer agrees. Our copy is a plain bounds-checked write:

crates/vmm/src/loader/image.rslines 192-204
/// Copy the Image's file bytes to its load address. The rest of `image_size` (BSS, early page/// tables) is left as it is: guest RAM is freshly allocated, hence zero, on every boot, and/// the kernel clears its own BSS anyway.pub fn load(img: &ArmImage, b: &[u8], mem: &dyn GuestMemory) -> Result<(), LoaderError> {    if u64::try_from(b.len()).unwrap_or(u64::MAX) != img.file_len {        return Err(LoaderError::ImageFileTooLong {            file_len: u64::try_from(b.len()).unwrap_or(u64::MAX),            image_size: img.file_len,        });    }    mem.write(GuestAddress(img.load), b)?;    Ok(())}

No cache maintenance follows: a measured decision. The measurement is chapter 04's memtest, run here by the reference from the repository root, since it loads memtest from its ELF file and your ELF loader comes last. With its MMU off the guest writes patterns over 16 MiB, then our VMM hashes the same memory through its cacheable mapping:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/memtest --timeout 10exit: 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 ok
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: chapter 04's memtest guest, now loaded from its ELF file. With its MMU off it writes patterns over 16 MiB and the VMM hashes the same memory through its own cacheable mapping.
course/captures/13-memtest.txt

The line memhash ok is the comparison: the guest's hash of what it wrote equals the hash our VMM computed through its own mapping. That is guest to host. Host to guest, which loading needs, is shown by every Linux boot here and in chapter 14: about 35 MiB of kernel copied in, then run with the MMU off. The caches primer explains why this is a measured property of Apple Silicon, not a rule. The lab shows the hazard:

Lab

Cache views

Write guest RAM from the VMM or an MMU-off guest, then clean or invalidate cache lines and see who reads stale data and which operation can lose a write.

Runs in browserOpen full page: Cache views
Two observers of one guest RAM line The VMM writes 0x4D through its write-back cache, so the line sits dirty in the cache while RAM still holds 0x00. The guest, with its MMU off, reads RAM around the cache and gets the stale 0x00. Cleaning the line to the Point of Coherency writes 0x4D to RAM and fixes the guest's read. In the other direction, a guest write goes straight to RAM, the VMM's cached copy becomes stale, and invalidating the line fixes the VMM's read. Invalidating a dirty line instead of cleaning it throws the VMM's write away. VMM cacheable map cache: 0x4D Dirty RAM: 0x00 the PoC guest reads 0x00 STALE write clean (DC CVAC) MMU off: around the cache Invalidate drops a dirty line: write lost.

Breaking it on purpose

Two breaks, each predicted first, on your own code. The second needs an edit; undo it afterwards.

Deliberate breakage 1: flip the magic. Copy the Image and change the byte at 0x38 from A to B:

Shell
cp ../.cache/macvmm/Image-virt ../.cache/ch13/Image-badmagicprintf 'B' | dd of=../.cache/ch13/Image-badmagic bs=1 seek=56 conv=notrunccargo run -q -p macvmm -- run --kernel ../.cache/ch13/Image-badmagic --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 10

Predict the message, then what happens if the same bytes go through --raw, which parses nothing:

TerminalReal output
cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-badmagic --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: --initrd needs an arm64 Image --kernel
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The kernel is a copy of .cache/macvmm/Image-virt with the byte at offset 0x38 changed from 0x41 ('A') to 0x42 ('B'); the copy lived in a private scratch directory, shown as .cache/ch13.
course/captures/13-bad-magic.txt

Your ImageBadMagic never fires here. detect looks at the magic first, decides this is not an Image, and the plan refuses the --initrd that only an Image may take. Drop --initrd and detect's verdict shows directly:

Shell
cargo run -q -p macvmm -- run --kernel ../.cache/ch13/Image-badmagic --mem 512M --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-badmagic --mem 512M --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: --kernel is not an ELF file; load a flat binary with --raw F@ADDR
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The same corrupted kernel as the bad-magic run (byte 0x38 changed from 'A' to 'B'), this time without --initrd; the copy lived in a private scratch directory, shown as .cache/ch13.
course/captures/13-bad-magic-no-initrd.txt

No magic matched, so detect returned Raw and the plan refused it as NotAKernel, exit 2. That message assumes you meant an ELF and points at --raw for flat binaries: the next command. (The magic check in parse_header guards callers that skip detect; the checkpoint's tests reach it.) With no parser, copied to 0x4020_0000 and started there:

Shell
cargo run -q -p macvmm -- run --raw ../.cache/ch13/Image-badmagic@0x40200000 --mem 512M --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --raw .cache/ch13/Image-badmagic@0x40200000 --mem 512M --timeout 10exit: 5--- stdout ---[    0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][    0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[    0.000000] random: crng init done[    0.000000] Machine model: macvmm-virt[    0.000000] efi: UEFI not found.[    0.000000] OF: reserved mem: Reserved memory: No reserved-memory node in the DT[    0.000000] NUMA: Faking a node at [mem 0x0000000040000000-0x000000005fffffff][    0.000000] NODE_DATA(0) allocated [mem 0x5fd038c0-0x5fd05d7f][    0.000000] Zone ranges:[    0.000000]   DMA      [mem 0x0000000040000000-0x000000005fffffff][    0.000000]   DMA32    empty[    0.000000]   Normal   empty[    0.000000] Movable zone start for each node[    0.000000] Early memory node ranges[    0.000000]   node   0: [mem 0x0000000040000000-0x000000005fffffff][    0.000000] Initmem setup node 0 [mem 0x0000000040000000-0x000000005fffffff][    0.000000] psci: probing for conduit method from DT.[    0.000000] psci: PSCIv1.1 detected in firmware.[    0.000000] psci: Using standard PSCI v0.2 function IDs[    0.000000] psci: Trusted OS migration not required[    0.000000] psci: SMC Calling Convention v1.1[    0.000000] percpu: Embedded 34 pages/cpu s99608 r8192 d31464 u139264[    0.000000] Detected PIPT I-cache on CPU0[    0.000000] CPU features: detected: Address authentication (IMP DEF algorithm)[    0.000000] CPU features: detected: GICv3 CPU interface[    0.000000] CPU features: detected: Spectre-v4[    0.000000] CPU features: detected: Spectre-BHB[    0.000000] alternatives: applying boot alternatives[    0.000000] Kernel command line: [    0.000000] printk: log buffer data + meta data: 131072 + 458752 = 589824 bytes[    0.000000] Dentry cache hash table entries: 65536 (order: 7, 524288 bytes, linear)[    0.000000] Inode-cache hash table entries: 32768 (order: 6, 262144 bytes, linear)[    0.000000] software IO TLB: SWIOTLB bounce buffer size adjusted to 0MB[    0.000000] software IO TLB: area num 1.[    0.000000] software IO TLB: mapped [mem 0x000000005f380000-0x000000005f400000] (0MB)[    0.000000] Fallback order for Node 0: 0 [    0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 131072[    0.000000] Policy zone: DMA[    0.000000] mem auto-init: stack:all(zero), heap alloc:on, heap free:off[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1[    0.000000] Dynamic Preempt: none[    0.000000] rcu: Preemptible hierarchical RCU implementation.[    0.000000] rcu: 	RCU restricting CPUs from NR_CPUS=4096 to nr_cpu_ids=1.[    0.000000] 	Trampoline variant of Tasks RCU enabled.[    0.000000] 	Tracing variant of Tasks RCU enabled.[    0.000000] rcu: RCU calculated value of scheduler-enlistment delay is 100 jiffies.[    0.000000] rcu: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1[    0.000000] RCU Tasks: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] RCU Tasks Trace: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] NR_IRQS: 64, nr_irqs: 64, preallocated irqs: 0[    0.000000] GICv3: 988 SPIs implemented[    0.000000] GICv3: 0 Extended SPIs implemented[    0.000000] Root IRQ handler: gic_handle_irq[    0.000000] GICv3: GICv3 features: 16 PPIs, RSS[    0.000000] GICv3: GICD_CTLR.DS=1, SCR_EL3.FIQ=0[    0.000000] GICv3: CPU0: found redistributor 0 region 0:0x00000000080a0000[    0.000000] rcu: srcu_init: Setting srcu_struct sizes based on contention.[    0.000000] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 1911260446275000 ns[    0.000000] arch_timer: cp15 timer running at 24.00MHz (virt).[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x588fe9dc0, max_idle_ns: 440795202592 ns[    0.000000] sched_clock: 56 bits at 24MHz, resolution 41ns, wraps every 4398046511097ns[    0.000190] kfence: initialized - using 2097152 bytes for 255 objects at 0x(____ptrval____)-0x(____ptrval____)[    0.000227] Console: colour dummy device 80x25[    0.000229] printk: legacy console [tty0] enabled[    0.000271] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=24000)[    0.000273] pid_max: default: 32768 minimum: 301[    0.000288] LSM: initializing lsm=lockdown,capability,landlock,yama[    0.000348] landlock: Up and running.[    0.000348] Yama: becoming mindful.[    0.000371] Mount-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.000372] Mountpoint-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.000807] rcu: Hierarchical SRCU implementation.[    0.000812] rcu: 	Max phase no-delay instances is 400.[    0.000923] EFI services will not be available.[    0.000936] smp: Bringing up secondary CPUs ...[    0.000939] smp: Brought up 1 node, 1 CPU[    0.000940] SMP: Total of 1 processors activated.[    0.000941] CPU: All CPU(s) started at EL1[    0.000947] CPU features: detected: Branch Target Identification[    0.000948] CPU features: detected: ARMv8.4 Translation Table Level[    0.000949] CPU features: detected: Data cache clean to the PoU not required for I/D coherence[    0.000950] CPU features: detected: Common not Private translations[    0.000951] CPU features: detected: CRC32 instructions[    0.000951] CPU features: detected: Data independent timing control (DIT)[    0.000952] CPU features: detected: E0PD[    0.000952] CPU features: detected: Enhanced Privileged Access Never[    0.000953] CPU features: detected: Generic authentication (IMP DEF algorithm)[    0.000955] CPU features: detected: RCpc load-acquire (LDAPR)[    0.000955] CPU features: detected: LSE atomic instructions[    0.000956] CPU features: detected: Privileged Access Never[    0.000956] CPU features: detected: RAS Extension Support[    0.000957] CPU features: detected: Speculation barrier (SB)[    0.000958] CPU features: detected: TLB range maintenance instructions[    0.000958] CPU features: detected: Scalable Matrix Extension[    0.000959] CPU features: detected: SME2[    0.000979] alternatives: applying system-wide alternatives[    0.001710] SME: minimum available vector length 64 bytes per vector[    0.001711] SME: maximum available vector length 64 bytes per vector[    0.001712] SME: default vector length 64 bytes per vector[    0.001733] Memory: 473304K/524288K available (13312K kernel code, 1994K rwdata, 8460K rodata, 2048K init, 9282K bss, 48508K reserved, 0K cma-reserved)[    0.002174] devtmpfs: initialized[    0.002459] posixtimers hash table entries: 512 (order: 1, 8192 bytes, linear)[    0.002469] futex hash table entries: 256 (16384 bytes on 1 NUMA nodes, total 16 KiB, linear).[    0.002483] 23904 pages in range for non-PLT usage[    0.002483] 515424 pages in range for PLT usage[    0.002510] pinctrl core: initialized pinctrl subsystem[    0.002565] DMI not present or invalid.[    0.003138] NET: Registered PF_NETLINK/PF_ROUTE protocol family[    0.003205] DMA: preallocated 128 KiB GFP_KERNEL pool for atomic allocations[    0.003222] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA pool for atomic allocations[    0.003281] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA32 pool for atomic allocations[    0.003291] audit: initializing netlink subsys (disabled)[    0.003344] thermal_sys: Registered thermal governor 'step_wise'[    0.003349] audit: type=2000 audit(0.002:1): state=initialized audit_enabled=0 res=1[    0.003353] cpuidle: using governor ladder[    0.003354] cpuidle: using governor menu[    0.003363] hw-breakpoint: found 6 breakpoint and 4 watchpoint registers.[    0.003366] ASID allocator initialised with 65536 entries[    0.003385] Serial: AMBA PL011 UART driver[    0.003515] 9000000.pl011: ttyAMA0 at MMIO 0x9000000 (irq = 13, base_baud = 0) is a PL011 rev1[    0.003541] printk: console [ttyAMA0] enabled[    0.050403] HugeTLB: registered 1.00 GiB page size, pre-allocated 0 pages[    0.050408] HugeTLB: 0 KiB vmemmap can be freed for a 1.00 GiB page[    0.050409] HugeTLB: registered 32.0 MiB page size, pre-allocated 0 pages[    0.050410] HugeTLB: 0 KiB vmemmap can be freed for a 32.0 MiB page[    0.050410] HugeTLB: registered 2.00 MiB page size, pre-allocated 0 pages[    0.050411] HugeTLB: 0 KiB vmemmap can be freed for a 2.00 MiB page[    0.050412] HugeTLB: registered 64.0 KiB page size, pre-allocated 0 pages[    0.050412] HugeTLB: 0 KiB vmemmap can be freed for a 64.0 KiB page[    0.050570] ACPI: Interpreter disabled.[    0.050578] iommu: Default domain type: Translated[    0.050579] iommu: DMA domain TLB invalidation policy: lazy mode[    0.054081] clocksource: Switched to clocksource arch_sys_counter[    0.060386] VFS: Disk quotas dquot_6.6.0[    0.060394] VFS: Dquot-cache hash table entries: 512 (order 0, 4096 bytes)[    0.060657] pnp: PnP ACPI: disabled[    0.062072] NET: Registered PF_INET protocol family[    0.062113] IP idents hash table entries: 8192 (order: 4, 65536 bytes, linear)[    0.067118] tcp_listen_portaddr_hash hash table entries: 256 (order: 0, 4096 bytes, linear)[    0.067123] Table-perturb hash table entries: 65536 (order: 6, 262144 bytes, linear)[    0.067125] TCP established hash table entries: 4096 (order: 3, 32768 bytes, linear)[    0.067130] TCP bind hash table entries: 4096 (order: 5, 131072 bytes, linear)[    0.067134] TCP: Hash tables configured (established 4096 bind 4096)[    0.067162] MPTCP token hash table entries: 512 (order: 2, 12288 bytes, linear)[    0.067168] UDP hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.067170] UDP-Lite hash table entries: 256 (order: 2, 16384 bytes, linear)[    0.067184] NET: Registered PF_UNIX/PF_LOCAL protocol family[    0.067191] NET: Registered PF_XDP protocol family[    0.067195] PCI: CLS 0 bytes, default 64[    0.067266] kvm [1]: HYP mode not available[    0.067333] Initialise system trusted keyrings[    0.067408] workingset: timestamp_bits=44 max_order=17 bucket_order=0[    0.074081] Key type asymmetric registered[    0.074086] Asymmetric key parser 'x509' registered[    0.074114] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 248)[    0.081257] io scheduler mq-deadline registered[    0.081264] io scheduler kyber registered[    0.081276] io scheduler bfq registered[    0.081494] Serial: 8250/16550 driver, 4 ports, IRQ sharing enabled[    0.083112] hv_vmbus: registering driver hyperv_keyboard[    0.083256] rtc-pl031 9010000.pl031: registered as rtc0[    0.083262] rtc-pl031 9010000.pl031: setting system clock to 2026-11-20T08:57:23 UTC (1795165043)[    0.083336] NET: Registered PF_INET6 protocol family[    0.083541] Segment Routing with IPv6[    0.083544] In-situ OAM (IOAM) with IPv6[    0.087444] registered taskstats version 1[    0.087496] Loading compiled-in X.509 certificates[    0.088377] Loaded X.509 cert 'alpinelinux.org: Alpine Linux kernel key: 87fa969a47f3e2a6aa35859eb932a17c95abcd82'[    0.090020] Demotion targets for Node 0: null[    0.090064] Key type .fscrypt registered[    0.090065] Key type fscrypt-provisioning registered[    0.091597] clk: Disabling unused clocks[    0.091603] PM: genpd: Disabling unused power domains[    0.093285] check access for rdinit=/init failed: -2, ignoring[    0.093288] md: Skipping autodetection of RAID arrays. (raid=autodetect will force)[    0.093299] List of all partitions:[    0.093300] No filesystem could mount root, tried: [    0.093301] [    0.093302] Kernel panic - not syncing: VFS: Unable to mount root fs on "" or unknown-block(0,0)[    0.095497] CPU: 0 UID: 0 PID: 1 Comm: swapper/0 Not tainted 6.18.60-0-virt #1-Alpine PREEMPT(none) [    0.096134] Hardware name: macvmm-virt (DT)[    0.096449] Call trace:[    0.096608]  show_stack+0x28/0xbc (C)[    0.096845]  dump_stack_lvl+0x60/0x94[    0.097066]  dump_stack+0x18/0x30[    0.097274]  vpanic+0xf8/0x2e4[    0.097642]  trace_suspend_resume+0x0/0xcc[    0.097851]  mount_root_generic+0x3b0/0x3f0[    0.098071]  mount_root+0x3d4/0x42c[    0.098251]  prepare_namespace+0x4c4/0x56c[    0.098463]  kernel_init_freeable+0x40c/0x468[    0.098686]  kernel_init+0x20/0x160[    0.098877]  ret_from_fork+0x10/0x20[    0.099074] Kernel Offset: disabled[    0.099262] CPU features: 0x000000,00006500,42242281,94267727[    0.099603] Memory Limit: none[    0.099761] ---[ end Kernel panic - not syncing: VFS: Unable to mount root fs on "" or unknown-block(0,0) ]------ stderr ---macvmm: timeout: the guest was still running after --timeout 10s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified, given the same broken-magic copy through --raw, the path that copies bytes to an address and parses nothing (no header checks, no initrd, no command line).
course/captures/13-bad-magic-raw.txt

Surprise: Linux boots. The magic is a promise to the loader; the kernel never checks it. --raw still generates the device tree and puts its address in x0 (chapter 10), hence Machine model: macvmm-virt; it skips only the header checks, the initramfs and the command line.

About 180 lines in, it ends in Kernel panic - not syncing: VFS: Unable to mount root fs, then spins until our timeout (exit 5). No initramfs was passed, so there was no /init; the kernel looked for a root disk, found none, and panicked. The message blames the root file system, far from the cause.

What you saw: with the loader, a refusal before any guest code ran; without it, a misleading panic. The misconception: "a corrupt kernel fails fast on its own". The tool: the loader's checks, and --dry-run to see what the VMM decided before anything runs.

Deliberate breakage 2: put the initramfs inside the kernel's BSS. In your initrd.rs, make place() start the initramfs 4 MiB lower: replace align_up(kernel_end, LINUX_ALIGN) with align_up(kernel_end, LINUX_ALIGN).and_then(|a| a.checked_sub(4 << 20)). Nothing else checks this overlap. The plan, then the boot:

Shell
cargo run -q -p macvmm -- run --dry-run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512Mcargo run -q -p macvmm -- run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 15
TerminalReal output
cargo run -q -p macvmm -- run --dry-run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512Mexit: 0--- stdout ---macvmm boot plan (dry run, no VM created)ram     0x40000000..0x60000000  512 MiBdtb     0x40000000..0x40000724  device tree (1828 bytes)kernel  0x40200000..0x424a0000  kernel (arm64 Image) (36306944 bytes)initrd  0x42200000..0x42afd8fc  initrd (9427196 bytes)header  text_offset=0x0 image_size=0x22a0000 file=0x22a0000 page_size=K4cmdline "console=ttyAMA0 earlycon=pl011,0x09000000"entry   pc=0x40200000 x0=0x40000000 cpsr=0x3c5memory map (Virt):  0x00000000..0x04000000  flash0       Rom  0x04000000..0x08000000  flash1       Rom  0x08000000..0x08010000  gicd         GicDist  0x08010000..0x08020000  gicv2-cpu    Reserved  0x08020000..0x08030000  gic-v2m      GicMsi  0x08080000..0x080a0000  gic-its      Reserved  0x080a0000..0x09000000  gicr         GicRedist  0x09000000..0x09001000  pl011        Mmio intid 33  0x09010000..0x09011000  pl031        Mmio intid 34  0x09020000..0x09020018  fw-cfg       Reserved  0x09030000..0x09031000  pl061        Reserved intid 39  0x0a000000..0x0a004000  virtio-mmio  Mmio  0x0b000000..0x0b001000  testdev      Mmio  0x0c000000..0x0e000000  probe-hole   Reserved  0x10000000..0x3eff0000  pcie-mmio    Reserved  0x3eff0000..0x3f000000  pcie-pio     Reserved  0x3f000000..0x40000000  pcie-ecam    Reserved  0x40000000..0x60000000  ram          Ramdevice tree: 1828 bytes at 0x40000000 (limit 2097152), 1 vCPU(s), irqchip InKernelGicV3, rng-seed 64 bytes and kaslr-seed (values not shown)  /chosen linux,initrd-start 0x42200000 linux,initrd-end 0x42afd8fcdebug hypercalls: off
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: the same one-line edit to place() in crates/vmm/src/loader/initrd.rs (the initrd starts 4 MiB below align_up(kernel_end, 2 MiB)).
  • Run in a copy of the reference with that one edit, using the repository's .cache/macvmm files.
course/captures/13-initrd-in-bss-plan.txt

The kernel ends at 0x424a0000; the initramfs starts at 0x42200000, inside it. Predict the boot: an immediate error, a panic about the archive, or something else?

TerminalReal output
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 15exit: 5--- stdout ---[    0.000000] Booting Linux on physical CPU 0x0000000000 [0x610f0000][    0.000000] Linux version 6.18.60-0-virt (buildozer@build-3-24-aarch64) (cc (Alpine 15.2.0) 15.2.0, GNU ld (GNU Binutils) 2.45.1) #1-Alpine SMP PREEMPT_DYNAMIC 2026-11-01 07:26:31[    0.000000] random: crng init done[    0.000000] Machine model: macvmm-virt[    0.000000] earlycon: pl11 at MMIO 0x0000000009000000 (options '')[    0.000000] printk: legacy bootconsole [pl11] enabled[    0.000000] efi: UEFI not found.[    0.000000] OF: reserved mem: Reserved memory: No reserved-memory node in the DT[    0.000000] NUMA: Faking a node at [mem 0x0000000040000000-0x000000005fffffff][    0.000000] NODE_DATA(0) allocated [mem 0x5fd03780-0x5fd05c3f][    0.000000] Zone ranges:[    0.000000]   DMA      [mem 0x0000000040000000-0x000000005fffffff][    0.000000]   DMA32    empty[    0.000000]   Normal   empty[    0.000000] Movable zone start for each node[    0.000000] Early memory node ranges[    0.000000]   node   0: [mem 0x0000000040000000-0x000000005fffffff][    0.000000] Initmem setup node 0 [mem 0x0000000040000000-0x000000005fffffff][    0.000000] psci: probing for conduit method from DT.[    0.000000] psci: PSCIv1.1 detected in firmware.[    0.000000] psci: Using standard PSCI v0.2 function IDs[    0.000000] psci: Trusted OS migration not required[    0.000000] psci: SMC Calling Convention v1.1[    0.000000] percpu: Embedded 34 pages/cpu s99608 r8192 d31464 u139264[    0.000000] Detected PIPT I-cache on CPU0[    0.000000] CPU features: detected: Address authentication (IMP DEF algorithm)[    0.000000] CPU features: detected: GICv3 CPU interface[    0.000000] CPU features: detected: Spectre-v4[    0.000000] CPU features: detected: Spectre-BHB[    0.000000] alternatives: applying boot alternatives[    0.000000] Kernel command line: console=ttyAMA0 earlycon=pl011,0x09000000[    0.000000] printk: log buffer data + meta data: 131072 + 458752 = 589824 bytes[    0.000000] Dentry cache hash table entries: 65536 (order: 7, 524288 bytes, linear)[    0.000000] Inode-cache hash table entries: 32768 (order: 6, 262144 bytes, linear)[    0.000000] software IO TLB: SWIOTLB bounce buffer size adjusted to 0MB[    0.000000] software IO TLB: area num 1.[    0.000000] software IO TLB: mapped [mem 0x000000005f380000-0x000000005f400000] (0MB)[    0.000000] Fallback order for Node 0: 0 [    0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 131072[    0.000000] Policy zone: DMA[    0.000000] mem auto-init: stack:all(zero), heap alloc:on, heap free:off[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1[    0.000000] Dynamic Preempt: none[    0.000000] rcu: Preemptible hierarchical RCU implementation.[    0.000000] rcu: 	RCU restricting CPUs from NR_CPUS=4096 to nr_cpu_ids=1.[    0.000000] 	Trampoline variant of Tasks RCU enabled.[    0.000000] 	Tracing variant of Tasks RCU enabled.[    0.000000] rcu: RCU calculated value of scheduler-enlistment delay is 100 jiffies.[    0.000000] rcu: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1[    0.000000] RCU Tasks: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] RCU Tasks Trace: Setting shift to 0 and lim to 1 rcu_task_cb_adjust=1 rcu_task_cpu_ids=1.[    0.000000] NR_IRQS: 64, nr_irqs: 64, preallocated irqs: 0[    0.000000] GICv3: 988 SPIs implemented[    0.000000] GICv3: 0 Extended SPIs implemented[    0.000000] Root IRQ handler: gic_handle_irq[    0.000000] GICv3: GICv3 features: 16 PPIs, RSS[    0.000000] GICv3: GICD_CTLR.DS=1, SCR_EL3.FIQ=0[    0.000000] GICv3: CPU0: found redistributor 0 region 0:0x00000000080a0000[    0.000000] rcu: srcu_init: Setting srcu_struct sizes based on contention.[    0.000000] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 1911260446275000 ns[    0.000000] arch_timer: cp15 timer running at 24.00MHz (virt).[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x588fe9dc0, max_idle_ns: 440795202592 ns[    0.000000] sched_clock: 56 bits at 24MHz, resolution 41ns, wraps every 4398046511097ns[    0.000832] kfence: initialized - using 2097152 bytes for 255 objects at 0x(____ptrval____)-0x(____ptrval____)[    0.001633] Console: colour dummy device 80x25[    0.001981] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=24000)[    0.002825] pid_max: default: 32768 minimum: 301[    0.003186] LSM: initializing lsm=lockdown,capability,landlock,yama[    0.003735] landlock: Up and running.[    0.003989] Yama: becoming mindful.[    0.004272] Mount-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.004820] Mountpoint-cache hash table entries: 1024 (order: 1, 8192 bytes, linear)[    0.005746] rcu: Hierarchical SRCU implementation.[    0.006091] rcu: 	Max phase no-delay instances is 400.[    0.006557] EFI services will not be available.[    0.006906] smp: Bringing up secondary CPUs ...[    0.007303] smp: Brought up 1 node, 1 CPU[    0.007650] SMP: Total of 1 processors activated.[    0.008054] CPU: All CPU(s) started at EL1[    0.008461] CPU features: detected: Branch Target Identification[    0.009009] CPU features: detected: ARMv8.4 Translation Table Level[    0.009557] CPU features: detected: Data cache clean to the PoU not required for I/D coherence[    0.010231] CPU features: detected: Common not Private translations[    0.010662] CPU features: detected: CRC32 instructions[    0.011049] CPU features: detected: Data independent timing control (DIT)[    0.011595] CPU features: detected: E0PD[    0.011874] CPU features: detected: Enhanced Privileged Access Never[    0.012298] CPU features: detected: Generic authentication (IMP DEF algorithm)[    0.012844] CPU features: detected: RCpc load-acquire (LDAPR)[    0.013244] CPU features: detected: LSE atomic instructions[    0.013651] CPU features: detected: Privileged Access Never[    0.014049] CPU features: detected: RAS Extension Support[    0.014429] CPU features: detected: Speculation barrier (SB)[    0.014822] CPU features: detected: TLB range maintenance instructions[    0.015260] CPU features: detected: Scalable Matrix Extension[    0.015689] CPU features: detected: SME2[    0.016037] alternatives: applying system-wide alternatives[    0.017222] SME: minimum available vector length 64 bytes per vector[    0.017663] SME: maximum available vector length 64 bytes per vector[    0.018101] SME: default vector length 64 bytes per vector[    0.018503] Memory: 466784K/524288K available (13312K kernel code, 1994K rwdata, 8460K rodata, 2048K init, 9282K bss, 55028K reserved, 0K cma-reserved)[    0.019620] devtmpfs: initialized[    0.020162] posixtimers hash table entries: 512 (order: 1, 8192 bytes, linear)[    0.020680] futex hash table entries: 256 (16384 bytes on 1 NUMA nodes, total 16 KiB, linear).[    0.021341] 23904 pages in range for non-PLT usage[    0.021342] 515424 pages in range for PLT usage[    0.021723] pinctrl core: initialized pinctrl subsystem[    0.022494] DMI not present or invalid.[    0.023545] NET: Registered PF_NETLINK/PF_ROUTE protocol family[    0.024067] DMA: preallocated 128 KiB GFP_KERNEL pool for atomic allocations[    0.024607] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA pool for atomic allocations[    0.025219] DMA: preallocated 128 KiB GFP_KERNEL|GFP_DMA32 pool for atomic allocations[    0.025810] audit: initializing netlink subsys (disabled)[    0.026379] thermal_sys: Registered thermal governor 'step_wise'[    0.026388] audit: type=2000 audit(0.021:1): state=initialized audit_enabled=0 res=1[    0.027397] cpuidle: using governor ladder[    0.027705] cpuidle: using governor menu[    0.028009] hw-breakpoint: found 6 breakpoint and 4 watchpoint registers.[    0.028515] ASID allocator initialised with 65536 entries[    0.028974] Serial: AMBA PL011 UART driver[    0.029412] 9000000.pl011: ttyAMA0 at MMIO 0x9000000 (irq = 13, base_baud = 0) is a PL011 rev1[    0.030061] printk: console [ttyAMA0] enabled[    0.030061] printk: console [ttyAMA0] enabled[    0.030575] printk: legacy bootconsole [pl11] disabled[    0.030575] printk: legacy bootconsole [pl11] disabled[    0.032254] HugeTLB: registered 1.00 GiB page size, pre-allocated 0 pages[    0.032256] HugeTLB: 0 KiB vmemmap can be freed for a 1.00 GiB page[    0.032256] HugeTLB: registered 32.0 MiB page size, pre-allocated 0 pages[    0.032257] HugeTLB: 0 KiB vmemmap can be freed for a 32.0 MiB page[    0.032257] HugeTLB: registered 2.00 MiB page size, pre-allocated 0 pages[    0.032257] HugeTLB: 0 KiB vmemmap can be freed for a 2.00 MiB page[    0.032257] HugeTLB: registered 64.0 KiB page size, pre-allocated 0 pages[    0.032257] HugeTLB: 0 KiB vmemmap can be freed for a 64.0 KiB page[    0.032402] ACPI: Interpreter disabled.[    0.032407] iommu: Default domain type: Translated[    0.032408] iommu: DMA domain TLB invalidation policy: lazy mode[    0.032547] clocksource: Switched to clocksource arch_sys_counter[    0.041349] VFS: Disk quotas dquot_6.6.0[    0.041354] VFS: Dquot-cache hash table entries: 512 (order 0, 4096 bytes)[    0.042388] pnp: PnP ACPI: disabled[    0.042876] NET: Registered PF_INET protocol family[    0.042900] IP idents hash table entries: 8192 (order: 4, 65536 bytes, linear)--- stderr ---macvmm: timeout: the guest was still running after --timeout 15s
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: in crates/vmm/src/loader/initrd.rs, place() starts the initrd 4 MiB below align_up(kernel_end, 2 MiB), at 0x42200000, inside the kernel's image_size span (one-line edit, no other change).
  • Run in a copy of the reference with that one edit, using the repository's .cache/macvmm files.
course/captures/13-initrd-in-bss.txt

About 140 lines in, the boot stops after IP idents hash table entries, with no error, until our timeout (exit 5). Early in boot the kernel clears the end of its image_size span for its BSS and early page tables, and the first 2.6 MiB of the initramfs sat there. We have not traced which later step stalls; another overlap would change the last line.

What you saw: a silent stop whose last printed line comes from networking code, nothing to do with the cause. The misconception: "loading means copying the file to RAM; the file's size is the kernel's footprint". The tool: the boot plan's tests. Copy the checkpoint's boot-plan test into your workspace and run it, with the edit still in place (the next section opens this file):

Shell
mkdir -p crates/vmm/testscp ../course/checkpoints/13/contract/bootplan.rs crates/vmm/tests/cargo test -q -p vmm --test bootplan
TerminalReal output
cargo test -q -p vmm --test bootplanexit: 101--- stdout ---running 4 testsone_gib_window_rule --- FAILEDproperty_no_overlap_nothing_outside_ram --- FAILEDinitrd_too_large_for_ram --- FAILEDalpine_numbers --- FAILEDfailures:---- one_gib_window_rule stdout ----thread 'one_gib_window_rule' (121125805) panicked at crates/vmm/tests/bootplan.rs:111:5:assertion `left == right` failed  left: Ok((1109393408, 35429285888)) right: Ok((1113587712, 35433480192))note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace---- property_no_overlap_nothing_outside_ram stdout ----thread 'property_no_overlap_nothing_outside_ram' (121125806) panicked at crates/vmm/tests/bootplan.rs:231:9:seed 7881690183168229385 iter 0: ram 0x4000000 text_offset 0x0 image_size 0x1614e67 file 312 initrd 0xaf---- initrd_too_large_for_ram stdout ----thread 'initrd_too_large_for_ram' (121125804) panicked at crates/vmm/tests/bootplan.rs:93:9:assertion `left == right` failed: 0x1a00001: Ok(BootPlan { entry: 1075838976, cpsr: 965, x0: 1073741824, ram: RamRange { base: 1073741824, size: 67108864 }, dtb: Placement { what: "device tree (reserved)", addr: 1073741824, len: 524288 }, dtb_limit: 2097152, images: [Placement { what: "kernel (arm64 Image)", addr: 1075838976, len: 36306944 }, Placement { what: "initrd", addr: 1109393408, len: 27262977 }], elf: None, image: Some(ArmImage { header: ImageHeader { text_offset: 0, image_size: 36306944, flags: 10, page_size: K4, phys_anywhere: true }, load: 1075838976, end: 1112145920, file_len: 64 }), initrd: Some((1109393408, 1136656385)), bootargs: Some("console=ttyAMA0 earlycon=pl011,0x09000000"), firmware: None })  left: true right: false---- alpine_numbers stdout ----thread 'alpine_numbers' (121125803) panicked at crates/vmm/tests/bootplan.rs:46:5:assertion `left == right` failed  left: Some((1109393408, 1118393408)) right: Some((1113587712, 1122587712))failures:    alpine_numbers    initrd_too_large_for_ram    one_gib_window_rule    property_no_overlap_nothing_outside_ramtest result: FAILED. 0 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s--- stderr ---error: test failed, to rerun pass `-p vmm --test bootplan`
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • Deliberate breakage: the same one-line edit to place() in crates/vmm/src/loader/initrd.rs (the initrd starts 4 MiB below align_up(kernel_end, 2 MiB)).
  • Run in a copy of the reference with that one edit; only the boot-plan suite.
course/captures/13-initrd-in-bss-test.txt

All four tests fail at once. Undo the edit before you go on.

Ten thousand plans

The test alpine_numbers in your copy, crates/vmm/tests/bootplan.rs, pins the plan for one kernel: your dry run's numbers. The property test asks more: for 10,000 combinations of RAM size, text_offset, image_size, file length and initramfs size, does every plan the code accepts keep everything in RAM, disjoint, aligned and inside the window? Its heart:

crates/vmm/tests/bootplan.rslines 219-240
accepted += 1;let ilen = iend - istart;let dtb = (RAM_BASE, DTB_MAX);let kernel = (img.load, img.header.image_size);assert!(r.contains(dtb.0, dtb.1.min(ram_size)), "{}", ctx());assert!(    r.contains(kernel.0, kernel.1),    "kernel outside RAM: {}",    ctx());assert!(r.contains(istart, ilen), "initrd outside RAM: {}", ctx());assert!(!overlaps(dtb.0, dtb.1, kernel.0, kernel.1), "{}", ctx());assert!(!overlaps(dtb.0, dtb.1, istart, ilen), "{}", ctx());assert!(!overlaps(kernel.0, kernel.1, istart, ilen), "{}", ctx());assert_eq!(istart % RAM_ALIGN, 0, "{}", ctx());assert!(    initrd::check_window(kernel.0, img.end, istart, iend).is_ok(),    "{}",    ctx());assert_eq!(p.entry, img.load);assert!(p.dtb_limit <= DTB_MAX && p.dtb_limit > 0);

Aside

This is property-based testing: a generator produces many inputs and the test checks a rule that must hold for all of them. Ours uses a seeded pseudo-random generator (a small xorshift, no extra crate), so a failure prints its seed; the broken run above printed seed 7881690183168229385 iter 0. Tools such as proptest also shrink a failure to a minimal case. An introduction: "What is property-based testing?" from the Hypothesis project.

To replay that exact failure, set the seed:

Shell
MACVMM_SEED=7881690183168229385 cargo test -q -p vmm --test bootplan

The ELF loader: a spec exercise

Our test guests are ELF files, so far fed to the VMM as flat binaries. An ELF file says where every byte goes and where execution starts. You write this loader from the specification, with no code shown first: the System V Application Binary Interface (ABI), whose generic part (the gABI) has the ELF Header and Program Header chapters; the elf primer walks both. The rules, each one a test in the checkpoint's course/checkpoints/13/contract/elf_hostile.rs:

  1. e_ident: the magic \x7fELF, ELFCLASS64, little-endian data, version 1; then e_type = ET_EXEC, e_machine = 183 (AArch64), e_version = 1.
  2. e_phentsize = 56, e_phnum at most 64, and e_phoff + e_phnum * 56 inside the file, with checked_mul and checked_add.
  3. For each PT_LOAD: p_filesz <= p_memsz; [p_offset, p_offset + p_filesz) inside the file; p_vaddr == p_paddr (the MMU is off, so the address the code runs at is the physical address); [p_paddr, p_paddr + p_memsz), computed with checked_add, inside RAM; at or above RAM base + 512 KiB, clear of the device-tree slot plan() reserved first; and disjoint from every other segment.
  4. e_entry inside a segment marked executable.
  5. Ignore section headers: a loader does not need them, and every field you do not read is a field nobody can attack.
  6. Load by copying p_filesz bytes and zeroing the rest up to p_memsz, through the guest-memory API, in fixed-size chunks, so p_memsz never sizes a host buffer.

The test guests start at 0x4008_0000, right above the slot. Write learner/crates/vmm/src/loader/elf.rs now, from these rules, and replace the stand-in ImageKind::Elf arm of plan() with one that calls it. Then run chapter 03's guest from its ELF file:

Shell
cargo run -q -p macvmm -- run --dry-run --mem 64M --kernel ../target/guests/aarch64-unknown-none/release/hellocargo run -q -p macvmm -- run --mem 64M --kernel ../target/guests/aarch64-unknown-none/release/hello --timeout 10
TerminalReal output
cargo run -q -p macvmm -- run --dry-run --mem 64M --kernel target/guests/aarch64-unknown-none/release/helloexit: 0--- stdout ---macvmm boot plan (dry run, no VM created)ram     0x40000000..0x44000000  64 MiBdtb     0x40000000..0x40000697  device tree (1687 bytes)elf     0x40080000..0x40082a28  ELF segment 0 (10792 bytes)elf     0x40082a30..0x40082d9a  ELF segment 1 (874 bytes)elf     0x40082da0..0x40102dc0  ELF segment 2 (524320 bytes)entry   pc=0x40080000 x0=0x40000000 cpsr=0x3c5memory map (Virt):  0x00000000..0x04000000  flash0       Rom  0x04000000..0x08000000  flash1       Rom  0x08000000..0x08010000  gicd         GicDist  0x08010000..0x08020000  gicv2-cpu    Reserved  0x08020000..0x08030000  gic-v2m      GicMsi  0x08080000..0x080a0000  gic-its      Reserved  0x080a0000..0x09000000  gicr         GicRedist  0x09000000..0x09001000  pl011        Mmio intid 33  0x09010000..0x09011000  pl031        Mmio intid 34  0x09020000..0x09020018  fw-cfg       Reserved  0x09030000..0x09031000  pl061        Reserved intid 39  0x0a000000..0x0a004000  virtio-mmio  Mmio  0x0b000000..0x0b001000  testdev      Mmio  0x0c000000..0x0e000000  probe-hole   Reserved  0x10000000..0x3eff0000  pcie-mmio    Reserved  0x3eff0000..0x3f000000  pcie-pio     Reserved  0x3f000000..0x40000000  pcie-ecam    Reserved  0x40000000..0x44000000  ram          Ramdevice tree: 1687 bytes at 0x40000000 (limit 524288), 1 vCPU(s), irqchip InKernelGicV3, rng-seed 64 bytes and kaslr-seed (values not shown)debug hypercalls: on
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: the plan for chapter 03's hello guest as an ELF file.
course/captures/13-hello-elf-plan.txt
TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/hello --timeout 10exit: 0--- stdout ---hello from guest, x0=0x40000000guest done
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified: chapter 03's hello guest, given as its ELF file instead of the flat binary.
course/captures/13-hello-elf.txt

Segment 2 occupies 0x80020 bytes of RAM. How many come from the file? objdump (Xcode's command-line tools) prints the program headers:

Shell
objdump -p ../target/guests/aarch64-unknown-none/release/hello
TerminalReal output
objdump -p target/guests/aarch64-unknown-none/release/helloexit: 0--- stdout ---target/guests/aarch64-unknown-none/release/hello:	file format elf64-littleaarch64Program Header:    LOAD off    0x0000000000010000 vaddr 0x0000000040080000 paddr 0x0000000040080000 align 2**16         filesz 0x0000000000002a28 memsz 0x0000000000002a28 flags r-x    LOAD off    0x0000000000012a30 vaddr 0x0000000040082a30 paddr 0x0000000040082a30 align 2**16         filesz 0x000000000000036a memsz 0x000000000000036a flags r--    LOAD off    0x0000000000012da0 vaddr 0x0000000040082da0 paddr 0x0000000040082da0 align 2**16         filesz 0x0000000000000000 memsz 0x0000000000080020 flags rw-   STACK off    0x0000000000000000 vaddr 0x0000000000000000 paddr 0x0000000000000000 align 2**64         filesz 0x0000000000000000 memsz 0x0000000000000000 flags rw-Dynamic Section:
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The hello guest's program headers, read with the objdump that ships with Xcode's command-line tools (it is LLVM's).
course/captures/13-hello-phdrs.txt

The third LOAD has filesz 0: the guest's BSS and stack, which only p_memsz describes. The lesson of image_size again.

Try it

Set e_phnum (two bytes at 0x38) of a hello copy to ff ff, then run it. Which rule fires first? A loader that loops before checking that the table fits reads far past the file's end.

Shell
cp ../target/guests/aarch64-unknown-none/release/hello ../.cache/ch13/hello-phnumprintf '\377\377' | dd of=../.cache/ch13/hello-phnum bs=1 seek=56 conv=notrunccargo run -q -p macvmm -- run --mem 64M --kernel ../.cache/ch13/hello-phnum --timeout 10

Check your guess:

TerminalReal output
cargo run -q -p macvmm -- run --mem 64M --kernel .cache/ch13/hello-phnum --timeout 10exit: 2--- stderr ---macvmm: cannot load the guest: ELF has 65535 program headers (at most 64)
captured: real output, Apple M5 Pro, macOS 27.2.1, commit dad6c99, 2026-11-20
  • The reference, unmodified. The kernel is a copy of the hello ELF with e_phnum (2 bytes at offset 0x38) set to ff ff, 65535; the copy lived in a private scratch directory, shown as .cache/ch13.
course/captures/13-elf-phnum.txt
Lab

ELF inspector

Decode an ELF file's header and program headers byte by byte, see what a loader copies into guest RAM, and find which check catches a broken byte.

Runs in browserOpen full page: ELF inspector
ELF inspector: the hello guest from the elf primer The 844,736-byte file holds the ELF header and four program headers in its first 0x120 bytes. Segment 0 (read, execute) copies 0x29f0 bytes from file offset 0x10000 to 0x4008_0000. Segment 1 (read) copies 0x36a bytes from 0x129f0 to 0x4008_29f0. Segment 2 (read, write) takes no bytes from the file and is 0x80020 bytes of zeros at 0x4008_2d60. The rest of the file, debug information, symbols and section headers, is not loaded. The device-tree slot fills 0x4000_0000 to 0x4008_0000. All checks pass; the guest spans 535,936 bytes of RAM, and the flat binary is 11,610 bytes. file (844,736 bytes) guest RAM 0x0 headers (not copied) 0x10000 code 0x29f0 0x129f0 rodata 0x36a 0x12d5a debug info, symbols, section headers (not loaded) 0x4000_0000 device-tree slot 0x4008_0000 code R X 0x4008_29f0 rodata R 0x4008_2d60 BSS RW 0x80020 bytes zero-filled, none of them in the file copy copy zero All checks pass. Entry 0x4008_0000 is in segment 0 (executable). Three sizes: file 844,736 · flat binary 11,610 · guest RAM 535,936 bytes. Patch e_phnum (offset 0x38) to ff ff: "ELF has 65535 program headers (at most 64)".

Your turn

Check your learner/ against the list and finish what is missing:

  1. arch/layout.rs: the seven constants shown.
  2. loader/mod.rs: ImageKind, detect, and the LoaderError variants below, each with a one-line message, plus a Memory(MemoryError) variant and From<MemoryError> for LoaderError, so that ? works on guest-memory writes. RamRange and overlaps are chapter 03's, unchanged.
  3. loader/image.rs: parse_header, place and load as shown, with TEXT_OFFSET_ALIGN (4096), the flag bits from the table, and the types PageSize, ImageHeader and ArmImage (whose placement() is the kernel's plan row). Two helpers the code above uses: fn le64(b: &[u8], off: usize) -> Option<u64> reads the little-endian u64 at off, or returns None when the slice is too short (compute the end with checked_add); and placement() returns plan.rs's pub struct Placement { pub what: String, pub addr: u64, pub len: u64 }, with what set to "kernel (arm64 Image)", addr to the load address and len to image_size.
  4. loader/initrd.rs: align_up, place and check_window.
  5. loader/plan.rs: BootPlan and plan(): the 512 KiB device-tree slot first, then the ELF arm, the Image arm as shown, --initrd and --cmdline refused for anything but an Image, and dtb_limit last, as shown. Its printed lines must match the --dry-run capture exactly, from dtb 0x40000000 to entry pc=… x0=… cpsr=0x3c5.
  6. loader/elf.rs: from the rules, then compare with the reference.
  7. fdt/machine.rs: /chosen gains bootargs, linux,initrd-start and linux,initrd-end.
  8. machine/mod.rs: BootParams { pc, x: [x0, 0, 0, 0], cpsr } from the plan.
  9. crates/macvmm/src/cli.rs: --kernel (ELF or Image, decided by detect), --initrd, --cmdline and --dry-run, as in "Wire it to the command line", with the ELF arm now real.

The error variants, with the cases the checkpoint's tests build:

crates/vmm/src/loader/mod.rslines 105-164
/// Why a boot input cannot be loaded. Each is a configuration error (exit code 2).#[derive(Clone, Debug, PartialEq, Eq)]pub enum LoaderError {    /// The Image is shorter than its 64-byte header.    ImageTooShort { len: u64 },    /// The Image magic `ARM\x64` is missing at offset 56.    ImageBadMagic,    /// `flags` bit 0: a big-endian kernel.    ImageBigEndian,    /// `flags` bits 1–2 = 3 (64 KiB pages), which Apple Silicon does not implement.    ImagePageSize { field: u64 },    /// `image_size == 0`: a kernel older than 3.17.    ImageZeroSize,    /// `text_offset` is not 4 KiB-aligned.    ImageTextOffset { text_offset: u64 },    /// The file is longer than the `image_size` it declares.    ImageFileTooLong { file_len: u64, image_size: u64 },    /// `--initrd` was given with an empty file.    InitrdEmpty,    /// The initrd and the kernel do not fit one 1 GiB-aligned 32 GiB window (booting.rst section 4).    InitrdWindow { start: u64, end: u64 },    /// `--initrd` or `--cmdline` without an arm64 Image `--kernel` (they are Linux only).    LinuxOnly { what: &'static str },    /// The kernel command line is longer than [`plan::MAX_CMDLINE`] bytes or contains NUL.    BadCmdline { len: usize },    /// `--kernel` is an EFI zboot wrapper.    EfiZboot,    /// `--kernel` is neither ELF nor Image.    NotAKernel,    /// The ELF file is shorter than the structure being read.    ElfTruncated { what: &'static str },    /// An `e_ident` or header field has a value we do not load (class, data, version, type,    /// machine, `e_phentsize`).    ElfUnsupported { field: &'static str, value: u64 },    /// `e_phnum` is above [`elf::MAX_PHNUM`].    ElfTooManyPhdrs { phnum: u16 },    /// The program-header table does not fit in the file.    ElfPhdrsOutOfFile,    /// Segment `index`'s file bytes lie outside the file.    ElfSegmentOutOfFile { index: usize },    /// Segment `index` has `p_filesz > p_memsz`.    ElfFileszGtMemsz { index: usize },    /// Segment `index` has `p_vaddr != p_paddr` (the MMU is off at entry: VA = PA).    ElfVaddrNotPaddr { index: usize },    /// No `PT_LOAD` segment with bytes in it.    ElfNoSegments,    /// `e_entry` is not inside an executable `PT_LOAD`.    ElfEntryNotExecutable { entry: u64 },    /// An image (segment, raw blob) is not entirely inside RAM.    OutsideRam { what: String, addr: u64, len: u64 },    /// Two images overlap.    Overlap { a: String, b: String },    /// An image overlaps the DTB slot at the start of RAM.    OverlapsDtb { what: String },    /// The device tree does not fit its slot: `len` is 0, above `limit` (the least of 2 MiB,    /// the RAM size and the space below the lowest image), or not the size the slot was    /// planned for.    DtbTooLarge { len: u64, limit: u64 },    /// Nothing to boot.    NoImage,

Then rerun every learner/ command on this page and compare with the captures; with your ELF loader in place, the memtest run works too (--mem 64M --kernel ../target/guests/aarch64-unknown-none/release/memtest --timeout 10). Answer journal question 2 right after the second break.

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

Checkpoint

Back at the repository root, run:

Checkpoint

Needs a Mac

Run this from the repository root:

scripts/checkpoint.sh 13

You should see, as the last line:

CHECKPOINT 13 PASS

It runs the contract tests (hostile Image and ELF files, the boot plan and its property test), then three runs on your Mac: hello from its ELF file, the Alpine dry run from an unentitled binary, and the vmlinuz-virt refusal, then checks your journal. On our Mac, against the reference:

TerminalReal output
scripts/checkpoint.sh 13exit: 0--- stdout ---checkpoint: implementation <tree>[PASS] contract tests   image_hostile (18 tests), elf_hostile (25 tests), bootplan (4 tests)[PASS] runs on your Mac hello-elf: 2/2 serial markers, exit 0 in 0.07s[PASS] runs on your Mac dry-run: 4/4 serial markers, exit 0 in 0.05s[PASS] runs on your Mac zboot: 1/1 serial markers, exit 2 in 0.01s[INFO] journal          not checked (not a learner tree)CHECKPOINT 13 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 13 --impl <tree>): what a finished chapter 13 looks like.
  • The journal line reports "not a learner tree" here; in your own learner/ workspace it checks your journal.
course/captures/13-checkpoint.txt

The contract line is the contract tests, run the runs on your Mac, journal the journal check.

What now works:

  • your VMM parses an arm64 Image header, refusing hostile fields and zboot wrappers by name;
  • it plans and prints the boot without a VM, and survives 10,000 generated cases;
  • it starts a kernel in the protocol's entry state, with the initramfs in /chosen;
  • it loads ELF files by their program headers.

The next chapter starts from this state (the reference at the end of chapter 13, tag ch-13).

What's next

Chapter 14 boots Alpine to a shell, then breaks the machine three ways and diagnoses each break from the outside.

Open question

The ELF rules say p_filesz <= p_memsz. A program header says p_filesz = 4096 and p_memsz = 2^40, which passes that rule. What is the loader's rule for this header, and which two numbers do you compare p_memsz with before you zero anything?

Spec hunt

  • Linux Documentation/arch/arm64/booting.rst, section 4, "Call the kernel image": when header flag bit 3 is 0, what does the document say about memory below the kernel's base address, and why (look for the linear mapping)?
  • The System V gABI, the "Program Header" chapter, the entries for p_filesz and p_memsz: what must the loader put in the bytes between them, and what does the specification say if p_filesz is larger?
  • Linux drivers/of/fdt.c, the function early_init_dt_check_for_initrd: what does the kernel do if linux,initrd-start or linux,initrd-end is missing, or if start is above end?
Progress is stored only in this browser.