Chapter 13 · Part VI
Loading kernels: arm64 Image, initramfs and ELF
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.
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.
From chapter 12: Why an interrupt controller, and why in the kernel
The
/timernode lists<1 11 4>for the virtual timer. Which INTID is that, and why is it not an SPI?Show answer
INTID 27. The first cell 1 means PPI (private peripheral interrupt), and PPI n is INTID 16 + n. Each CPU has its own timer, so its interrupt is private to that CPU and lives in that CPU's redistributor, not in the shared distributor.
From chapter 12: Why an interrupt controller, and why in the kernel
An interrupt handler reads
ICC_IAR1_EL1and gets 1023. What happened, and should it writeICC_EOIR1_EL1?Show answer
1023 is the spurious INTID: nothing was pending by the time the CPU asked (another CPU took it, or the line dropped). There is nothing to handle and nothing was made active, so the handler returns without an end-of-interrupt write.
From chapter 12: Why an interrupt controller, and why in the kernel
Your VMM calls
hv_gic_createright after creating vCPU 0. What comes back, and where must the call go instead?Show answer
An error,
HV_BUSYon our Mac (beforehv_vm_createit isHV_NO_DEVICE). The GIC must be created after the VM and before any vCPU, because each vCPU gets its own redistributor and CPU-interface state when it is created.From chapter 12: Why an interrupt controller, and why in the kernel
A UART model raises its level line when a byte arrives but never lowers it. The guest's handler reads the byte and writes EOI. What does the guest see next?
Show answer
The same interrupt again, at once, forever: at EOI the GIC sees the line still high and makes it pending again. The guest makes no progress (an interrupt storm). The device must lower the line when the cause is gone: the FIFO drained, the cause cleared in
ICR, or the source masked inIMSC.From chapter 12: Why an interrupt controller, and why in the kernel
GicSpi::newis asked to wire INTID 27 to a device. What does it answer, and why is refusing at machine build time better than lettinghv_gic_set_spifail later?Show answer
It refuses with
NotAnSpi: 27 is a PPI (the virtual timer), outside the SPI range 32..1020. Refusing at build time turns a wiring bug into a start-up error with a message; a later failure would happen on a path the guest triggers (every UART access) and could only be logged and ignored.From chapter 12: Why an interrupt controller, and why in the kernel
A 2-vCPU machine puts its redistributors at
0x080A_0000. How much space must the GIC node's secondregentry cover, and where does vCPU 1's redistributor start?Show answer
Two frames of 128 KiB (
0x2_0000), so0x4_0000bytes. The second frame starts at0x080C_0000; the frames follow the order in which the vCPUs were created, so the guest finds its own by reading each frame's affinity.From chapter 12: Why an interrupt controller, and why in the kernel
The chapter 11 timer guest made 10 VTIMER and 10 WFI exits for ten 100 ms sleeps. How many of each does the same workload make with the in-kernel GIC, and why?
Show answer
Zero of each. The kernel delivers the virtual timer's interrupt through its own GIC and handles WFI by parking the vCPU until an interrupt is pending, so neither event needs our VMM. What remains are the exits our devices cause, such as UART register accesses.
From chapter 12: Why an interrupt controller, and why in the kernel
A key arrives while the guest's only vCPU sleeps in WFI under the in-kernel GIC. Which thread raises the interrupt, and what does it call?
Show answer
The stdin reader thread: it pushes the byte into the UART model, which recomputes its level and calls
hv_gic_set_spi(33, true)through itsIrqLine. That call works from any thread and wakes the vCPU inside the kernel; no kick and no VM exit is needed.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'sregdescribes two ranges. How many bytes long is theregproperty?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.
From chapter 10: The Device Tree: the VMM's promise to the guest
The first eight bytes of a blob are
d0 0d fe ed 00 00 04 f7. What is it, and how big is it?Show answer
A flattened device tree:
0xd00dfeedis its magic number. The next big-endian 32-bit word istotalsize,0x4f7= 1271 bytes. Read little-endian, the same bytes would give0xf7040000, which is why the byte order matters.From chapter 10: The Device Tree: the VMM's promise to the guest
Why can an arm64 kernel not find the PL011 by reading every address in the first 4 GiB and looking for a UART?
Show answer
Nothing on that bus answers "who is here?", and an address with no device behind it does not return a polite "nothing" either: on real hardware it can fault or hang, and in our VMM it is an unhandled access that stops the guest (exit code 3 by default). Even the PrimeCell ID registers help only once you know where the device is. So somebody has to tell the kernel: the DTB.
From chapter 10: The Device Tree: the VMM's promise to the guest
Two nodes each have a
compatibleproperty. How many times does the wordcompatibleappear in the blob, and where?Show answer
Once, in the strings block: property names are stored there once and referred to by offset (
nameoff). The values ("arm,pl011","arm,pl031") are not names; they sit in the structure block after eachFDT_PROPtoken.From chapter 10: The Device Tree: the VMM's promise to the guest
Your writer opens
/cpus, openscpu@0, closes it, and then adds#size-cellsto/cpus. What should happen, and why?Show answer
An error. The format requires every property of a node to come before its first child node, because a reader walks the token stream once and attaches each property to the node it is in. The reference writer refuses it as
PropAfterChildinstead of writing a tree a kernel would misread.From chapter 10: The Device Tree: the VMM's promise to the guest
A guest's first instruction runs with
x0 = 0x40000000. What does an arm64 kernel expect to find there, and what two rules does the address obey?Show answer
The device tree blob: Linux's boot protocol says
x0holds its physical address. It must be 8-byte aligned and the blob at most 2 MiB long, in RAM. Our VMM puts it at the start of RAM.From chapter 10: The Device Tree: the VMM's promise to the guest
You add a node
pl031@9050000to the DTB but no device to the bus. Linux boots. With the default unhandled-access policy, what doesmacvmmprint, and why at that address?Show answer
unhandled MMIO read at 0x9050fe0, then exit code 3. The AMBA bus code reads a PrimeCell's ID registers, at offsets0xFE0to0xFFC, before it picks a driver, so the first access to the phantom device is the ID read. With--unhandled-mmio logthe reads return zero and the device is left unbound ("deferred probe pending").From chapter 10: The Device Tree: the VMM's promise to the guest
A node says
compatible = "arm,pl011", "arm,primecell". Why two strings, and in which order are they tried?Show answer
Most specific first. A kernel looks for a driver that knows
arm,pl011; the second string says what family the device belongs to (an Arm PrimeCell, with ID registers), which a more general driver or bus can use.From chapter 10: The Device Tree: the VMM's promise to the guest
/cpussays#address-cells = <1>and#size-cells = <0>. How long iscpu@0'sreg, and what does it hold?Show answer
4 bytes: one address cell and no size. It holds the CPU's identity (its MPIDR affinity, here 0), which is why the node is called
cpu@0.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 is1 << 2 = 0x4. The stack-pointer select bit 0 set meansSP_EL1:0x1. Together0x3c5, the mode EL1h.From chapter 06: vCPU state: registers, PSTATE and reset
A dump shows
cpsr=0x3c9. Which level and stack pointer is that, and what does HVF do if you start a vCPU there without offering EL2 to the guest?Show answer
M[3:0] = 0b1001: EL2 (bits 3 to 2 =0b10) with its own stack pointer, EL2h, all four masks set. Without EL2 offered, the guest cannot be in that mode, andhv_vcpu_runrefuses withHV_ILLEGAL_GUEST_STATEbefore the guest runs a single instruction: no VM exit at all.From chapter 06: vCPU state: registers, PSTATE and reset
A guest dies with
pc=0x200,VBAR_EL1=0x0,ELR_EL1=0x40081094andESR_EL1=0x96000021. What went wrong first, and where?Show answer
The PC is
VBAR_EL1 + 0x200, a vector entry, so the guest took an exception at EL1 first and its handler (which does not exist) faulted on the fetch. The first fault is inESR_EL1: class0x25, a data abort at the same level, with fault status0x21, an alignment fault, caused by the load at0x40081094.From chapter 06: vCPU state: registers, PSTATE and reset
The guest runs
svc #0x4dat EL1 with a vector table of its own installed. How many VM exits does thatsvccause, and why?Show answer
None. An
svcfrom EL1 is routed to EL1, so the guest's own vector table handles it (ESR_EL1 = 0x5600004d, class0x15). Only exceptions routed to EL2 and forwarded by HVF reach the VMM.From chapter 06: vCPU state: registers, PSTATE and reset
What value does the VMM give vCPU 0's
MPIDR_EL1, and why is the top bit set when the CPU number is 0?Show answer
0x8000_0000. The affinity fields that number the CPU (Aff0,Aff1, …) are all 0 for the first CPU, and bit 31 is defined as always 1 (RES1) by the architecture.From chapter 06: vCPU state: registers, PSTATE and reset
Reset clears three bits of
SCTLR_EL1. Which, and why does a kernel want them clear at entry?Show answer
M (bit 0, stage-1 address translation), C (bit 2, data caching) and I (bit 12, instruction caching). A kernel turns translation and caches on itself, in an order it controls; it cannot trust translation or cache state left behind by whatever ran before it.
From chapter 06: vCPU state: registers, PSTATE and reset
You start a test guest in EL1t (
0x3c4) instead of EL1h. Its start code setsspand prints fine, but the first exception it takes never returns. Which register explains it?Show answer
SP_EL1. In EL1t, the start code'sspisSP_EL0, soSP_EL1keeps its reset value 0. Taking an exception to EL1 always switches toSP_EL1, so the handler's first store goes below address 0, faults, and re-enters the same handler forever, inside the guest.From chapter 06: vCPU state: registers, PSTATE and reset
A guest asks the platform for a system reset. Is that the same thing as the reset state
Vcpu::resetcreates?Show answer
No. The reset state is the set of register values a CPU has at power-on, which
Vcpu::resetrecreates for one vCPU. A system reset is a request, made through PSCI (chapter 08), to restart the whole machine; it ends with every vCPU back in its reset state.
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:
x0and/chosen(chapter 10); checked arithmetic and guest memory (chapter 04);layout.rs(chapter 05); PSTATE0x3c5(chapter 02) and the virtual CPU (vCPU) reset (chapter 06); the random seeds in/chosen(chapter 10);--raw,helloand exit codes 2 and 5 (chapter 03). - Primers (read first):
arm64-boot-protocol(header, placement, entry state);elf(program headers,fileszversusmemsz);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?
xxd -l 64 .cache/macvmm/Image-virt00000000: 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@...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-virtas an EFI zboot wrapper, refuse it by name, and unwrap it withcargo xtask unzboot. - Implement a boot plan you can print and test: device tree at
0x4000_0000, Image at0x4020_0000 + text_offset, initramfs atalign_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,x1tox3= 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:
scripts/fetch.sh linuxscripts/fetch.sh linuxfetch: cached vmlinuz-virtfetch: cached initramfs-virtfetch: cached config-6.18.60-0-virtfetch: cached Image-virtfetch: built initramfs-test.img sha256=caef97fecea58e6ee29a2dda26fba750ad0e0da1df31f4f170b87f14fed204d4The 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 know | Who decides | Where it comes from |
|---|---|---|
| where it sits | the kernel, partly | a 2 MiB-aligned base plus text_offset from its header |
| how much room it has | the kernel | image_size from its header: the file plus the memory it will clear |
| what machine this is | the VMM | the device tree, with its address in x0 (chapter 10) |
| where its first files are | the VMM | the initramfs, with its range in /chosen |
| what state the CPU is in | the protocol | booting.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.
| Offset | Field | Alpine's bytes | Our rule |
|---|---|---|---|
0x00 | code0, code1 | 4d5a 40fa 27b4 5514 | code, not ours to read |
0x08 | text_offset | 0 | a multiple of 4 KiB |
0x10 | image_size | 0x022a_0000 | not zero; start plus size inside RAM, without overflow |
0x18 | flags | 0xa (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..0x37 | reserved | zeros | ignored |
0x38 | magic | 41 52 4d 64, ARM\x64 | must match |
0x3c | res5 | 0x40 | ignored |
| (the file) | its length | 0x022a_0000 | at 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:
/// 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.
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 inspectorLoading 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:
/// 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:
/// 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 }}/// 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:
/// 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:
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 10dd reports 8+0 records in; that is expected.
cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-huge --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10macvmm: cannot load the guest: kernel (arm64 Image) (0xffffffffffffffff bytes at 0x40200000) does not fit inside guest RAMAnswer (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:
/// 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:
xxd -l 64 .cache/macvmm/vmlinuz-virt00000000: 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 .........#..@...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:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/vmlinuz-virtcargo run -q -p macvmm -- run --kernel .cache/macvmm/vmlinuz-virtmacvmm: cannot load the guest: EFI zboot image; run scripts/fetch.sh linux (unwraps it) or pass the raw ImageThe 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:
cargo xtask unzboot .cache/macvmm/vmlinuz-virt .cache/ch13/Imageshasum -a 256 .cache/ch13/Image .cache/macvmm/Image-virtcargo xtask unzboot .cache/macvmm/vmlinuz-virt .cache/ch13/Imageunzboot: wrote .cache/ch13/Imageshasum -a 256 .cache/ch13/Image .cache/macvmm/Image-virta2cecb9b6fdbd83e87bd43c8040de67300d5b8dde1fc50c34714faa272888f17 .cache/ch13/Imagea2cecb9b6fdbd83e87bd43c8040de67300d5b8dde1fc50c34714faa272888f17 .cache/macvmm/Image-virtWhy 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:
/// 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:
/// 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.
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 inspectorDrop .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:
/// `/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:
/// 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:
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).
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:
// 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:
"--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:
"--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:
- Read each file whole, as your
--rawpath reads its blob: a regular file, not empty, at most the RAM size. (The reference's isread_inputincrates/vmm/src/backend/hostio.rs.) - Hand the bytes to
plan()in thekernel,initrdandcmdlinefields ofBootInputs;plan()callsdetect, so the file name never matters. - Print a
LoaderErrorasmacvmm: cannot load the guest:and its message, and exit with code 2. - Add
--dry-run, a flag with no value (chapter 05 ran only the reference's): printmacvmm boot plan (dry run, no VM created)and the plan, exit 0, create no VM. - Until the ELF loader, let the
ImageKind::Elfarm returnLoaderError::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:
cargo run -q -p macvmm -- run --kernel ../.cache/ch13/Image-huge --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 10It 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:
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-noentcp target/debug/macvmm target/ch13/macvmm-noent && scripts/sign.sh --no-entitlements target/ch13/macvmm-noent && codesign -d --entitlements - target/ch13/macvmm-noentExecutable=<repo>/target/ch13/macvmm-noentNow the dry run, from that copy:
../target/ch13/macvmm-noent run --dry-run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512Mtarget/ch13/macvmm-noent run --dry-run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512Mmacvmm 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: offExit 0, and every number this chapter set out to produce. Ask the same copy to boot for real:
../target/ch13/macvmm-noent run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --mem 512M --timeout 10target/ch13/macvmm-noent run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10macvmm: 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.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.
xxd -s 0x1972800 -l 16 ../.cache/macvmm/Image-virttail -c +26683401 ../.cache/macvmm/Image-virt | cmp - /dev/zeroxxd -s 0x1972800 -l 16 .cache/macvmm/Image-virt; tail -c +26683401 .cache/macvmm/Image-virt | cmp - /dev/zero01972800: ffff ffff ffff ffff 0000 0000 0000 0000 ................cmp: EOF on stdinEOF 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):
| State | Value | Why |
|---|---|---|
| PC | the kernel's first byte, 0x4020_0000 | the 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) |
x0 | 0x4000_0000, the device tree | the kernel's only description of the machine |
x1, x2, x3 | 0 | "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) | 0x3c5 | EL1h (EL1, using its own stack pointer), with debug, SError (system error), IRQ (interrupt request) and FIQ (fast interrupt request) masked |
| MMU | off (SCTLR_EL1.M = 0, in the system control register, chapter 06) | required: the kernel builds its own page tables |
| instruction cache | on or off | required: no stale lines for the Image |
SCTLR_EL1.C and .I | 0 | our reset's choice, not the protocol's; with the MMU off, data accesses are non-cacheable anyway |
| the Image's bytes | cleaned 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:
let boot = BootParams { pc: self.plan.entry, x: [self.plan.x0, 0, 0, 0], cpsr: self.plan.cpsr,};/// 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:
/// 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:
cargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/memtest --timeout 10memtest: 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 okThe 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:
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 viewsBreaking 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:
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 10Predict the message, then what happens if the same bytes go through --raw, which parses nothing:
cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-badmagic --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 10macvmm: cannot load the guest: --initrd needs an arm64 Image --kernelYour 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:
cargo run -q -p macvmm -- run --kernel ../.cache/ch13/Image-badmagic --mem 512M --timeout 10cargo run -q -p macvmm -- run --kernel .cache/ch13/Image-badmagic --mem 512M --timeout 10macvmm: cannot load the guest: --kernel is not an ELF file; load a flat binary with --raw F@ADDRNo 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:
cargo run -q -p macvmm -- run --raw ../.cache/ch13/Image-badmagic@0x40200000 --mem 512M --timeout 10cargo run -q -p macvmm -- run --raw .cache/ch13/Image-badmagic@0x40200000 --mem 512M --timeout 10[ 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) ]---macvmm: timeout: the guest was still running after --timeout 10sSurprise: 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:
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 15cargo run -q -p macvmm -- run --dry-run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512Mmacvmm 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: offThe 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?
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --mem 512M --timeout 15[ 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)macvmm: timeout: the guest was still running after --timeout 15sAbout 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):
mkdir -p crates/vmm/testscp ../course/checkpoints/13/contract/bootplan.rs crates/vmm/tests/cargo test -q -p vmm --test bootplancargo test -q -p vmm --test bootplanrunning 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.00serror: test failed, to rerun pass `-p vmm --test bootplan`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:
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:
MACVMM_SEED=7881690183168229385 cargo test -q -p vmm --test bootplanThe 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:
e_ident: the magic\x7fELF,ELFCLASS64, little-endian data, version 1; thene_type = ET_EXEC,e_machine = 183(AArch64),e_version = 1.e_phentsize = 56,e_phnumat most 64, ande_phoff + e_phnum * 56inside the file, withchecked_mulandchecked_add.- 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 withchecked_add, inside RAM; at or above RAM base + 512 KiB, clear of the device-tree slotplan()reserved first; and disjoint from every other segment. e_entryinside a segment marked executable.- Ignore section headers: a loader does not need them, and every field you do not read is a field nobody can attack.
- Load by copying
p_fileszbytes and zeroing the rest up top_memsz, through the guest-memory API, in fixed-size chunks, sop_memsznever 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:
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 10cargo run -q -p macvmm -- run --dry-run --mem 64M --kernel target/guests/aarch64-unknown-none/release/hellomacvmm 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: oncargo run -q -p macvmm -- run --mem 64M --kernel target/guests/aarch64-unknown-none/release/hello --timeout 10hello from guest, x0=0x40000000guest doneSegment 2 occupies 0x80020 bytes of RAM. How many come from the file? objdump (Xcode's command-line tools) prints the program headers:
objdump -p ../target/guests/aarch64-unknown-none/release/helloobjdump -p target/guests/aarch64-unknown-none/release/hellotarget/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: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.
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 10Check your guess:
cargo run -q -p macvmm -- run --mem 64M --kernel .cache/ch13/hello-phnum --timeout 10macvmm: cannot load the guest: ELF has 65535 program headers (at most 64)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 inspectorYour turn
Check your learner/ against the list and finish what is missing:
arch/layout.rs: the seven constants shown.loader/mod.rs:ImageKind,detect, and theLoaderErrorvariants below, each with a one-line message, plus aMemory(MemoryError)variant andFrom<MemoryError> for LoaderError, so that?works on guest-memory writes.RamRangeandoverlapsare chapter 03's, unchanged.loader/image.rs:parse_header,placeandloadas shown, withTEXT_OFFSET_ALIGN(4096), the flag bits from the table, and the typesPageSize,ImageHeaderandArmImage(whoseplacement()is the kernel's plan row). Two helpers the code above uses:fn le64(b: &[u8], off: usize) -> Option<u64>reads the little-endianu64atoff, or returnsNonewhen the slice is too short (compute the end withchecked_add); andplacement()returnsplan.rs'spub struct Placement { pub what: String, pub addr: u64, pub len: u64 }, withwhatset to"kernel (arm64 Image)",addrto the load address andlentoimage_size.loader/initrd.rs:align_up,placeandcheck_window.loader/plan.rs:BootPlanandplan(): the 512 KiB device-tree slot first, then the ELF arm, the Image arm as shown,--initrdand--cmdlinerefused for anything but an Image, anddtb_limitlast, as shown. Its printed lines must match the--dry-runcapture exactly, fromdtb 0x40000000toentry pc=… x0=… cpsr=0x3c5.loader/elf.rs: from the rules, then compare with the reference.fdt/machine.rs:/chosengainsbootargs,linux,initrd-startandlinux,initrd-end.machine/mod.rs:BootParams { pc, x: [x0, 0, 0, 0], cpsr }from the plan.crates/macvmm/src/cli.rs:--kernel(ELF or Image, decided bydetect),--initrd,--cmdlineand--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:
/// 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 MacRun this from the repository root:
scripts/checkpoint.sh 13You should see, as the last line:
CHECKPOINT 13 PASSIt 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:
scripts/checkpoint.sh 13checkpoint: 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 PASSThe 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_fileszandp_memsz: what must the loader put in the bytes between them, and what does the specification say ifp_fileszis larger? - Linux
drivers/of/fdt.c, the functionearly_init_dt_check_for_initrd: what does the kernel do iflinux,initrd-startorlinux,initrd-endis missing, or if start is above end?