Chapter 07 · Part III
The exit loop: decoding syndromes and emulating MMIO
Course progress: chapter 07 is 8 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 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.From chapter 04: Guest memory: the only safe access is a copy
A guest asks the VMM to read 8 bytes at address
0xFFFF_FFFF_FFFF_FFFC. Guest RAM is0x4000_0000..0x4400_0000. Computeaddr + lenin 64-bit wrapping arithmetic, and say whether the checkaddr >= 0x4000_0000 && addr + len <= 0x4400_0000accepts the access.Show answer
The true sum is
0x1_0000_0000_0000_0004, which needs 65 bits; wrapped to 64 bits it is0x4. Both halves of the check pass (0xFFFF_FFFF_FFFF_FFFCis above the base,0x4is below the end), so a wrapping check accepts an access that starts 4 bytes below the top of the address space.checked_addreturnsNoneinstead, and the access is refused.From chapter 04: Guest memory: the only safe access is a copy
hv_vm_mapis asked to map 4 KiB of host memory at guest address0x4000_0000, which is 16 KiB-aligned. What does it answer on a Mac with the default configuration?Show answer
HV_BAD_ARGUMENT. The address is fine, but the size must be a whole number of 16 KiB host pages, because HVF's stage-2 table, the one that maps guest memory to ours, uses the Mac's 16 KiB page size by default.From chapter 04: Guest memory: the only safe access is a copy
A guest RAM made of two adjacent regions,
0x4000_0000(64 KiB) and0x4001_0000(64 KiB). Is an 8-byte read at0x4000_FFFCvalid, and why?Show answer
No. The range crosses from the first region into the second. The two regions are separate host allocations that only look contiguous to the guest, so one copy from a single host pointer would run off the end of the first allocation. An access must lie inside one region.
From chapter 04: Guest memory: the only safe access is a copy
Why does the
GuestMemorycontract have noget_slicethat returns a&[u8]into guest RAM?Show answer
A
&[u8]promises the compiler that nobody changes those bytes while the reference lives, and the compiler uses that promise (it may load a byte once and reuse the value, or load it twice and assume both loads agree). The guest, another vCPU or a device thread can change guest RAM at any moment, so the promise would be false. The contract hands out copies instead, and the VMM checks its own copy.From chapter 04: Guest memory: the only safe access is a copy
check_range(GuestAddress(0x4000_0000), 0)on a valid RAM region: true or false, and why does the contract choose that answer?Show answer
False. A zero-length range is never a valid access, so
readandwriterefuse an empty buffer too, andcheck_rangeis true exactly when the matchingreadwould succeed.From chapter 04: Guest memory: the only safe access is a copy
Name two things a volatile load guarantees and two things it does not.
Show answer
It guarantees that the compiler performs the load, at its size, every time the program says so, in program order relative to other volatile accesses, and never assumes the value is unchanged. It does not make an access of several elements atomic, and it gives no ordering or visibility guarantee towards other threads or the guest (that needs atomics and barriers, chapter 16). Volatile does not mean thread-safe.
From chapter 04: Guest memory: the only safe access is a copy
write_u32(GuestAddress(0x4000_0010), 0xdead_beef)succeeds. Which byte doesread_u8(GuestAddress(0x4000_0010))return, and why?Show answer
0xef. The helpers are little-endian, like the guest: the least significant byte of the value goes to the lowest address, so the bytes in memory areef be ad de.From chapter 04: Guest memory: the only safe access is a copy
A region table is given the region
base = 0xFFFF_FFFF_FFFF_C000, size = 0x8000. Both are 16 KiB multiples. Which construction rule rejects it, and what would go wrong without that rule?Show answer
The overflow rule:
base + sizepassesu64::MAX. Without it, the region's end would wrap to0x4000, and a test of the formaddr < endwould place the region's end in low memory, so the table would answer nonsense for addresses near zero.From chapter 04: Guest memory: the only safe access is a copy
Your VMM's bounds check uses
addr + lenwith Rust's default release settings, where overflow is not checked. A guest calls the memory-hash debug call withaddr = 0xFFFF_FFFF_FFFF_FFF0, len = 0x20. What happens, and what changes if overflow checks are on?Show answer
Without overflow checks the sum wraps to
0x10, the range test passes, and the VMM forms a host pointer far outside the RAM allocation: a guest-chosen read of host memory, unless a second check catches it. With overflow checks on, the addition panics, and the guest has crashed the VMM. Both are wrong: onlychecked_add, which turns the overflow into an ordinary error, keeps the VMM running and safe.From chapter 00: Two kernels, one Mac: what a virtual machine is
A guest runs 1,000 instructions under trap-and-emulate; 6 of them are privileged or touch the console. Roughly how many instructions does the VMM handle for it, and what does the processor do with the rest?
Show answer
About 6, one per trap. The other 994 run natively on the real processor, unseen by the VMM; only an emulator handles every instruction.
From chapter 00: Two kernels, one Mac: what a virtual machine is
An instruction reads the current privilege mode and, in user mode, answers "user" without trapping. Is it sensitive, privileged, both or neither, and why does that break trap-and-emulate?
Show answer
Sensitive (it reads state the VMM must control) but not privileged (it does not trap). Nothing traps, so the VMM never gets a turn to supply the virtual answer "kernel", and the guest kernel acts on the truth: it is in user mode.
From chapter 00: Two kernels, one Mac: what a virtual machine is
You must run an unmodified guest on a processor that has sensitive, unprivileged instructions and no hardware assist. Which strategies are open to you, and which is not?
Show answer
Interpretation (slow but correct) and binary translation (rewrite the bad instructions just before they run). Paravirtualization is not: it needs the guest's source changed.
From chapter 00: Two kernels, one Mac: what a virtual machine is
A kernel copied into an ordinary process stores to the console's address. Which ledger row is that, and what does a VMM using trap-and-emulate do to make it work?
Show answer
Row 3, devices at fixed addresses. The VMM leaves the address unmapped, so the store traps; the VMM plays the device's part (prints the character) and resumes the guest after the store.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Under hardware assist, why does the guest kernel's "am I in kernel mode?" check pass, when it failed under plain trap-and-emulate?
Show answer
The guest kernel now runs in a real kernel mode, below a new, more privileged level that the VMM's side controls, so the honest answer is "kernel". The level above traps only what it was told to watch.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Before hardware help for memory, how did a VMM stop a guest kernel from mapping memory that is not its own, and what did that cost?
Show answer
With shadow page tables: real tables the VMM keeps, mapping guest addresses straight to host memory, kept in step by trapping every guest write to its own page tables. Every such write cost a trap; a second hardware translation stage removed them.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Someone says "QEMU is a hypervisor". How does this course say the same thing, and which part of a Mac is the course's "hypervisor"?
Show answer
QEMU is a VMM (with its own emulator when no hardware assist is used). In this course the hypervisor is only the part at a level more privileged than the kernel's that controls the processor's support for virtual machines; on a Mac, a part of macOS, not our program.
From chapter 00: Two kernels, one Mac: what a virtual machine is
scripts/doctor.shprintsdoctor: hv_vm_create: OK. What has this proved about the Mac and the probe process?Show answer
The processor has the hardware-assisted level, macOS offers it, and this process (signed with the one permission it needs) was allowed to create a virtual machine.
Concepts you'll need
Chapters before this one: chapter 06, vCPU state: registers, PSTATE and reset.
- Core, taught here: decoding a memory-mapped I/O (MMIO) access from the syndrome alone; the frozen
Exitenum and its decoder, which never panics; the PC-advance table (PC: program counter); register 31 asxzr; emulating the access, not the instruction; the test device and a one-entry bus; the trace's MMIO fields and the per-vCPU (virtual CPU) ring of exits. - Core, from earlier: the exception class (EC), IL (instruction length), the ISS (instruction-specific syndrome) and the call-versus-retry rule (chapter 02); the run loop and exit trace (chapter 03); guest memory (chapter 04); stage-2 holes, data aborts, the DFSC (data fault status code),
classify_ipaand the unhandled-MMIO policy (chapter 05); the register dump (chapter 06). - Primers (read first):
reading-arm-specs(a register page, the ESR's ISS tables, RES0);aarch64-reading(wandxregisters,xzr, sign extension,ldp/stp, writeback forms). - Pointers: the Arm Architecture Reference Manual (ARM ARM) page for
ESR_EL2; other ISV = 0 instructions, an Aside; x86's version of this exit, an Aside. - Forward definitions: the checked bus (chapter 09);
SysReg(chapter 08);WfxandVtimerActivated(chapter 11);CpuOff(chapter 20); the ISV = 0 decoder, the stage-1 walk and theAbortoutcome (chapter 21);Brk(a post-v1 chapter). Each is defined at first use.
At the end of chapter 05, a guest stored to an address where nothing lives, and the reference virtual machine monitor (VMM) stopped it with unhandled MMIO write at 0xc000000 size 4 and a dump that said SRT=9. Its decision never looked at the guest's instruction (the insn at pc: line was read afterwards, for humans). So how did it know the store was 4 bytes wide, from register 9? And once we answer that store instead of stopping, what else must we do before the guest can carry on?
This chapter works on row 3 of chapter 00's problem ledger, devices at fixed physical addresses: chapter 05 left holes in stage 2, and now something answers in them; chapter 09 closes it. Sitting A decodes the hardware's note in the browser and host-only tests (about 1.5 hours); sitting B emulates the access on your Mac (about 2.5 hours).
Predict In sitting B your VMM will emulate stores to a device. Suppose you comment out the line that moves the guest's PC (program counter, the address of the instruction it runs) past an emulated store. Will the guest (a) crash, (b) take the same exit forever, or (c) skip the store and carry on? Use your exit cost from chapter 03 (ours was about 1.4 µs): how many exits per second do you expect?
Write it under ## Predict in your journal. Sitting B runs it as the first deliberate break.
Objectives: by the end you can
- (Sitting A) Decode any
ESR_EL2value into the ten-variantExitenum, with a decoder that never panics for any 64-bit input. - (Sitting A) Decode a data-abort syndrome by hand into its six fields, and name a guest instruction that produces it.
- (Sitting B) Emulate a data abort with ISV = 1: mask a write, sign-extend a read, treat SRT = 31 as
xzr(neversp), then advance the PC by 4. - (Sitting B) For ISV = 0, stop with a fatal error that prints the instruction word, not a guess.
- (Sitting B) Fill the trace's MMIO fields, keep a ring of the last 256 exits per vCPU, and predict, then observe, what a missing PC advance does.
Before you start. Run scripts/learner start 07 from the repository root to copy this chapter's journal to learner/journal/07.md. Work in learner/ and run from inside it. Each block's lead-in says whether to type it, check yours against it, or read it and write your own.
The note the hardware leaves
The guest ran str w2, [x1], and x1 pointed at a hole, so the CPU took a data abort to EL2 (exception level 2, where the hypervisor runs). Before handing us the exit, the hardware wrote a note in the syndrome: this was a write (WnR, write not read), of 4 bytes (SAS, syndrome access size), from register 2 (SRT, syndrome register transfer), a 32-bit register (SF, sixty-four-bit flag, here 0); and for loads, whether to sign-extend the value (SSE, syndrome sign extend). One more bit, ISV (instruction syndrome valid), says whether the note was written at all.
With that note, our VMM can do the store for the guest without looking at the instruction.
Aside
x86 is less helpful. On Intel the matching exit (an EPT violation, EPT being extended page tables, or, for the MMIO pages of Linux's KVM, the Kernel-based Virtual Machine, an EPT misconfiguration; on AMD a nested page fault) gives the address and access type but not the register or size, so the VMM decodes the instruction itself. See the Intel Software Developer's Manual, volume 3.
The fields live in the ISS, the low 25 bits of the syndrome you split in chapter 02. ESR_EL2 is 64 bits wide; we ignore the bits above 31, but the decoder must accept any value. Open the ARM ARM (document DDI 0487) at the register page ESR_EL2, "ISS encoding for an exception from a Data Abort", as the reading-arm-specs primer showed you. The bits we use:
| Bits | Field | Meaning |
|---|---|---|
| 24 | ISV | 1: bits 23 to 14 describe the access |
| 23:22 | SAS | size: 1 << SAS bytes (0 is 1 byte, 3 is 8 bytes) |
| 21 | SSE | a load must be sign-extended |
| 20:16 | SRT | the register loaded or stored; 31 means xzr |
| 15 | SF | 1: a 64-bit x register; 0: a 32-bit w register |
| 6 | WnR | 1: write (store); 0: read (load) |
| 5:0 | DFSC | data fault status code (chapter 05): 0x4 to 0x7 are translation faults at levels 0 to 3; our holes show 0x6, level 2 |
The code also decodes AR (bit 14, acquire/release ordering), FnV (bit 10, fault address not valid) and S1PTW (bit 7, the fault hit the guest's own stage-1 page-table walk); only S1PTW matters today.
Put the story's values in and the syndrome falls out:
31 26 25 24 23 22 21 20 16 15 6 5 0+---------+--+--+-----+--+--------+--+ ... +--+-------+| 100100 | 1| 1| 10 | 0| 00010 | 0| | 1| 000110|+---------+--+--+-----+--+--------+--+ ... +--+-------+ EC 0x24 IL ISV SAS=2 SSE SRT=2 SF WnR DFSC 0x6 = 0x93820046str w2, [x1] into a stage-2 hole: every field but the base register is in the note.
Check it against chapter 05's stop, esr=0x93890046. Only bits 20 to 16 differ: SRT is 9, so the store came from w9. That dump's insn at pc: 0xb9000109 is str w9, [x8], and x8 held 0xc000000: note and instruction agree. That answers the opening question: the hardware wrote it down.
In the decoder, toggle ISV, change SAS, set SRT to 31.
ESR decoder
Split an ESR_EL2 syndrome into its fields, flip bits to see what changes, and see what macvmm would do with the exit.
Runs in browserOpen full page: ESR decoderIf the lab does not load, do the same on paper: decode 0x93890046 and 0x92000046 with the table above. Sitting A's host tests check both answers.
When the note is blank: ISV = 0
The note has room for one register number and one size. ldp x0, x1, [x2] loads two registers, so it leaves ISV = 0. A writeback form (ldr x0, [x1], #8) has one data register, but it also changes its base register, and the note has no room to say so; it gives ISV = 0 too. So do other instructions the ARM ARM leaves out of the note (exclusives, atomics, vector loads). With ISV = 0, bits 23 to 14 are RES0 (the primer's word: reserved, with no meaning you may rely on): SAS, SSE, SRT and SF carry no information and must not be used.
Aside
ISV = 0 also comes from exclusives (ldxr, stxr), atomics (ldadd, cas), SIMD (single instruction, multiple data) and floating-point loads and stores (ldr q0), and DC ZVA, which zeroes a block; the same ARM ARM page lists them. Chapter 21 emulates pairs and writeback forms and refuses the rest.
So what should our VMM do with ISV = 0? The tempting answer is to guess: 8 bytes, from the register in SRT. Sitting B's optional third break lets you see what the guess does. This chapter's rule: stop with a fatal error that prints the instruction word, as the reference's dump does. A human can decode the word; a guess hides the problem.
One enum for every exit
From now on, every return from hv_vcpu_run becomes one value of a single enum. Its shape is frozen: later chapters and the contract tests use it exactly as shown, so new behaviour goes into handlers, never new variants.
Open learner/crates/vmm/src/arch/esr.rs; chapter 05's field helpers, DataAbort struct and decode_data_abort stay as they are. The file stays pure (no framework calls), so it runs in host-only tests. Type its top, which denies three Clippy lints, unchecked arithmetic, indexing and truncating casts, the usual ways to panic:
#![deny( clippy::arithmetic_side_effects, clippy::indexing_slicing, clippy::cast_possible_truncation)]Type the enum. Each variant is named after what the guest did:
/// What one `hv_vcpu_run` return was. Frozen: later chapters add handlers, never variants.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Exit { /// `HV_EXIT_REASON_CANCELED`: our own kick; may be spurious or sticky (seen on real hardware). Canceled, /// `HV_EXIT_REASON_VTIMER_ACTIVATED` (never seen with the in-kernel GIC). VtimerActivated, /// EC 0x01. `ti`: 0 WFI, 1 WFE, 2 WFIT, 3 WFET. Wfx { ti: u8 }, /// EC 0x16. The PC has ALREADY advanced past the HVC. Hvc { imm: u16 }, /// EC 0x17. The PC still points AT the SMC. Smc { imm: u16 }, /// EC 0x18. SysReg(SysRegAccess), /// EC 0x20. InstructionAbort { ifsc: u8, s1ptw: bool }, /// EC 0x24. DataAbort(DataAbort), /// EC 0x3c (only with debug exceptions trapped). Brk { imm: u16 }, /// Any other EC, and `HV_EXIT_REASON_UNKNOWN` or an undefined reason. Unknown { ec: u8, esr: u64 },}The decoder knows them all, so nothing is silently misread, though some wait several chapters for a handler:
| Variant | Exception class | Handled now? |
|---|---|---|
Canceled | (our own stop, chapter 03's --timeout) | yes: re-check the stop flag |
Hvc, Smc | 0x16, 0x17 | yes: chapter 03's debug calls |
DataAbort | 0x24 | yes: this chapter |
InstructionAbort, Unknown | 0x20, anything else | yes: a fatal stop with the dump |
SysReg | 0x18, a trapped system register access | stop until chapter 08 |
Wfx, VtimerActivated | 0x01 ("wait for interrupt or event"), the timer | stop until chapter 11 |
Brk | 0x3c, a breakpoint instruction | stop (a debugger stub in a post-v1 chapter would handle it) |
The variants not handled yet stop the virtual machine (VM) with a message naming them.
Already in your file from chapter 05; check that your data-abort decoder masks every field to its width, ISV or not:
/// Decode a data-abort ISS (module docs table). Every field is masked to its width, so any/// `esr` gives a value; with ISV = 0 bits 23:14 are RES0, so those fields carry nothing.pub const fn decode_data_abort(esr: u64) -> DataAbort { DataAbort { isv: bit(esr, 24), sas: field8(esr, 22, 2), sse: bit(esr, 21), srt: field8(esr, 16, 5), sf: bit(esr, 15), ar: bit(esr, 14), fnv: bit(esr, 10), s1ptw: bit(esr, 7), wnr: bit(esr, 6), dfsc: field8(esr, 0, 6), }}A trapped system register has its own ISS layout, which chapter 08 explains. The SysReg variant needs it now; type it (encoding can wait for chapter 08):
/// A trapped `MSR`/`MRS`/system instruction (EC 0x18; D17.2.40, "ISS encoding for an exception/// from MSR, MRS, or System instruction execution in AArch64 state"). Frozen.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct SysRegAccess { pub op0: u8, pub op1: u8, pub crn: u8, pub crm: u8, pub op2: u8, /// The general-purpose register; 31 means XZR. pub rt: u8, /// `Direction = 1`: MRS (a read into Rt). pub read: bool,}impl SysRegAccess { /// The register as `hv_sys_reg_t` (`op0<<14 | op1<<11 | CRn<<7 | CRm<<3 | op2`), the id /// `hv_vcpu_{get,set}_sys_reg` takes (verified against the header by `hvf`'s tests). pub const fn encoding(&self) -> SysReg { SysReg::new(self.op0, self.op1, self.crn, self.crm, self.op2) }}/// Decode a sysreg-trap ISS (EC 0x18).pub const fn decode_sysreg(esr: u64) -> SysRegAccess { SysRegAccess { op0: field8(esr, 20, 2), op2: field8(esr, 17, 3), op1: field8(esr, 14, 3), crn: field8(esr, 10, 4), rt: field8(esr, 5, 5), crm: field8(esr, 1, 4), read: bit(esr, 0), }}The decoder's arms name classes from a small pub mod ec of u8 constants (WFX = 0x01, HVC64 = 0x16, SMC64 = 0x17, SYSREG = 0x18, IABT_LOWER = 0x20, DABT_LOWER = 0x24, BRK64 = 0x3c). Add it at the top of the file, and fill in chapter 06's ec_name rows for the same classes. Then type the decoder, and from_hv, which combines chapter 02's exit reason with the syndrome; your run loop now calls it instead of its own match:
impl Exit { /// Decode an `ESR_EL2` value from an `EXCEPTION` exit. Pure and total: never panics for /// any `u64`, because a hostile guest chooses what trapped. An EC we do not handle is /// [`Exit::Unknown`], which the exit handler turns into a fatal stop with a dump. pub const fn decode(esr: u64) -> Exit { let imm = field16(esr, 0, 16); match esr_ec(esr) { ec::WFX => Exit::Wfx { ti: field8(esr, 0, 2), }, ec::HVC64 => Exit::Hvc { imm }, ec::SMC64 => Exit::Smc { imm }, ec::SYSREG => Exit::SysReg(decode_sysreg(esr)), ec::IABT_LOWER => Exit::InstructionAbort { ifsc: field8(esr, 0, 6), s1ptw: bit(esr, 7), }, ec::DABT_LOWER => Exit::DataAbort(decode_data_abort(esr)), ec::BRK64 => Exit::Brk { imm }, other => Exit::Unknown { ec: other, esr }, } } /// Combine the framework's exit reason with the syndrome: `CANCELED` and /// `VTIMER_ACTIVATED` carry no syndrome, `EXCEPTION` is decoded, and `UNKNOWN` (or a value /// this SDK does not define) is [`Exit::Unknown`] with the syndrome kept for the dump. pub const fn from_hv(reason: ExitReason, esr: u64) -> Exit { match reason { ExitReason::Canceled => Exit::Canceled, ExitReason::VtimerActivated => Exit::VtimerActivated, ExitReason::Exception => Exit::decode(esr), ExitReason::Unknown | ExitReason::Other(_) => Exit::Unknown { ec: esr_ec(esr), esr, }, } }}Give Exit and DataAbort a one-line Display, such as data abort (EC 0x24): ISV=1 SAS=2 (4 bytes) ...; the contract tests check that it never prints a control character.
Security
The syndrome describes a hostile guest, so a decoder panic would let any guest kill the VMM on purpose; the checkpoint feeds it a million random values. Hence the three lints, and an Unknown that keeps the raw syndrome.
Test it on the host before you stop, with cargo test -p vmm esr inside learner/. Start with 0x93820046, the story's store, and 0x92000046, which should give a DataAbort with ISV = 0, WnR = 1 and DFSC 0x6.
Good place to stop. Sitting B needs your Mac, your learner workspace and about 2.5 hours.
Emulating the access
Notice that we never decode the instruction. The hardware did; we only perform the access it described, using the note plus the exit's IPA (intermediate physical address, chapter 05). A size is one of four widths, so it gets an enum, AccessSize, with a mask() for the low bytes. Create learner/crates/vmm/src/bus.rs (declare it with pub mod bus; in lib.rs) and type:
/// The width of one MMIO access (a load or store of 1, 2, 4 or 8 bytes). Frozen from/// chapter 9 on: later chapters rely on it unchanged.#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]pub enum AccessSize { B1 = 1, B2 = 2, B4 = 4, B8 = 8,}impl AccessSize { /// The size in bytes. pub const fn bytes(self) -> u64 { self as u64 } /// The low `bytes() * 8` bits set: `0xff`, `0xffff`, `0xffff_ffff` or `u64::MAX`. pub const fn mask(self) -> u64 { match self { AccessSize::B1 => 0xff, AccessSize::B2 => 0xffff, AccessSize::B4 => 0xffff_ffff, AccessSize::B8 => u64::MAX, } } /// From a data abort's `SAS` field (`size = 1 << SAS`). Only the low two bits are used, /// so every input gives a size. pub const fn from_sas(sas: u8) -> AccessSize { match sas & 3 { 0 => AccessSize::B1, 1 => AccessSize::B2, 2 => AccessSize::B4, _ => AccessSize::B8, } } /// From a byte count, if it is 1, 2, 4 or 8. pub const fn from_bytes(n: u64) -> Option<AccessSize> { match n { 1 => Some(AccessSize::B1), 2 => Some(AccessSize::B2), 4 => Some(AccessSize::B4), 8 => Some(AccessSize::B8), _ => None, } }}from_sas uses only the low two bits, so every syndrome gives a size. Type the access, in vcpu/mmio.rs:
/// One decoded MMIO access. Frozen: later chapters use this shape.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct MmioAccess { pub ipa: u64, pub size: AccessSize, /// `Some(value)` for a store: `X[SRT]` masked to `size` (0 for XZR). pub write: Option<u64>, /// SRT: the register loaded or stored; 31 = XZR. pub reg: u8, /// SSE: sign-extend a load. pub sign_extend: bool, /// SF: the register is an X register (64-bit), not W. pub sixty_four: bool,}For a store, building it reads the source register at once. Two lines carry the rules: register 31 reads as zero, and the value is masked to the access size, so a strb sends only its low byte. Type:
/// The access a data abort with ISV = 1 describes, or `None` when ISV = 0 (bits 23:14 are/// then RES0: they describe nothing and must not be used). For a store the source register/// is read now: XZR (SRT = 31) reads as 0, and the value is masked to the access size.pub fn from_data_abort( ipa: u64, da: &DataAbort, regs: &dyn VcpuRegs,) -> Result<Option<MmioAccess>> { if !da.isv { return Ok(None); } let size = AccessSize::from_sas(da.sas); let reg = da.srt & 31; let write = if da.wnr { let x = if reg == 31 { 0 } else { regs.x(reg)? }; Some(x & size.mask()) } else { None }; Ok(Some(MmioAccess { ipa, size, write, reg, sign_extend: da.sse, sixty_four: da.sf, }))}Why special-case 31? In Hypervisor.framework's numbering, hv_reg_t 0 to 30 are x0 to x30 and 31 is HV_REG_PC. Check the SDK (software development kit) header:
grep -n HV_REG_PC "$(xcrun --show-sdk-path)/System/Library/Frameworks/Hypervisor.framework/Headers/hv_vcpu_types.h"An SRT passed through unchanged would reach the guest's PC. Make your hvf wrapper refuse 31 too, so that a slip that goes through Reg::x cannot reach the PC; type this:
/// `Xn` for `n` in 0..=30. `n = 31` is not a register here: in a load/store or MRS it means/// XZR (or SP), so the caller must decide, and this returns `None`.pub const fn x(n: u8) -> Option<Reg> { if n <= 30 { Some(Reg(n as ffi::hv_reg_t)) } else { None }}Route your Vcpu's accessors in vcpu/mod.rs through it. x(31) reads 0 and set_x(31, _) throws the value away, which is what makes ldr xzr safe. Type:
fn x(&self, n: u8) -> Result<u64> { match Reg::x(n) { Some(r) => self.inner.get_reg(r).map_err(hv("get Xn")), None => Ok(0), // XZR }}fn set_x(&mut self, n: u8, value: u64) -> Result<()> { match Reg::x(n) { Some(r) => self.inner.set_reg(r, value).map_err(hv("set Xn")), None => Ok(()), // writes to XZR are discarded }}For a load, ldrsh of 0x8001 puts 0xffff8001 in a w register and 0xffffffffffff8001 in an x register, because writing a w register clears the upper 32 bits. Type:
/// Extend a `size`-byte value loaded from a device into what the instruction puts in its/// register: with SSE, sign-extend from `size * 8` bits; then, for a W register/// (SF = 0), keep 32 bits, because writing `Wt` zeroes the upper half of `Xt`. So `ldrsh w`/// of `0x8001` gives `0xffff_8001` and `ldrsh x` gives `0xffff_ffff_ffff_8001`.pub fn sign_extend(value: u64, size: AccessSize, sse: bool, sixty_four: bool) -> u64 { let v = value & size.mask(); let v = if sse && size != AccessSize::B8 { // Shift the sign bit to bit 63, then arithmetic-shift back. let unused = 64u32.saturating_sub(u32::try_from(size.bytes().saturating_mul(8)).unwrap_or(64)); let shifted = v.checked_shl(unused).unwrap_or(0).cast_signed(); shifted.checked_shr(unused).unwrap_or(0).cast_unsigned() } else { v }; if sixty_four { v } else { v & 0xffff_ffff }}Give MmioAccess one more method, load_result(v), which the handler below calls: one line that returns sign_extend(v, self.size, self.sign_extend, self.sixty_four).
A device that remembers
To test a decoder you want a device that cannot surprise you. The test device (--testdev) is 512 scratch registers of 8 bytes at 0x0b00_0000: a read returns what was last written there, cut to the access size, so any wrong value is the decoder's fault.
A device answers read(offset, size) and write(offset, size, value), the offset relative to its base. Type the trait into bus.rs exactly as shown; later chapters and the checkpoint use this signature:
/// An emulated device on the bus. Frozen from chapter 9 on: later chapters rely on it unchanged.pub trait MmioDevice: Send { /// `offset` is relative to the device base. Return value is zero-extended to 64 bits; /// the caller sign-extends if the instruction asked for it. fn read(&mut self, offset: u64, size: AccessSize) -> u64; /// `value` holds the low `size` bytes of the source register. fn write(&mut self, offset: u64, size: AccessSize, value: u64);}Send lets a device move between threads (chapter 20). The device lives in learner/crates/vmm/src/devices/testdev.rs (declare it with pub mod testdev; in devices/mod.rs). TestDev holds regs: Box<[u64; TESTDEV_REGS]>, with TESTDEV_REGS = 512 and a new() that zeroes them. TESTDEV_SIZE is 512 * 8, and the base is TESTDEV_BASE from your layout.rs, the testdev row of chapter 05's table. Type its two methods:
impl MmioDevice for TestDev { fn read(&mut self, offset: u64, size: AccessSize) -> u64 { match locate(offset, size).and_then(|(i, s)| Some((*self.regs.get(i)?, s))) { Some((reg, shift)) => reg.checked_shr(shift).unwrap_or(0) & size.mask(), None => { crate::guest_warn!( "testdev: {}-byte read at offset {offset:#x} is misaligned or outside the \ window (read as zero)", size.bytes() ); 0 } } } fn write(&mut self, offset: u64, size: AccessSize, value: u64) { let slot = locate(offset, size).and_then(|(i, s)| Some((self.regs.get_mut(i)?, s))); match slot { Some((reg, shift)) => { let lanes = size.mask().checked_shl(shift).unwrap_or(0); let v = (value & size.mask()).checked_shl(shift).unwrap_or(0); *reg = (*reg & !lanes) | v; } None => crate::guest_warn!( "testdev: {}-byte write at offset {offset:#x} is misaligned or outside the \ window (ignored)", size.bytes() ), } }}locate is your helper: it accepts an offset only if it is a multiple of the access size and inside the 4 KiB window, and returns the slot (offset / 8) and the bit shift inside it ((offset % 8) * 8). A misaligned access reads as zero and is reported, but only a few times, because the guest decides how often it happens.
A bus with one entry
Our VMM finds the device through the bus, a table from address windows to devices. Today it has one entry, so the smallest bus that works will do; chapter 09 replaces its insides and keeps every name below. Add to bus.rs:
BusError:Unmapped { ipa }, no window contains the address;Straddle { ipa, size }, the access runs past its window's end. AddBus(BusError)to your crate'sError.Bus, aVecof entries: a name (&'static str), a base, a size and the device asArc<Mutex<dyn MmioDevice>>. The mutex is there because handlers get&Bus, yet a write changes the device; your chapter 04lockhelper takes it. Give itnew().insert(name, base, size, dev) -> Result<(), BusError>, which pushes and always returnsOkfor now.device_at(ipa) -> Option<(&'static str, u64)>: the first entry withbase <= ipa < base + size(end bychecked_add), its name and the offset.read(ipa, size) -> Result<u64, BusError>andwrite(ipa, size, value) -> Result<(), BusError>: find the entry (none:Unmapped), refuse withStraddleif the access passes the end, lock the device, call it with the offset, and mask withsize.mask().
Read the reference's read and write, then write your own from the bullets (its route is the lookup plus the straddle check):
/// A `size`-byte read at `ipa`, zero-extended.pub fn read(&self, ipa: u64, size: AccessSize) -> Result<u64, BusError> { let (e, offset) = self.route(ipa, size)?; let value = lock(&e.dev).read(offset, size); Ok(value & size.mask())}/// A `size`-byte write at `ipa`; only the low `size` bytes of `value` are passed on.pub fn write(&self, ipa: u64, size: AccessSize, value: u64) -> Result<(), BusError> { let (e, offset) = self.route(ipa, size)?; lock(&e.dev).write(offset, size, value & size.mask()); Ok(())}Then wire the bus in, in three places.
First, give classify_ipa a bus: &Bus parameter and add the Device { name, offset } variant to IpaClass; ask the bus between the RAM check and the board map. Check yours against the reference's:
/// Classify `ipa` against RAM, the bus and the board layout, in that order. DFSC is/// never consulted: it says *how* stage 2 failed, not *what* lives at the address.pub fn classify_ipa(ipa: u64, mem: &dyn GuestMemory, bus: &Bus) -> IpaClass { if mem.check_range(GuestAddress(ipa), 1) { return IpaClass::Ram; } if let Some((name, offset)) = bus.device_at(ipa) { return IpaClass::Device { name, offset }; } match Layout::virt().find(ipa) { Some(r) if r.kind == RegionKind::Rom => IpaClass::Rom, Some(r) => IpaClass::Unmapped { region: Some(r.name), }, None => IpaClass::Unmapped { region: None }, }}Second, the handlers receive the bus in ExitEnv, a struct of references every handler takes, in vcpu/exit.rs. If yours still take guest memory and the policy as separate arguments, bundle them now: mem: &'a dyn GuestMemory, bus: &'a Bus, unhandled_mmio, plus whatever your hvc handler uses.
Third, your run configuration (the reference's VmConfig) gets a testdev: bool, set by a new --testdev flag. Register the device only when it is set, so earlier guests still see a hole. Type:
/// Put the devices `cfg` asks for on `bus` (one block per device).pub fn register_devices(cfg: &VmConfig, bus: &mut Bus) -> Result<()> { // The scratch-register test device, only with --testdev. if cfg.testdev { bus.insert( "testdev", TESTDEV_BASE, TESTDEV_SIZE, Arc::new(Mutex::new(TestDev::new())), ) .map_err(Error::Bus)?; } Ok(())}Create the bus in your VM setup, call register_devices before the first vCPU runs, and put &bus in the ExitEnv.
The handler and the PC-advance table
The handler fills trace fields that chapter 03's ExitRecord lacks: add wnr, size, reg, value and isv now, as Options (bool, u8, u8, u64, bool), and an Action::Mmio variant. It returns an MmioOutcome: Done, or Fatal(String) with the reason.
The handler first checks S1PTW: a guest page-table walk that hit a hole is fatal. It asks our own map what lives at the IPA (classify_ipa), never the fault code, which says how stage 2 failed, not what is there. A stage-2 fault inside RAM means our own mapping is wrong (chapter 04 maps all of RAM), so it stops. Then it builds the access, sends it to the bus, and writes a load's result. Type it, except the isv0 call:
/// Emulate the data abort `da` reported by `raw`: walk check, classify, build the access,/// route it to the bus, write a load's result. Fills the trace fields of `rec`. `pc` is/// the PC of the faulting instruction.pub fn handle( regs: &mut dyn VcpuRegs, env: &ExitEnv<'_>, raw: &hvf::VcpuExit, da: &DataAbort, pc: u64, rec: &mut ExitRecord,) -> Result<MmioOutcome> { let ipa = raw.ipa; // Every data-abort record says which kind it was, including the ones stopped below. rec.isv = Some(da.isv); if da.s1ptw { return Ok(MmioOutcome::Fatal(format!( "stage-1 table walk touched non-RAM IPA {ipa:#x} pc {pc:#x}" ))); } let class = classify_ipa(ipa, env.mem, env.bus); if class == IpaClass::Ram { return Ok(MmioOutcome::Fatal(format!( "stage-2 fault in RAM at {ipa:#x} pc {pc:#x} (dfsc {:#x})", da.dfsc ))); } let Some(access) = MmioAccess::from_data_abort(ipa, da, regs)? else { return isv0(regs, env, raw, da, pc, rec); }; rec.wnr = Some(access.write.is_some()); rec.size = u8::try_from(access.size.bytes()).ok(); rec.reg = Some(access.reg); rec.action = Some(Action::Mmio); let routed = match (class, access.write) { (IpaClass::Device { .. }, Some(v)) => env.bus.write(ipa, access.size, v).map(|()| v), (IpaClass::Device { .. }, None) => env .bus .read(ipa, access.size) .map(|v| access.load_result(v)), _ => Err(BusError::Unmapped { ipa }), }; match routed { Ok(value) => { if access.write.is_none() { regs.set_x(access.reg, value)?; // SRT = 31: XZR, discarded by set_x } rec.value = Some(value); Ok(MmioOutcome::Done)The isv0 call is chapter 21's decoder. Your else branch returns MmioOutcome::Fatal with the message data abort with ISV=0 at IPA <ipa> pc <pc>: the syndrome does not describe this access; not emulated.
The block stops after the success arm. The other arm, an unclaimed or straddling access, goes to chapter 05's unhandled-MMIO policy. Now replace chapter 05's log policy needs chapter 07 stop: for a load, set_x(reg, 0); for a store, nothing; then return Done so the PC advances. Check it from learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --raw $G/mmio-poke.bin@0x40080000 --timeout 10 --unhandled-mmio logYou should see what chapter 05 showed from the reference:
cargo run -q -p macvmm -- run --mem 64M --raw {guests}/mmio-poke.bin@0x40080000 --timeout 10 --unhandled-mmio logmmio-poke: storing 0x4d to 0xc000000mmio-poke: survivedmacvmm: warn: [vcpu0] guest: unhandled MMIO write at 0xc000000 size 4 pc 0x40081088 (ignored: --unhandled-mmio log)Print the instruction word. The ISV = 0 stop promises the word, so add it to your dump: mem.read_u32(GuestAddress(pc)), chapter 04's helper, treating the PC as an IPA. That holds for every guest so far, and for this chapter's ISV = 0 guest, whose code is identity-mapped. Print insn at pc: 0x and eight hex digits ({:#010x}), or insn at pc: not readable if the read fails. Chapter 21 adds the stage-1 walk for code that is not identity-mapped.
Who moves the PC? Chapter 02's rule: an executed call continues; a fault or an intercepted instruction (like smc) retries. Per exit, that is the PC-advance table:
| Exit | Saved PC points | The VMM, after handling it |
|---|---|---|
Hvc | after the hvc | leaves the PC alone |
Smc | at the smc (intercepted before it ran) | adds 4 |
DataAbort, emulated | at the load or store (a fault) | adds 4 |
Canceled | wherever the guest was | leaves it alone |
| a fatal stop | at the instruction | nothing: the VM stops |
The dispatcher in learner/crates/vmm/src/vcpu/exit.rs follows the table. Type its first arms, leaving out the Abort arm:
/// Handle one decoded exit (module docs, the PC-advance table). `raw` is the framework's exit/// record (ESR, IPA); `rec` is this exit's trace record, which the handler completes.pub fn handle( regs: &mut dyn VcpuRegs, env: &ExitEnv<'_>, exit: &Exit, raw: &hvf::VcpuExit, rec: &mut ExitRecord,) -> Result<ExitAction> { match *exit { Exit::Canceled => Ok(ExitAction::Resume { advance_pc: false }), Exit::Hvc { imm } => smccc_call(regs, env, Conduit::Hvc, imm, rec), Exit::Smc { imm } => smccc_call(regs, env, Conduit::Smc, imm, rec), Exit::DataAbort(da) => { let pc = regs.pc()?; match mmio::handle(regs, env, raw, &da, pc, rec)? { MmioOutcome::Done => Ok(ExitAction::Resume { advance_pc: true }), MmioOutcome::Fatal(why) => fatal(regs, env, exit, raw, rec, why), MmioOutcome::Abort { far, write } => { inject_abort(regs, env, exit, raw, rec, far, write) } } }Abort tells the guest its access failed, as real hardware would; chapter 21 adds it, so your DataAbort arm has two cases. In yours, Wfx, VtimerActivated (chapter 11), SysReg (chapter 08), InstructionAbort, Brk and Unknown share one fatal arm.
The advance is one register write. Every AArch64 instruction is 4 bytes, as the IL bit from chapter 02 promises; the open question asks what if it did not:
/// Advance the PC by one instruction (A64 instructions are 4 bytes).pub fn advance_pc(&mut self) -> Result<()> { let pc = self.pc()?; self.inner .set_reg(Reg::PC, pc.wrapping_add(4)) .map_err(hv("set PC"))}Remembering the last 256 exits
A data-abort record gains seven fields: ipa, from the exit, and the handler's wnr, size, reg, value (the masked value written or the sign-extended value loaded), action ("mmio", or "stop") and isv. The keys come in this order, with no spaces: t_ns, vcpu, reason, ec, pc, ipa, wnr, size, reg, value, action, isv. Addresses and values are "0x..." strings; size and reg are plain numbers; wnr and isv are JSON (JavaScript Object Notation) booleans. A field that is None is left out, so a stopped ISV = 0 access has only ipa, action and isv (a stopped ISV = 1 one keeps wnr, size, reg).
A new filter, --trace exits:FILE:mmio, keeps only data-abort records; implement it beside chapter 03's :hvc.
A trace file only helps if you asked for it before the crash, so every vCPU also keeps an exit ring of its last 256 records. Type:
/// One vCPU's last [`RING_CAP`] exits. A `Mutex` so that a later chapter's on-demand dump/// can read it from another thread; in practice only its vCPU locks it.#[derive(Debug, Default)]pub struct ExitRing { inner: Mutex<VecDeque<ExitRecord>>,}impl ExitRing { pub fn new() -> ExitRing { ExitRing { inner: Mutex::new(VecDeque::with_capacity(RING_CAP)), } } /// Keep `rec`, dropping the oldest record when full. pub fn push(&self, rec: ExitRecord) { let mut q = lock(&self.inner); if q.len() >= RING_CAP { q.pop_front(); } q.push_back(rec); } /// The last `n` records, oldest first. pub fn last(&self, n: usize) -> Vec<ExitRecord> { let q = lock(&self.inner); let skip = q.len().saturating_sub(n); q.iter().skip(skip).cloned().collect() }A fatal stop prints the last 32. Here is chapter 03's run loop as the reference has it now:
/// Run `vcpu` until the VM stops. Every outcome, including a framework error, ends in/// `ctl.request_stop`, so the control thread always learns why.pub fn run(vcpu: &mut Vcpu<'_>, env: &ExitEnv<'_>, obs: &Observe<'_>, log: &mut VcpuLog) { let ctl = env.ctl; loop { if ctl.is_stopping() { return; } let raw = match vcpu.run() { Ok(raw) => raw, Err(e) => { ctl.request_stop(StopReason::Vmm(e)); return; } }; let exit = Exit::from_hv(raw.reason, raw.esr); log.stats .record(&exit, raw.esr, raw.reason == hvf::ExitReason::Exception); let t_ns = obs.clock.now_ns(); let mut rec = ExitRecord::new( t_ns, vcpu.index, env.generation, &raw, &exit, vcpu.pc().ok(), ); let action = exit::handle_watched(vcpu, env, &exit, &raw, &mut rec); if let Some(trace) = obs.trace { trace.record(&rec); } log.ring.push(rec); let step = match action { Ok(ExitAction::Resume { advance_pc: true }) => vcpu.advance_pc(), Ok(ExitAction::Resume { advance_pc: false }) => Ok(()), Ok(ExitAction::Stop(StopReason::GuestFatal(mut g))) => { g.last_exits = log.ring.last(FATAL_LAST_EXITS); ctl.request_stop(StopReason::GuestFatal(g)); return; } Ok(ExitAction::Stop(reason)) => { ctl.request_stop(reason); return; } // A vCPU that powered itself off (chapter 20): park outside `hv_vcpu_run` until it is // powered on again or the VM stops. Ok(ExitAction::CpuOff) => match park(vcpu, ctl) { Some(on) => vcpu.power_on(&on), None => return, }, Err(e) => Err(e), }; if let Err(e) = step { ctl.request_stop(StopReason::Vmm(e)); return; } }}New: log.ring.push(rec) after the trace, and g.last_exits in the fatal arm, which attaches 32 records to the stop. Call your own handle where it calls handle_watched (a later hook), and leave out log.stats (chapter 11), generation and the CpuOff arm (chapter 20, where a vCPU powers itself off). Print the stop's records after the dump as last exits: N (oldest first), then each record on its own line, indented two spaces; the checkpoint looks for last exits:.
Chapter 06's self-fault now ends with the ring: the DEBUG_PUTC calls that printed its message, then the fatal abort with "action":"stop". Its PC, 0x200, is not RAM, so its word is not readable:
macvmm run --mem 64M --raw {guests}/self-fault.bin@0x40080000 --timeout 10self-fault: SCTLR_EL1.A=1, VBAR_EL1=0, loading 8 bytes from 0x40082a51macvmm: guest fatal: instruction abort at pc 0x200: translation fault at IPA 0x200 (ifsc 0x6)vcpu0: instruction abort (EC 0x20): IFSC=0x6 S1PTW=0 (translation fault) esr=0x82000006 ipa=0x200 x0=0x0000000000000000 x1=0x000000000000000a x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000002 x5=0x0000000000000008 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x0000000030000182 x9=0x0000000000000000 x10=0x0000000000000078 x11=0x0000000040082d40 x12=0x0000000000000034 x13=0x0000000040092d69 x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040092d80 x19=0x0000000040082a51 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x0000000000000000 x23=0x0000000000000000 x24=0x0000000000000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x000000004008107c sp_el0=0x0 sp_el1=0x40092e10 pc=0x200 cpsr=0x824003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x40081094 SPSR_EL1=0x800003c5 ESR_EL1=0x96000021 (EC 0x25: data abort, same EL) FAR_EL1=0x40082a51 VBAR_EL1=0x0 SCTLR_EL1=0x30000182 TCR_EL1=0x0 TTBR0_EL1=0x0 TTBR1_EL1=0x0 note: pc is VBAR_EL1 + 0x200, an exception vector: the guest took an exception at EL1 first, so ELR_EL1 and ESR_EL1 describe the first fault insn at pc: not readable (the pc does not translate to RAM)last exits: 32 (oldest first) {"t_ns":398875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":400750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":403125,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":404875,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":406666,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":413458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":415166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":418041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":419833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":422208,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":423958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":426375,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":428250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":430500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":433083,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":434958,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":437291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":439041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":441416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":443166,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":451791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":464833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":469250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":471250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":473041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":483291,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":486833,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":488625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":490416,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":492250,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x400811a4","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":495750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081124","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":498333,"vcpu":0,"reason":"exception","ec":"0x20","pc":"0x200","ipa":"0x200","action":"stop"}The run
guests/mmio-probe makes ten checks against the test device, each access in assembly so the note is exactly the one named: four sizes, write masking, xzr both ways, and three sign extensions. Run it from learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --testdev --raw $G/mmio-probe.bin@0x40080000 --trace exits:t.jsonl:mmio --timeout 10Our capture is from the checkpoint harness ({guests} is that folder, {out} a scratch one):
macvmm run --mem 64M --testdev --raw {guests}/mmio-probe.bin@0x40080000 --trace exits:{out}/t.jsonl:mmio --timeout 10mmio-probe: strb/ldrb okmmio-probe: strh/ldrh okmmio-probe: str w/ldr w okmmio-probe: str x/ldr x okmmio-probe: write masked to 1 byte okmmio-probe: str xzr stores 0 okmmio-probe: ldr xzr discarded (sp kept) okmmio-probe: ldrsb w sign-extends to 32 okmmio-probe: ldrsh x sign-extends to 64 okmmio-probe: ldrsw x sign-extends to 64 okmmio-probe: 10/10 okOne record per access; your t_ns and pc will differ slightly:
{"t_ns":241083,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810e4","ipa":"0xb000000","wnr":true,"size":1,"reg":8,"value":"0x5a","action":"mmio","isv":true}{"t_ns":251833,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810f0","ipa":"0xb000000","wnr":false,"size":1,"reg":3,"value":"0x5a","action":"mmio","isv":true}{"t_ns":339041,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008110c","ipa":"0xb000000","wnr":true,"size":2,"reg":8,"value":"0xbeef","action":"mmio","isv":true}{"t_ns":345125,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081118","ipa":"0xb000000","wnr":false,"size":2,"reg":3,"value":"0xbeef","action":"mmio","isv":true}{"t_ns":413416,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081140","ipa":"0xb000000","wnr":true,"size":4,"reg":8,"value":"0xdeadbeef","action":"mmio","isv":true}{"t_ns":418125,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081144","ipa":"0xb000000","wnr":false,"size":4,"reg":3,"value":"0xdeadbeef","action":"mmio","isv":true}{"t_ns":526916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081178","ipa":"0xb000000","wnr":true,"size":8,"reg":4,"value":"0x123456789abcdef","action":"mmio","isv":true}{"t_ns":533208,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008117c","ipa":"0xb000000","wnr":false,"size":8,"reg":3,"value":"0x123456789abcdef","action":"mmio","isv":true}{"t_ns":598500,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081198","ipa":"0xb000008","wnr":true,"size":8,"reg":20,"value":"0xffffffffffffffff","action":"mmio","isv":true}{"t_ns":602791,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400811ac","ipa":"0xb000008","wnr":true,"size":1,"reg":9,"value":"0x42","action":"mmio","isv":true}{"t_ns":606583,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400811b4","ipa":"0xb000008","wnr":false,"size":8,"reg":3,"value":"0xffffffffffffff42","action":"mmio","isv":true}{"t_ns":727875,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400811d4","ipa":"0xb000010","wnr":true,"size":8,"reg":20,"value":"0xffffffffffffffff","action":"mmio","isv":true}{"t_ns":733916,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400811dc","ipa":"0xb000010","wnr":true,"size":8,"reg":31,"value":"0x0","action":"mmio","isv":true}{"t_ns":738000,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400811e8","ipa":"0xb000010","wnr":false,"size":8,"reg":3,"value":"0x0","action":"mmio","isv":true}{"t_ns":825041,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081204","ipa":"0xb000018","wnr":true,"size":8,"reg":8,"value":"0x1111","action":"mmio","isv":true}{"t_ns":829458,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008120c","ipa":"0xb000018","wnr":false,"size":8,"reg":31,"value":"0x1111","action":"mmio","isv":true}{"t_ns":960333,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081234","ipa":"0xb000020","wnr":true,"size":1,"reg":8,"value":"0x80","action":"mmio","isv":true}{"t_ns":964958,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081238","ipa":"0xb000020","wnr":false,"size":1,"reg":3,"value":"0xffffff80","action":"mmio","isv":true}{"t_ns":1086083,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081260","ipa":"0xb000028","wnr":true,"size":2,"reg":8,"value":"0x8001","action":"mmio","isv":true}{"t_ns":1090541,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081264","ipa":"0xb000028","wnr":false,"size":2,"reg":3,"value":"0xffffffffffff8001","action":"mmio","isv":true}{"t_ns":1208083,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x4008128c","ipa":"0xb000030","wnr":true,"size":4,"reg":8,"value":"0x80000000","action":"mmio","isv":true}{"t_ns":1212875,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081290","ipa":"0xb000030","wnr":false,"size":4,"reg":3,"value":"0xffffffff80000000","action":"mmio","isv":true}Read two. The thirteenth, "wnr":true,"size":8,"reg":31,"value":"0x0", is str xzr: an 8-byte store of zero. The twentieth, "wnr":false,"size":2,"reg":3,"value":"0xffffffffffff8001", is ldrsh x3: two bytes, sign-extended. Each exit is a round trip through macOS, about 1.4 µs by chapter 03's measure, against under a nanosecond for a store to RAM; that is why Part VII's virtio devices share memory and exit once per batch.
Here are the guest's two xzr checks. The ldr xzr one compares the stack pointer before and after, to catch a VMM that maps 31 to sp. store! and load! are the probe's macros, each wrapping one asm! instruction; in(reg) lets the compiler pick the address register:
store!("str {v}, [{a}]", 16, u64::MAX);{ let a: u64 = TESTDEV + 16; // SAFETY: as `store!`: an aligned store of XZR (SRT = 31) to the test device. unsafe { asm!("str xzr, [{a}]", a = in(reg) a, options(nostack)) };}check(&mut ok, "str xzr stores 0", load!("ldr {r}, [{a}]", 16), 0);store!("str {v}, [{a}]", 24, 0x1111);let before = sp();{ let a: u64 = TESTDEV + 24; // SAFETY: as `load!`: an aligned load into XZR (SRT = 31), whose result is discarded. unsafe { asm!("ldr xzr, [{a}]", a = in(reg) a, options(nostack)) };}// A VMM that writes the loaded 0x1111 into register 31 sets HV_REG_PC; after its +4// advance the guest takes a PC alignment fault at 0x1115 and never reaches this check.// SP is compared for a VMM that maps 31 to SP instead.check(&mut ok, "ldr xzr discarded (sp kept)", sp(), before);The emulator below steps through the same path: exit record, decode, device, PC.
MMIO trap emulator
Step real guest loads and stores through chapter 07's path: the exit, the syndrome decode, the bus, the device, then PC + 4; then break it on purpose.
Runs in browserOpen full page: MMIO trap emulatorIf the lab does not load, take the trace's twentieth record and write the steps on paper: the exit record, the decode (SAS, SSE, SRT, SF, WnR), the device read at offset 0x28, the register value after sign extension, then PC + 4.
The blank note, on your Mac
guests/isv0-probe belongs to chapter 21: it turns on its own stage-1 page tables (its MMU, memory management unit), then makes pair and writeback accesses to the test device. Chapter 21 needs the MMU to test aliases; for us it changes nothing except that the PC is a virtual address, identity-mapped here. Run it from learner/:
G=../target/guests/aarch64-unknown-none/releasecargo run -q -p macvmm -- run --mem 64M --testdev --raw $G/isv0-probe.bin@0x40080000 --timeout 10Our capture is from a copy of the reference with its chapter 21 decoder replaced by this chapter's stop:
cargo run -q -p macvmm -- run --mem 64M --testdev --raw target/guests/aarch64-unknown-none/release/isv0-probe.bin@0x40080000 --timeout 10isv0-probe: mmu onmacvmm: guest fatal: data abort with ISV=0 at IPA 0xb000000 pc 0x40081234: the syndrome does not describe this access; not emulatedvcpu0: data abort (EC 0x24): ISV=0 SAS=0 (1 bytes) SSE=0 SRT=0 SF=0 AR=0 FnV=0 S1PTW=0 WnR=1 DFSC=0x6 (translation fault) esr=0x92000046 ipa=0xb000000 x0=0x0000000000000000 x1=0x0000000040083abc x2=0x0000000000000000 x3=0x0000000000000000 x4=0x0000000000000000 x5=0x0000000000000000 x6=0x0000000000000000 x7=0x0000000000000000 x8=0x000000000b000000 x9=0x1111222233334444 x10=0x5555666677778888 x11=0x0000000030001185 x12=0x000000000000ff00 x13=0x0000000000000000 x14=0x0000000000000000 x15=0x0000000000000000 x16=0x0000000000000000 x17=0x0000000000000000 x18=0x0000000040083abc x19=0x0000000000000000 x20=0x0000000000000000 x21=0x0000000000000000 x22=0x1111222233334444 x23=0x5555666677778888 x24=0x000000000b000000 x25=0x0000000000000000 x26=0x0000000000000000 x27=0x0000000000000000 x28=0x0000000000000000 x29=0x0000000000000000 x30=0x00000000400811f8 sp_el0=0x0 sp_el1=0x40098f70 pc=0x40081234 cpsr=0x800003c5 (EL1h, DAIF, Nzcv) ELR_EL1=0x0 SPSR_EL1=0x0 ESR_EL1=0x0 (EC 0x00: unknown reason) FAR_EL1=0x0 VBAR_EL1=0x40080800 SCTLR_EL1=0x30001185 TCR_EL1=0x100803519 TTBR0_EL1=0x40086000 TTBR1_EL1=0x0 insn at pc: 0xa9002909last exits: 20 (oldest first) {"t_ns":198750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":207500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":209625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":215916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":217750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":219750,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":221333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":222916,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":224500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":227791,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":231333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":233041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":234625,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":236500,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":250333,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":252458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":254458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":256458,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081b0c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":258041,"vcpu":0,"reason":"exception","ec":"0x16","pc":"0x40081a8c","imm":0,"fn":"DEBUG_PUTC","action":"smccc"} {"t_ns":260416,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x40081234","ipa":"0xb000000","action":"stop","isv":false}Exit code 3; the reason names ISV = 0, the IPA and the PC. Ignore SAS, SRT and SF on the second line: with ISV = 0 they are RES0 and mean nothing. The word 0xa9002909 is stp x9, x10, [x8], and x9 and x10 hold the two values to store. Everything a human needs, and no guess.
Breaking it on purpose
Two breaks, each predicted first, and an optional third; undo each before the next. Our runs come from edited copies of the reference, so their commands say target/guests/.... From learner/, set G first:
G=../target/guests/aarch64-unknown-none/releaseDeliberate breakage 1: delete the PC advance. In your dispatcher's data-abort arm, return Resume { advance_pc: false }. This is the page's Predict: check your journal, then run:
cargo run -q -p macvmm -- run --mem 64M --testdev --raw $G/mmio-probe.bin@0x40080000 --trace exits:t.jsonl:mmio --timeout 2cargo run -q -p macvmm -- run --mem 64M --testdev --raw target/guests/aarch64-unknown-none/release/mmio-probe.bin@0x40080000 --trace exits:t.jsonl:mmio --timeout 2macvmm: timeout: the guest was still running after --timeout 2sNo output, then the timeout (exit code 5). Read the trace's ends and length:
head -n 3 t.jsonl; tail -n 1 t.jsonl; wc -l < t.jsonlsh -c 'head -n 3 t.jsonl; tail -n 1 t.jsonl; wc -l < t.jsonl'{"t_ns":504083,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810e4","ipa":"0xb000000","wnr":true,"size":1,"reg":8,"value":"0x5a","action":"mmio","isv":true}{"t_ns":522166,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810e4","ipa":"0xb000000","wnr":true,"size":1,"reg":8,"value":"0x5a","action":"mmio","isv":true}{"t_ns":527958,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810e4","ipa":"0xb000000","wnr":true,"size":1,"reg":8,"value":"0x5a","action":"mmio","isv":true}{"t_ns":1996679333,"vcpu":0,"reason":"exception","ec":"0x24","pc":"0x400810e4","ipa":"0xb000000","wnr":true,"size":1,"reg":8,"value":"0x5a","action":"mmio","isv":true} 324719The same strb exit, 324,719 times in two seconds, only t_ns growing: a data abort's saved PC is the faulting instruction (chapter 02's retry rule), so the guest retries forever.
What you saw: (b). The misconception: "the hardware moves the PC", true only for calls. The tool: the trace, where identical records with growing t_ns mean a loop. About 160,000 exits per second, not the 700,000 that 1.4 µs suggests; probably mostly the trace, since each record is a formatted file write. The trace is tens of megabytes: rm t.jsonl.
Deliberate breakage 2: treat SRT = 31 as a real register. In your Reg::x, change n <= 30 to n <= 31, and in from_data_abort remove the reg == 31 test. Predict which checks fail, and the first failure's "got" value. Run mmio-probe without the trace:
cargo run -q -p macvmm -- run --mem 64M --testdev --raw target/guests/aarch64-unknown-none/release/mmio-probe.bin@0x40080000 --timeout 10mmio-probe: strb/ldrb okmmio-probe: strh/ldrh okmmio-probe: str w/ldr w okmmio-probe: str x/ldr x okmmio-probe: write masked to 1 byte okmmio-probe: FAILED: str xzr stores 0: got 0x400811dc, want 0x0guest exception: kind=4 (sync, EL1h) esr=0x8a000000 ec=0x22 elr=0x1115 far=0x1115macvmm: guest exit code 228str xzr stored 0x400811dc, its own address: register 31 in hv_reg_t is the PC. Then ldr xzr loaded 0x1111 into the PC, we added 4, and the guest landed at 0x1115. Its own handler reported a PC alignment fault (EC 0x22; kind=4 is its label for a synchronous exception at EL1), and it exited with failure, our exit code 6 (chapter 03).
What you saw: a zero turned into an address, then a jump. The misconception: "register 31 is a register". The tool: a probe in which each check isolates one field.
Deliberate breakage 3 (optional): emulate ISV = 0 by guessing. In your ISV = 0 else branch, build the access as if the note were valid: 8 bytes, a 64-bit register, whatever SRT holds. Rerun isv0-probe (a "stage-1 alias" is the device through a second virtual address). Predict: crash, or not?
cargo run -q -p macvmm -- run --mem 64M --testdev --raw target/guests/aarch64-unknown-none/release/isv0-probe.bin@0x40080000 --timeout 10isv0-probe: mmu onisv0-probe: FAILED: stp x: got [0, 0], want [1111222233334444, 5555666677778888]isv0-probe: FAILED: ldp x: got [0, 0], want [a1, a2]isv0-probe: FAILED: stp w: got [0], want [123456780badf00d]isv0-probe: FAILED: ldp w: got [ffffffffffffffff, ffffffffffffffff], want [cafebabe, 87654321]isv0-probe: FAILED: ldpsw: got [0, 0], want [ffffffff80000001, 7fffffff]isv0-probe: FAILED: stp x pre-index: got [0, 0, b000000], want [5555666677778888, 1111222233334444, b000040]isv0-probe: FAILED: ldp x post-index: got [0, 0, b000050], want [b1, b2, b000040]isv0-probe: FAILED: stp w post-index: got [0, 0, b000060], want [c1, c2, b000068]isv0-probe: FAILED: ldp w pre-index: got [0, 0, b000068], want [d1, d2, b000070]isv0-probe: FAILED: ldpsw pre-index: got [0, 0, b000088], want [fffffffffffffffe, ffffffff80000000, b000080]isv0-probe: FAILED: str x pre-index: got [40098f7c, b000088], want [e1e2e3e4e5e6e7e8, b000090]isv0-probe: FAILED: ldrsh x post-index: got [0, b000098], want [ffffffffffff8001, b00009a]isv0-probe: FAILED: ldp x via stage-1 alias: got [0, 0], want [f1, f2]isv0-probe: FAILED: stp x [sp]! at EL1t: got [0, 0, b0000c0], want [5151, 5252, b0000b0]isv0-probe: FAILED: ldp x [sp], #16 at EL1h: got [b0000d8, 62, b0000d0], want [6161, 6262, b0000e0]isv0-probe: FAILED: ldp x with pc via stage-1 code alias: got [7272, b0000e8], want [7171, 7272]isv0-probe: 0/16 okisv0-probe: FAILED: simd store: esr 0x0 far 0x0 value 0x40081040Exit code 0 says nothing; read the lines. Ignore the last, the SIMD store (chapter 21). The other sixteen are all wrong. SRT read 0 on this Mac: with ISV = 0 the field is RES0, so whatever it holds means nothing, and here it happened to be 0. So stores wrote x0, and loads went to x0.
What you saw: silent corruption that only the guest's checks noticed. The misconception: "MMIO emulation means emulating instructions", or guessing them. The tool: this chapter's rule, stop and print the word. Undo the edit.
Your turn
Before the checkpoint, check:
cargo test -p vmmpasses inlearner/, including your own test thatExit::decodereturns something for0,u64::MAXand a few values in between.- The
mmio-probecommand from "The run" printsmmio-probe: 10/10 ok. - The
isv0-probecommand exits with code 3; standard error startsmacvmm: guest fatal: data abort with ISV=0, and the dump includes aninsn at pc:line. - Your journal has the Predict entry, written before breakage 1.
Stuck? scripts/learner hint 07 gives four graded hints.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 07You should see, as the last line:
CHECKPOINT 07 PASSIt runs the contract tests (about 70 syndromes with expected decodes, plus the million-value sweep), runs mmio-probe and checks its output and trace, re-runs self-fault looking for last exits:, and checks your journal. Ours ran against the reference, so its journal line says "not checked":
scripts/checkpoint.sh 07checkpoint: implementation <tree>[PASS] contract tests esr_vectors (2 tests)[PASS] runs on your Mac mmio-probe: 5/5 serial markers, 8/8 trace markers, exit 0 in 0.06s[PASS] runs on your Mac self-fault: 6/6 serial markers, exit 3 in 0.01s[INFO] journal not checked (not a learner tree)CHECKPOINT 07 PASSWhat now works:
- every exit becomes one
Exitvalue, from a pure decoder that cannot panic; - a guest can load and store to a device at four sizes, with sign extension and
xzr, and carry on; - an access the hardware could not describe stops the VM with the instruction word;
- the trace records each access, and a fatal stop shows the exits that led to it.
The next chapter starts from this state (tag ch-07, the reference at the end of chapter 07).
What's next
A guest kernel also touches system registers, and Hypervisor.framework forwards some of those accesses: chapter 08 decides what to answer, injects the exception real hardware would raise for a register we lack, and gives the guest a standard way to power off.
Open question
After emulating a store, you advance the PC by 4. What does the IL bit tell you, and what would you do if it ever said the instruction was 16 bits long?
Spec hunt
- ARM ARM (DDI 0487), register page ESR_EL2, "ISS encoding for an exception from a Data Abort": in which cases does the manual say ISV is 0, and which of them could a guest kernel reach by accident?
- The same page, the description of IL: for which exception classes is IL fixed at 1, and when can it be 0?
- The software development kit (SDK) header
hv_vcpu_types.h, thehv_reg_tenumeration: which values followHV_REG_PC, and which of them could a 5-bit SRT field never name? Why is 31, and only 31, the dangerous number?