Chapter 02 · Part I
An exception, one level up: your first VM exit
Course progress: chapter 02 is 3 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 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Your doctor prints
hv_vm_create: HV_BUSY (0xfae94002). What is the most likely cause in your own code?Show answer
A VM already exists in this process: Hypervisor.framework allows one per process. Usually an earlier
Vmis still alive, or was dropped withoutDropcallinghv_vm_destroy.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
hv_vm_createreturns0xfae94009, a code yourHvErrordoes not list. What shouldHvError::from_codereturn, and why not a generic "unknown error"?Show answer
HvError::Unknown(0xfae94009). The exact value is the evidence a bug report needs, and a newer macOS may add codes;Displaystill prints it in full.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A freshly built
macvmm, run without the signing runner, getsHV_DENIED (0xfae94007). Is that a link problem? What fixes it?Show answer
No: the program linked and started; the kernel refused at the call because the signature has no
com.apple.security.hypervisor. Run it throughcargo run(the runner signs a copy first) or sign it withscripts/sign.sh.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest stores a byte to
0x0900_0000, where nothing is mapped. Which layer decides that this access leaves the guest, and which decides what it means?Show answer
The macOS kernel's EL2 part decides it stops the guest and forwards it (a VM exit); our VMM, an ordinary EL0 process, decides what it means, by playing the device at that address.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Inside an
unsafeblock you index a slice out of bounds. What happens, and what does that tell you aboutunsafe?Show answer
It still panics: bounds checks on safe indexing stay on, as do type and borrow checks.
unsafeonly allows a few extra operations (such as calling an FFI function); the invariants those operations need become yours.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
The header declares
hv_return_t hv_vm_get_max_vcpu_count(uint32_t *max_vcpu_count);. What is the Rust parameter type, and who owns the memory it points to?Show answer
*mut u32. It is an out-pointer: the caller owns a live, writableu32(for example a local variable) and passes its address; the function writes the answer there and returns only an error code.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Why does
hv_vm_destroytake no argument at all?Show answer
There is no handle to pass: the VM belongs to the whole process, and there can be only one, so "destroy the VM" is unambiguous.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
At which exception level does
macvmmitself run, and at which does the guest kernel run?Show answer
macvmmruns at EL0, like any app. The guest kernel runs natively at EL1. The level above both, EL2, belongs to part of the macOS kernel.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest reads the clock counter with
mrs x0, CNTVCT_EL0a million times. How many of those reads reach our VMM?Show answer
None: the hardware virtualizes the counter, so the read completes inside the guest without any exit.
From chapter 00: Two kernels, one Mac: what a virtual machine is
A guest runs 1,000 instructions under trap-and-emulate; 6 of them are privileged or touch the console. Roughly how many instructions does the VMM handle for it, and what does the processor do with the rest?
Show answer
About 6, one per trap. The other 994 run natively on the real processor, unseen by the VMM; only an emulator handles every instruction.
From chapter 00: Two kernels, one Mac: what a virtual machine is
An instruction reads the current privilege mode and, in user mode, answers "user" without trapping. Is it sensitive, privileged, both or neither, and why does that break trap-and-emulate?
Show answer
Sensitive (it reads state the VMM must control) but not privileged (it does not trap). Nothing traps, so the VMM never gets a turn to supply the virtual answer "kernel", and the guest kernel acts on the truth: it is in user mode.
From chapter 00: Two kernels, one Mac: what a virtual machine is
You must run an unmodified guest on a processor that has sensitive, unprivileged instructions and no hardware assist. Which strategies are open to you, and which is not?
Show answer
Interpretation (slow but correct) and binary translation (rewrite the bad instructions just before they run). Paravirtualization is not: it needs the guest's source changed.
From chapter 00: Two kernels, one Mac: what a virtual machine is
A kernel copied into an ordinary process stores to the console's address. Which ledger row is that, and what does a VMM using trap-and-emulate do to make it work?
Show answer
Row 3, devices at fixed addresses. The VMM leaves the address unmapped, so the store traps; the VMM plays the device's part (prints the character) and resumes the guest after the store.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Under hardware assist, why does the guest kernel's "am I in kernel mode?" check pass, when it failed under plain trap-and-emulate?
Show answer
The guest kernel now runs in a real kernel mode, below a new, more privileged level that the VMM's side controls, so the honest answer is "kernel". The level above traps only what it was told to watch.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Before hardware help for memory, how did a VMM stop a guest kernel from mapping memory that is not its own, and what did that cost?
Show answer
With shadow page tables: real tables the VMM keeps, mapping guest addresses straight to host memory, kept in step by trapping every guest write to its own page tables. Every such write cost a trap; a second hardware translation stage removed them.
From chapter 00: Two kernels, one Mac: what a virtual machine is
Someone says "QEMU is a hypervisor". How does this course say the same thing, and which part of a Mac is the course's "hypervisor"?
Show answer
QEMU is a VMM (with its own emulator when no hardware assist is used). In this course the hypervisor is only the part at a level more privileged than the kernel's that controls the processor's support for virtual machines; on a Mac, a part of macOS, not our program.
From chapter 00: Two kernels, one Mac: what a virtual machine is
scripts/doctor.shprintsdoctor: hv_vm_create: OK. What has this proved about the Mac and the probe process?Show answer
The processor has the hardware-assisted level, macOS offers it, and this process (signed with the one permission it needs) was allowed to create a virtual machine.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Your doctor prints
hv_vm_create: HV_BUSY (0xfae94002). What is the most likely cause in your own code?Show answer
A VM already exists in this process: Hypervisor.framework allows one per process. Usually an earlier
Vmis still alive, or was dropped withoutDropcallinghv_vm_destroy.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
hv_vm_createreturns0xfae94009, a code yourHvErrordoes not list. What shouldHvError::from_codereturn, and why not a generic "unknown error"?Show answer
HvError::Unknown(0xfae94009). The exact value is the evidence a bug report needs, and a newer macOS may add codes;Displaystill prints it in full.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A freshly built
macvmm, run without the signing runner, getsHV_DENIED (0xfae94007). Is that a link problem? What fixes it?Show answer
No: the program linked and started; the kernel refused at the call because the signature has no
com.apple.security.hypervisor. Run it throughcargo run(the runner signs a copy first) or sign it withscripts/sign.sh.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest stores a byte to
0x0900_0000, where nothing is mapped. Which layer decides that this access leaves the guest, and which decides what it means?Show answer
The macOS kernel's EL2 part decides it stops the guest and forwards it (a VM exit); our VMM, an ordinary EL0 process, decides what it means, by playing the device at that address.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Inside an
unsafeblock you index a slice out of bounds. What happens, and what does that tell you aboutunsafe?Show answer
It still panics: bounds checks on safe indexing stay on, as do type and borrow checks.
unsafeonly allows a few extra operations (such as calling an FFI function); the invariants those operations need become yours.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
The header declares
hv_return_t hv_vm_get_max_vcpu_count(uint32_t *max_vcpu_count);. What is the Rust parameter type, and who owns the memory it points to?Show answer
*mut u32. It is an out-pointer: the caller owns a live, writableu32(for example a local variable) and passes its address; the function writes the answer there and returns only an error code.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
Why does
hv_vm_destroytake no argument at all?Show answer
There is no handle to pass: the VM belongs to the whole process, and there can be only one, so "destroy the VM" is unambiguous.
From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
At which exception level does
macvmmitself run, and at which does the guest kernel run?Show answer
macvmmruns at EL0, like any app. The guest kernel runs natively at EL1. The level above both, EL2, belongs to part of the macOS kernel.From chapter 01: Where our VMM sits: Hypervisor.framework and a hand-written FFI
A guest reads the clock counter with
mrs x0, CNTVCT_EL0a million times. How many of those reads reach our VMM?Show answer
None: the hardware virtualizes the counter, so the read completes inside the guest without any exit.
Concepts you'll need
Chapters before this one: chapter 01, Where our VMM sits: Hypervisor.framework and a hand-written FFI.
- Core, taught here: exception levels EL0 to EL3 and who sits at EL2 on a Mac; the exception registers (
ELR,SPSR,ESRwith its EC, IL and ISS fields,FAR,VBAR) and the exception vector table; synchronous versus asynchronous exceptions; routing; the preferred return address (a call continues, a fault retries); the exit of a virtual machine (a VM exit) as an exception taken to EL2 and forwarded to us; reading the PSTATE value0x3c5with a field table (chapter 06 builds such values yourself). - Core, from earlier: hardware assist and the toy machine (chapter 00); the macOS stack and its two supervisors (chapter 01);
HvError,check,Vmand the foreign function interface (FFI) pattern (chapter 01). - Primers (read first):
aarch64-reading(registers,x0as the result register, 32-bit instruction words, the fields ofmovz,hvcandb, byte order);os-basics(a system call at the hardware level, the exception vector table). - Pointers: nested virtualization (an Aside). For the curious: the page-granules, reading-specs and host-concurrency primers.
- Forward definitions: IPA (intermediate physical address); the stage-2 mapping; the 16 KiB host page; page-aligned memory from
hv_vm_allocate; why RAM starts at0x4000_0000; thread;SP_EL1, EL1h and DAIF; data abort and instruction abort. Each is defined at first use.
Here is a whole program, three instructions long: put 42 in register x0, call the level above with hvc, then loop forever. You will run it inside a virtual machine on your Mac. When the guest reaches the hvc, the call that started it, hv_vcpu_run, returns to the virtual machine monitor (VMM) you are building, with a note. One number on it decides how every exit handler you write behaves: the guest's program counter (PC), the address of the instruction it will run next. Does it still point at the hvc, or has it moved past it?
Predict The program starts at 0x4000_0000 (the underscore only separates digits, as in Rust; programs print 0x40000000), so the hvc is at 0x40000004. After the exit, will the guest's PC read 0x40000004 (at the hvc) or 0x40000008 (after it)?
Write your answer and one sentence of reasoning under ## Predict in your journal. Sitting A gives you the rule that decides it; sitting B runs it.
This chapter opens row 1 of chapter 00's problem ledger, the CPU: by its end, guest instructions run natively and stop where we asked. Sitting A is exceptions on paper and in the browser, no Mac needed (about 2 hours); sitting B is your first run, at your Mac (about 3.5 hours).
Objectives: by the end you can
- (Sitting A) Before the registers are named, list what a kernel needs to know when an app runs
svc #0(from where, why, where to return, in which mode); then match each item toELR_EL1,SPSR_EL1,ESR_EL1orFAR_EL1, and say whatVBAR_EL1is for. - (Sitting A) Explain "the same thing, one level up":
hvcis thesvcof EL1, the software at EL2 owns the vector table there, andhv_vcpu_runreturns when the guest takes an exception that Hypervisor.framework forwards. - (Sitting A) For
svc,hvc, a faulting load and a timer interrupt, say whether each is synchronous or asynchronous and where the saved PC points, using the call-versus-retry rule. - (Sitting B) Declare the virtual CPU (vCPU) and mapping functions from the SDK (software development kit) headers, map one 16 KiB page of guest RAM at guest address
0x4000_0000, place three given instruction words, set the PC and the PSTATE value the lesson explains field by field, and run. - (Sitting B) Extract the exception class from the syndrome (
ESR >> 26), identify0x16as anhvcfrom the Arm manual's table, and predict, then observe, the PC after the exit.
Before you start. From the repository root, run scripts/learner start 02. It copies this chapter's journal to learner/journal/02.md, "your journal" below. In sitting B, type each code block into your workspace, learner/, and run your program from inside it; the repository root holds the finished reference, so a run there proves nothing about your code.
Watch an app call its kernel
Open the stepper below, choose source EL0, cause svc, and step once. The app is running at EL0, Arm's name for the least privileged level, where ordinary programs live (chapter 01's stack). It executes svc #0, the instruction an app uses to ask its kernel for a service (the os-basics primer).
Watch the PC jump somewhere new, the mode change, and three boxes, still unnamed, fill with values. Then press ERET (exception return): the PC and mode snap back, the PC one instruction on; the boxes keep their values.
Exception stepper
Pick where the code runs and what happens, take the exception, watch what the CPU saves, then return with ERET.
Runs in browserOpen full page: Exception stepperLoading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.
If the lab does not load, here is what it shows, for svc and for the "data abort" cause used later (the app's code at 0x1000, the kernel's table of handlers at 0x8000):
cause: svc #0 at 0x1000 before after the step PC 0x1000 0x8400 (table + 0x400) mode EL0 EL1 saved return address ? 0x1004 (after the svc) saved mode ? EL0 and its flags reason ? svc, number 0 fault address ? ? (not a fault)cause: data abort, a load at 0x1000 from an address with nothing behind it PC 0x1000 0x8400 (table + 0x400) mode EL0 EL1 saved return address ? 0x1000 (the load itself) saved mode ? EL0 and its flags reason ? data abort fault address ? the address the load usedERET: PC = saved return address, mode = saved mode.What the kernel needs to know
You are the kernel, and an app has knocked. What must you find out? Write your list before reading on; it is journal question 2.
Most lists contain four things: why the app came, where to go back to, what state it was in (which level, which flags), and, if something went wrong, which address was involved. On Arm each answer has its own register, written by the hardware as it changes the mode. The suffix _EL1 says the register belongs to EL1, the level that receives the exception:
| You need | Register | In the stepper |
|---|---|---|
| where to go back to | ELR_EL1, the Exception Link Register: the saved return address | "saved return address" |
| the state to go back to | SPSR_EL1, the Saved Program Status Register: the old mode and flags | "saved mode" |
| why it came | ESR_EL1, the Exception Syndrome Register | "reason" |
| which address, for faults only | FAR_EL1, the Fault Address Register | "fault address" |
The CPU's current mode and flags live in PSTATE (processor state). SPSR_EL1 is a snapshot of PSTATE taken at the exception, so ERET can restore it. Hypervisor.framework calls the same value CPSR (current program status register), an older Arm name.
Where the CPU goes: the vector table
Long before any app ran, the kernel wrote the address of its exception vector table (the table of handler entry points from the os-basics primer) into VBAR_EL1, the Vector Base Address Register. The CPU picks an entry at an offset set by the kind of exception and where it came from: an svc from EL0 lands at VBAR_EL1 + 0x400, and a synchronous exception at EL1 itself lands at VBAR_EL1 + 0x200, when the kernel runs on its own stack pointer, as ours will (sitting B's PSTATE table). Chapter 06 draws all sixteen entries, and chapter 08 uses them.
Calls continue, faults retry
Now the rule behind the opening puzzle. Recall from the aarch64-reading primer that the PC holds the address of the instruction being executed, and every Arm instruction is 4 bytes long. The saved return address cannot always be "the next instruction".
For a call, the caller wants to continue after it; for a fault, the faulting instruction must be retried once the cause is fixed.
So after an svc, ELR_EL1 holds the address after the svc. After a load that faulted (say the page was not in memory yet), it holds the address of the load itself, so the kernel can bring the page in and run the load again. The Arm Architecture Reference Manual (the ARM ARM, Arm's rulebook) calls this saved value the preferred return address, and defines it per kind of exception. The stepper's "data abort" cause shows the second case: a data abort is Arm's name for a load or store that faulted.
A third case comes from outside the program: a timer or a device signals an interrupt. The saved address is the first instruction not yet run, so the program carries on unharmed.
Reading the reason: the syndrome
ESR packs the reason, the syndrome, into 32 bits. Its top six bits, 31 to 26, are the exception class (EC): the kind of exception. Bit 25 is IL, the instruction length, 1 for a 32-bit instruction, which on 64-bit Arm is always. The low 25 bits are the instruction-specific syndrome (ISS), whose meaning depends on the class. For a call such as svc or hvc, the low 16 bits of the ISS hold the number written in the instruction.
31 26 25 24 0+------------+----+--------------------------------------+| EC | IL | ISS |+------------+----+--------------------------------------+ 0x5a000000 = 0101 10 | 1 | 0 0000 ... 0000 EC = 0b010110 = 0x16, IL = 1, ISS = 0The syndrome 0x5a000000 split into its fields: shift right by 26 to get EC.
Which class is 0x16? Open the ARM ARM (free from Arm's developer site, document DDI 0487) and search for the register page ESR_EL2, Exception Syndrome Register (EL2). Find the field EC and its table of values. The row for 0b010110 reads "HVC instruction execution in AArch64 state". That is your first look at the primary source. Notice the page: ESR_EL2, not ESR_EL1. The next section says why.
The same thing, one level up
Everything so far happened between an app at EL0 and a kernel at EL1. Arm stacks four exception levels: EL0 for apps, EL1 for a kernel, EL2 for the software that supervises kernels, and EL3 for firmware (which we never touch). Higher number, more power.
A guest kernel is an ordinary kernel at EL1, and it calls the level above the way an app does. hvc (hypervisor call) is the svc of EL1: an exception taken to EL2. A guest access to memory our VMM has not given it is the page fault of EL1, taken to EL2 instead of to the guest's own kernel (chapter 05 calls the gap it hits a stage-2 hole). And EL2 has its own copies of the registers: ELR_EL2, SPSR_EL2, ESR_EL2, VBAR_EL2.
Who sits at EL2 on a Mac? Not us: chapter 01's stack put the macOS kernel's virtualization part there. It owns VBAR_EL2, receives the hvc, and handles or forwards it. Our VMM runs the guest by calling hv_vcpu_run from one of its threads (a thread is an independent flow of execution inside a process), and that call runs one virtual CPU, a vCPU. When EL2 forwards an exception, the call returns, carrying the guest's ESR_EL2 value as the "syndrome". That forwarded stop is a VM exit, never to be confused with the exit code macvmm returns to the shell.
Aside
EL2 can also be offered to the guest, so a guest can be a hypervisor itself: nested virtualization. The switch is hv_vm_config_set_el2_enabled in the SDK header hv_vm_config.h; the ARM ARM's chapter on the EL2 exception model describes what such a guest sees. This chapter's open question uses it.
Two kinds, two destinations
Ask two independent questions of any exception. Was it caused by the running instruction (synchronous: svc, hvc, a fault), or by something outside it (asynchronous: a timer, an interrupt, or our VMM stopping the vCPU from another thread, which arrives with its own exit reason, chapter 09)? And which level takes it: the guest's kernel at EL1, through its own vector table, or EL2, through Apple's? That choice is the exception's routing, and EL2's software configures it.
| Event, in the guest | Kind | Saved PC points | Taken at |
|---|---|---|---|
svc from a guest app | synchronous | after the svc | EL1, the guest kernel |
hvc from the guest kernel | synchronous | after the hvc | EL2, then maybe to us |
| a load the guest's own page tables cannot translate | synchronous | at the load | EL1, the guest kernel |
| a timer interrupt | asynchronous | the next instruction not yet run | depends on routing (chapters 11 and 12) |
Most exceptions never leave the guest. Only those routed to EL2 can become VM exits.
Retiring the toy
Chapter 00's toy machine retires here, beside the real thing:
| Toy machine (chapter 00) | Arm, from now on | Where the toy was wrong |
|---|---|---|
| user mode | EL0 | |
| kernel mode | EL1 | |
| "hardware assist" mode | EL2 | on a Mac, the software at EL2 is Apple's, not ours |
| (none) | EL3, the firmware's level, unused by us | Arm has four levels; the toy had two or three |
| "trap" | an exception taken to a higher EL | the real trap leaves why (ESR) and where to return (ELR) in registers |
Good place to stop. Sitting B needs your Mac, your learner workspace and about 3.5 hours.
hv_vcpu_run is a system call
One sentence carries all of sitting B: hv_vcpu_run is a system call; our thread enters the macOS kernel, the kernel runs the guest on this CPU core, and when the guest takes an exception that the kernel's EL2 part chooses to forward, the call returns to us with the reason.
our thread (EL0) macOS kernel (EL1, EL2 part) guest (EL1) ---------------- ---------------------------- ----------- hv_vcpu_run(vcpu) -------> load the guest's registers, (blocked) enter the guest ------------------> movz x0, #0x2a hvc #0 exception taken to EL2 <---------- (stops here) forward it? yes returns HV_SUCCESS <------ write the exit record read reason, syndromeWhile the guest runs, our thread waits inside the kernel.
Declaring the vCPU functions
A vCPU is one guest CPU: a set of registers that Hypervisor.framework loads onto a real core when you call hv_vcpu_run. As chapter 01 did for hv_vm_create, open hv_vcpu.h and hv_vcpu_types.h and declare what we need in learner/crates/hvf/src/ffi.rs, checking each line against the header. First the plain types (keep those you have):
/// `hv_ipa_t` (`hv_vm_types.h`): an intermediate physical (guest physical) address.pub type hv_ipa_t = u64;/// `hv_memory_flags_t` (`hv_kern_types.h`): `HV_MEMORY_*` bits for map and protect.pub type hv_memory_flags_t = u64;/// `hv_allocate_flags_t` (`hv_vm_allocate.h`).pub type hv_allocate_flags_t = u64;/// `hv_vm_config_t` (`hv_vm_types.h`): opaque OS object, release with [`os_release`].pub type hv_vm_config_t = *mut c_void;/// `hv_vcpu_config_t` (`hv_vcpu_types.h`): opaque OS object, release with [`os_release`].pub type hv_vcpu_config_t = *mut c_void;The vCPU's types and the four exit reasons, whose values the checkpoint compares with the header:
/// `hv_vcpu_t`: a small integer on arm64 (`uint64_t`; on x86 it is `unsigned`).pub type hv_vcpu_t = u64;/// `hv_exit_reason_t` (`OS_ENUM(..., uint32_t, ...)`).pub type hv_exit_reason_t = u32;/// `hv_exception_syndrome_t`: the guest's ESR_EL2 value for the exit.pub type hv_exception_syndrome_t = u64;/// `hv_exception_address_t`: the guest's FAR_EL2 value for the exit.pub type hv_exception_address_t = u64;pub const HV_EXIT_REASON_CANCELED: hv_exit_reason_t = 0;pub const HV_EXIT_REASON_EXCEPTION: hv_exit_reason_t = 1;pub const HV_EXIT_REASON_VTIMER_ACTIVATED: hv_exit_reason_t = 2;pub const HV_EXIT_REASON_UNKNOWN: hv_exit_reason_t = 3;The five functions this chapter calls:
// hv_vcpu.h (macOS 11.0). Unless noted, "must be called by the owning thread"./// Creates a vCPU *for the calling thread*. `*exit` receives a framework-owned pointer that/// every `hv_vcpu_run` rewrites. `config` is `_Nullable`.pub fn hv_vcpu_create( vcpu: *mut hv_vcpu_t, exit: *mut *mut hv_vcpu_exit_t, config: hv_vcpu_config_t,) -> hv_return_t;pub fn hv_vcpu_destroy(vcpu: hv_vcpu_t) -> hv_return_t;pub fn hv_vcpu_get_reg(vcpu: hv_vcpu_t, reg: hv_reg_t, value: *mut u64) -> hv_return_t;pub fn hv_vcpu_set_reg(vcpu: hv_vcpu_t, reg: hv_reg_t, value: u64) -> hv_return_t;pub fn hv_vcpu_run(vcpu: hv_vcpu_t) -> hv_return_t;The register numbers; we use X0, PC and CPSR:
/// `hv_reg_t`: general-purpose and special registers for `hv_vcpu_{get,set}_reg`.pub type hv_reg_t = u32;pub const HV_REG_X0: hv_reg_t = 0;pub const HV_REG_X1: hv_reg_t = 1;pub const HV_REG_X2: hv_reg_t = 2;pub const HV_REG_X3: hv_reg_t = 3;pub const HV_REG_X4: hv_reg_t = 4;pub const HV_REG_X5: hv_reg_t = 5;pub const HV_REG_X6: hv_reg_t = 6;pub const HV_REG_X7: hv_reg_t = 7;pub const HV_REG_X8: hv_reg_t = 8;pub const HV_REG_X9: hv_reg_t = 9;pub const HV_REG_X10: hv_reg_t = 10;pub const HV_REG_X11: hv_reg_t = 11;pub const HV_REG_X12: hv_reg_t = 12;pub const HV_REG_X13: hv_reg_t = 13;pub const HV_REG_X14: hv_reg_t = 14;pub const HV_REG_X15: hv_reg_t = 15;pub const HV_REG_X16: hv_reg_t = 16;pub const HV_REG_X17: hv_reg_t = 17;pub const HV_REG_X18: hv_reg_t = 18;pub const HV_REG_X19: hv_reg_t = 19;pub const HV_REG_X20: hv_reg_t = 20;pub const HV_REG_X21: hv_reg_t = 21;pub const HV_REG_X22: hv_reg_t = 22;pub const HV_REG_X23: hv_reg_t = 23;pub const HV_REG_X24: hv_reg_t = 24;pub const HV_REG_X25: hv_reg_t = 25;pub const HV_REG_X26: hv_reg_t = 26;pub const HV_REG_X27: hv_reg_t = 27;pub const HV_REG_X28: hv_reg_t = 28;pub const HV_REG_X29: hv_reg_t = 29;pub const HV_REG_FP: hv_reg_t = HV_REG_X29;pub const HV_REG_X30: hv_reg_t = 30;pub const HV_REG_LR: hv_reg_t = HV_REG_X30;pub const HV_REG_PC: hv_reg_t = 31;pub const HV_REG_FPCR: hv_reg_t = 32;pub const HV_REG_FPSR: hv_reg_t = 33;pub const HV_REG_CPSR: hv_reg_t = 34;hv_vcpu_create has two out-pointers. The first receives the vCPU's id. The second receives a pointer to an exit record that the framework rewrites on every run; it is the repr(C) struct from chapter 01's layout lab:
/// `hv_vcpu_exit_exception_t`: what the guest did, as the hardware reported it to EL2.#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct hv_vcpu_exit_exception_t { /// ESR_EL2 (ARM ARM, ESR_EL2 register description): EC in bits 31:26, IL in 25, ISS in /// 24:0. pub syndrome: hv_exception_syndrome_t, /// FAR_EL2: the faulting guest *virtual* address, when the EC defines one. pub virtual_address: hv_exception_address_t, /// The faulting IPA, page offset included (checked on a real Mac). pub physical_address: hv_ipa_t,}/// `hv_vcpu_exit_t`: written by the framework on every `hv_vcpu_run`. 32 bytes; `reason` at 0,/// 4 bytes of padding, then the exception at 8 (syndrome 8, FAR 16, IPA 24).#[repr(C)]#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct hv_vcpu_exit_t { pub reason: hv_exit_reason_t, pub exception: hv_vcpu_exit_exception_t,}It is 32 bytes: reason at offset 0, four bytes of padding, then the syndrome at 8, the guest's virtual fault address (its FAR) at 16, and the guest-physical address (an IPA, defined below) at 24. The checkpoint checks your layout.
A vCPU that cleans up after itself
A thread has its own registers, and the header says hv_vcpu_create makes a vCPU "for the current thread", whose other calls "must be called by the owning thread". It does not say why (likely the kernel keeps the vCPU's state with that thread). So the creating thread runs it. The wrapper in learner/crates/hvf/src/vcpu.rs makes this a compile-time fact: Vcpu is not Send (Rust's mark for types that may move to another thread), and the doc-comment test proves the compiler refuses:
/// A vCPU, owned by the thread that created it. It is neither `Send` nor `Sync` (it cannot be/// moved to or shared with another thread) and it borrows the [`Vm`] (it cannot outlive it).#[derive(Debug)]pub struct Vcpu<'vm> { id: ffi::hv_vcpu_t, /// Framework-owned; valid until `hv_vcpu_destroy`. Read only with `read_volatile`. exit: *const ffi::hv_vcpu_exit_t, _vm: PhantomData<&'vm Vm>, /// Explicit `!Send + !Sync` marker (the raw pointer above already implies it). _not_send: PhantomData<*const ()>,}/// A `Vcpu` cannot be sent to another thread:////// ```compile_fail,E0277/// fn assert_send<T: Send>() {}/// assert_send::<hvf::Vcpu<'static>>();/// ```#[cfg(doctest)]pub mod vcpu_not_send {}Creating one wraps the call in chapter 01's check, which turns a return code into a Result:
/// Create a vCPU for the calling thread. A thread may own only one vCPU at a time (a second/// create returns `HV_BUSY`; checked on a real Mac).////// `vm` is not passed to the framework (the VM is per process); taking the borrow is what/// ties the vCPU's lifetime to the VM's.pub fn create(vm: &'vm Vm) -> Result<Vcpu<'vm>, CallError> { let _borrow: &'vm Vm = vm; let mut id: ffi::hv_vcpu_t = 0; let mut exit: *mut ffi::hv_vcpu_exit_t = core::ptr::null_mut(); // SAFETY: both out-parameters are live locals; a NULL config means "default", which the // header allows (`_Nullable`). A VM exists because we borrow `vm`. check("hv_vcpu_create", unsafe { ffi::hv_vcpu_create(&mut id, &mut exit, core::ptr::null_mut()) })?; if exit.is_null() { // Never observed; refuse rather than read through NULL later. Destroy on this, // the owning, thread. // SAFETY: `id` was just created by this thread and is destroyed once. let _ = unsafe { ffi::hv_vcpu_destroy(id) }; return Err(CallError { call: "hv_vcpu_create", error: HvError::Error, }); } Ok(Vcpu { id, exit, _vm: PhantomData, _not_send: PhantomData, })}Registers by name, and a Drop that destroys the vCPU on its own thread:
/// Read a general-purpose or special register.pub fn get_reg(&self, reg: Reg) -> Result<u64, CallError> { let mut v = 0u64; // SAFETY: owning thread; live out-parameter; the framework validates `reg`. check("hv_vcpu_get_reg", unsafe { ffi::hv_vcpu_get_reg(self.id, reg.0, &mut v) })?; Ok(v)}/// Write a general-purpose or special register.pub fn set_reg(&self, reg: Reg, value: u64) -> Result<(), CallError> { // SAFETY: owning thread; plain values. check("hv_vcpu_set_reg", unsafe { ffi::hv_vcpu_set_reg(self.id, reg.0, value) })}impl Drop for Vcpu<'_> { fn drop(&mut self) { // SAFETY: `Vcpu` is `!Send`, so this runs on the creating (owning) thread, as // `hv_vcpu_destroy` requires; the id is destroyed exactly once. let _ = unsafe { ffi::hv_vcpu_destroy(self.id) }; }}/// A general-purpose or special register for `hv_vcpu_{get,set}_reg` (`hv_reg_t`).#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct Reg(pub ffi::hv_reg_t);impl Reg { pub const X0: Reg = Reg(ffi::HV_REG_X0); pub const X1: Reg = Reg(ffi::HV_REG_X1); pub const X2: Reg = Reg(ffi::HV_REG_X2); pub const X3: Reg = Reg(ffi::HV_REG_X3); pub const X4: Reg = Reg(ffi::HV_REG_X4); pub const X5: Reg = Reg(ffi::HV_REG_X5); pub const X6: Reg = Reg(ffi::HV_REG_X6); pub const X7: Reg = Reg(ffi::HV_REG_X7); /// Frame pointer (X29). pub const FP: Reg = Reg(ffi::HV_REG_FP); /// Link register (X30). pub const LR: Reg = Reg(ffi::HV_REG_LR); /// The program counter. After an HVC exit it already points past the HVC; after SMC, data /// abort and sysreg traps it points *at* the instruction (checked on a real Mac). pub const PC: Reg = Reg(ffi::HV_REG_PC); pub const FPCR: Reg = Reg(ffi::HV_REG_FPCR); pub const FPSR: Reg = Reg(ffi::HV_REG_FPSR); /// PSTATE as SPSR-format bits (`0x3c5` = EL1h with DAIF masked). pub const CPSR: Reg = Reg(ffi::HV_REG_CPSR);Under the hood
The kernel writes the exit record behind the compiler's back. Vcpu::run therefore copies it out with one volatile read right after each run and never holds a Rust reference into it, so the compiler cannot reuse a stale copy. That read is the only unusual line.
/// Enter the guest until the next exit, then return an owned copy of the exit record.pub fn run(&mut self) -> Result<VcpuExit, CallError> { // SAFETY: owning thread; `self.id` is live until `drop`. check("hv_vcpu_run", unsafe { ffi::hv_vcpu_run(self.id) })?; // SAFETY: `self.exit` is the framework-owned record returned by `hv_vcpu_create` for // this vCPU, valid and aligned until `hv_vcpu_destroy`; the run has finished writing it. // A volatile read copies it without forming a reference the compiler could cache. let raw = unsafe { core::ptr::read_volatile(self.exit) }; Ok(VcpuExit::from_raw(raw))}The copy becomes an owned value; an unknown reason is kept, never a panic:
/// Why `hv_vcpu_run` returned (`hv_exit_reason_t`).#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum ExitReason { /// `hv_vcpus_exit` (possibly a sticky kick from before this run). Canceled, /// A synchronous exception to EL2: decode `esr`. Exception, /// The virtual timer fired (only without an in-kernel interrupt controller). The framework /// has masked it. VtimerActivated, /// `HV_EXIT_REASON_UNKNOWN`: "should not happen under normal operation". Unknown, /// A value this SDK does not define, kept verbatim. Never a panic. Other(u32),}impl ExitReason { fn from_raw(raw: ffi::hv_exit_reason_t) -> ExitReason { match raw { ffi::HV_EXIT_REASON_CANCELED => ExitReason::Canceled, ffi::HV_EXIT_REASON_EXCEPTION => ExitReason::Exception, ffi::HV_EXIT_REASON_VTIMER_ACTIVATED => ExitReason::VtimerActivated, ffi::HV_EXIT_REASON_UNKNOWN => ExitReason::Unknown, other => ExitReason::Other(other), } } /// The header's name without the `HV_EXIT_REASON_` prefix, for messages. pub fn name(self) -> &'static str { match self { ExitReason::Canceled => "CANCELED", ExitReason::Exception => "EXCEPTION", ExitReason::VtimerActivated => "VTIMER_ACTIVATED", ExitReason::Unknown => "UNKNOWN", ExitReason::Other(_) => "<undefined>", } }}/// An owned copy of the framework's exit record.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct VcpuExit { pub reason: ExitReason, /// ESR_EL2 for the exit (`exception.syndrome`). pub esr: u64, /// FAR_EL2: the faulting guest virtual address, where defined. pub far: u64, /// The faulting IPA, page offset included. pub ipa: u64,}impl VcpuExit { fn from_raw(raw: ffi::hv_vcpu_exit_t) -> VcpuExit { VcpuExit { reason: ExitReason::from_raw(raw.reason), esr: raw.exception.syndrome, far: raw.exception.virtual_address, ipa: raw.exception.physical_address, } }}Declare the new modules in crates/hvf/src/lib.rs and re-export Vcpu, VcpuExit, ExitReason, Reg, MemFlags and OwnedMapping, as chapter 01 did for Vm.
One page of guest memory
The guest's three instructions need a home: one page of our memory, shown to the guest at an address we choose. That guest address is an IPA (intermediate physical address): the address the guest believes is physical, which the hardware translates to our memory. hv_vm_map sets up that translation, a stage-2 mapping; chapter 05 tells the full story of both names. Declare it beside hv_vm_create, with hv_vm_unmap, the allocation pair and the permission bits:
/// Map host memory `addr..addr+size` at guest IPA `ipa`. All three must be aligned to the/// IPA granule (16 KiB by default; `hv_vm_config.h` lets a VM choose 4 KiB).pub fn hv_vm_map( addr: *mut c_void, ipa: hv_ipa_t, size: usize, flags: hv_memory_flags_t,) -> hv_return_t;pub fn hv_vm_unmap(ipa: hv_ipa_t, size: usize) -> hv_return_t;// hv_vm_allocate.h (macOS 12.1)/// Page-aligned anonymous memory "suitable to be mapped as guest memory".pub fn hv_vm_allocate( uvap: *mut *mut c_void, size: usize, flags: hv_allocate_flags_t,) -> hv_return_t;pub fn hv_vm_deallocate(uva: *mut c_void, size: usize) -> hv_return_t;// Memory permissions (`hv_kern_types.h`).pub const HV_MEMORY_READ: hv_memory_flags_t = 1 << 0;pub const HV_MEMORY_WRITE: hv_memory_flags_t = 1 << 1;pub const HV_MEMORY_EXEC: hv_memory_flags_t = 1 << 2;// `hv_vm_allocate.h`.pub const HV_ALLOCATE_DEFAULT: hv_allocate_flags_t = 0;In learner/crates/hvf/src/vm.rs, the permissions get names and Vm gains a thin unsafe wrapper whose # Safety list says what a caller must promise:
/// Stage-2 permissions (`HV_MEMORY_*`).#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct MemFlags(pub ffi::hv_memory_flags_t);impl MemFlags { /// Mapped, but every access faults (`flags = 0` maps successfully; checked on a real Mac). pub const NONE: MemFlags = MemFlags(0); pub const READ: MemFlags = MemFlags(ffi::HV_MEMORY_READ); pub const WRITE: MemFlags = MemFlags(ffi::HV_MEMORY_WRITE); pub const EXEC: MemFlags = MemFlags(ffi::HV_MEMORY_EXEC); pub const RW: MemFlags = MemFlags(ffi::HV_MEMORY_READ | ffi::HV_MEMORY_WRITE); pub const RX: MemFlags = MemFlags(ffi::HV_MEMORY_READ | ffi::HV_MEMORY_EXEC); pub const RWX: MemFlags = MemFlags(ffi::HV_MEMORY_READ | ffi::HV_MEMORY_WRITE | ffi::HV_MEMORY_EXEC);}/// Map `len` bytes of host memory at `host` to guest IPA `ipa` with `flags`.////// The framework checks alignment (16 KiB by default) and returns `HV_BAD_ARGUMENT`/// otherwise, and `HV_ERROR` for an overlap; nothing is pre-checked here, so callers and/// tests see the framework's real answer.////// # Safety////// - `host..host+len` must be a single live allocation (for example a [`host::Allocation`])/// that stays allocated until this IPA range is unmapped or the VM is destroyed./// - While mapped, the guest may read and write those bytes at any moment: no Rust/// reference (`&`/`&mut`, slice) to them may exist; access them with volatile raw-pointer/// operations only./// - The same host range must not also be handed out as ordinary Rust memory.pub unsafe fn map( &self, host: *mut u8, ipa: u64, len: usize, flags: MemFlags,) -> Result<(), CallError> { // SAFETY: the caller upholds the contract above; the framework validates alignment. check("hv_vm_map", unsafe { ffi::hv_vm_map(host.cast(), ipa, len, flags.0) })}The memory comes from hv_vm_allocate, which chapter 04 opens up; read it as "give me 16 KiB the framework can map". Two names are not yours yet: host_page_size() (use 16 * 1024 today) and Allocation, a pointer and a length whose Drop calls hv_vm_deallocate. A struct with those two fields and that Drop is enough; chapter 04 builds the real one.
/// `hv_vm_allocate(len)`. `len` must be a non-zero multiple of the host page size; that is/// checked here first (reported as `hv_vm_allocate: HV_BAD_ARGUMENT`), because the header only/// promises behaviour for page multiples.pub fn allocate(len: usize) -> Result<Allocation, CallError> { let page = crate::caps::host_page_size(); if len == 0 || page == 0 || !len.is_multiple_of(page) { return Err(CallError { call: "hv_vm_allocate", error: HvError::BadArgument, }); } let mut ptr: *mut c_void = core::ptr::null_mut(); // SAFETY: `ptr` is a live out-parameter; `len` is a non-zero page multiple; flags are the // documented default. check("hv_vm_allocate", unsafe { ffi::hv_vm_allocate(&mut ptr, len, ffi::HV_ALLOCATE_DEFAULT) })?; let ptr = NonNull::new(ptr.cast::<u8>()).ok_or(CallError { call: "hv_vm_allocate", error: HvError::NoResources, })?; Ok(Allocation { ptr, len })}The reference wraps "allocate, then map" in one value that unmaps and frees itself when dropped, like chapter 01's Vm. Each // SAFETY: comment says why its unsafe call is sound.
/// Host memory that this value allocated and mapped at a fixed IPA; unmapped and freed on drop.////// It borrows the [`Vm`], so it cannot outlive it. Host-side access copies bytes with volatile/// operations through a raw pointer, never through a reference, because the guest may be/// running and writing the same bytes.#[derive(Debug)]pub struct OwnedMapping<'vm> { vm: &'vm Vm, ipa: u64, alloc: Option<host::Allocation>,}/// Allocate `len` bytes (a non-zero multiple of the host page size) and map them at `ipa`.pub fn new( vm: &'vm Vm, ipa: u64, len: usize, flags: MemFlags,) -> Result<OwnedMapping<'vm>, CallError> { let alloc = host::allocate(len)?; // SAFETY: `alloc` is one live `hv_vm_allocate` block of exactly `len` bytes; it is // owned by the returned value, which unmaps before freeing (see `Drop`), and its bytes // are only ever touched through volatile raw-pointer copies. unsafe { vm.map(alloc.as_ptr(), ipa, len, flags)? }; Ok(OwnedMapping { vm, ipa, alloc: Some(alloc), })}Writing checks the range first; OutOfBounds is a plain struct of the three numbers:
/// The byte range `offset..offset+len` inside a `size`-byte block, or an error. Pure, so the/// bounds logic is host-testable (`owned_mapping_write_bounds`). `checked_add` makes/// `offset = u64::MAX` an error instead of a wrapped, in-range-looking index.pub fn checked_span(size: usize, offset: u64, len: usize) -> Result<Range<usize>, OutOfBounds> { let err = OutOfBounds { offset, len, size }; let start = usize::try_from(offset).map_err(|_| err)?; let end = start.checked_add(len).ok_or(err)?; if end > size { return Err(err); } Ok(start..end)}/// Copy `data` into the mapping at byte `offset`. Out-of-range writes are refused whole.pub fn write(&self, offset: u64, data: &[u8]) -> Result<(), OutOfBounds> { let Some(alloc) = &self.alloc else { return Err(OutOfBounds { offset, len: data.len(), size: 0, }); }; let span = checked_span(alloc.len(), offset, data.len())?; for (i, byte) in span.zip(data) { // SAFETY: `i < alloc.len()` by `checked_span`, so the pointer stays inside the live // allocation; a volatile byte store creates no reference to guest-shared memory. unsafe { alloc.as_ptr().add(i).write_volatile(*byte) }; } Ok(())}Dropping unmaps before freeing. If the unmap fails, the guest might still reach the memory, so it is never freed:
impl Drop for OwnedMapping<'_> { fn drop(&mut self) { if let Some(alloc) = self.alloc.take() { if self.vm.unmap(self.ipa, alloc.len()).is_ok() { drop(alloc); } else { // Fail closed: memory the guest may still reach is never freed. let _ = alloc.leak(); } } }}Two numbers need a word. By default, mappings come in 16 KiB pieces, the Mac's host page size, aligned to 16 KiB (most PCs use 4 KiB; newer macOS lets a VM choose 4 KiB, see the page-granules primer). And 0x4000_0000 (1 GiB) is where RAM starts in the standard Arm virtual machine layout that stock kernels expect (chapter 05).
Three instruction words
The guest program is three 32-bit words, read as the aarch64-reading primer taught:
| Guest address | Word | Instruction | Why it is there |
|---|---|---|---|
0x4000_0000 | 0xD2800540 | movz x0, #0x2a | leave a value we can read back afterwards |
0x4000_0004 | 0xD4000002 | hvc #0 | call the level above: our VM exit |
0x4000_0008 | 0x14000000 | b . | branch to itself; a safe place to park if we ever resume |
The encoder lab shows movz, hvc and b with every bit field labelled. It is exploratory and unscored; skipping it costs nothing:
A64 encoder
Build an instruction word from its labelled bit fields, or take a word apart, and watch the 32 bits and the little-endian bytes change together.
Runs in browserOpen full page: A64 encoderFrom here on, code goes into learner/crates/macvmm/src/first_exit.rs. The words become bytes in guest memory order, little-endian (the primer's byte-order section):
/// `movz x0, #0x2a` · `hvc #0` · `b .`, as A64 words.const CODE: [u32; 3] = [0xD280_0540, 0xD400_0002, 0x1400_0000];/// The words in guest memory order: A64 instructions are little-endian.fn code_bytes() -> Vec<u8> { CODE.iter().flat_map(|w| w.to_le_bytes()).collect()}The starting state: PC and PSTATE
A vCPU starts from whatever we write: here, the PC 0x4000_0000 and PSTATE 0x3c5, which reads field by field like this (chapter 06 has you build such values):
Bits of 0x3c5 | Value | Meaning |
|---|---|---|
3 to 0 (M) | 0b0101 | bits 3 and 2 give the level, 01 = EL1; bit 0 picks the stack pointer, 1 = EL1's own, SP_EL1. This mode is written EL1h ("h" for handler stack); 0b0100 would be EL1t, EL1 using EL0's stack pointer |
| 4 | 0 | 64-bit execution (AArch64) |
9 to 6 (DAIF) | 0b1111 | four mask bits for the kinds of asynchronous exception: debug, SError (system error), IRQ (interrupt request) and FIQ (fast interrupt request). All set, so nothing interrupts our three instructions |
| all other bits | 0 |
Together, 0x3c0 | 0x5 = 0x3c5. The constants:
/// Guest RAM base, `0x4000_0000` (1 GiB), where QEMU's `virt` machine puts RAM. Spelled as a/// shift because the repository's audit allows that hex literal only in `vmm::arch::layout`,/// the one file that defines the memory map (chapter 05); there it is `RAM_BASE` too.const RAM_BASE: u64 = 1 << 30;/// One 16 KiB page, the default stage-2 granule on a Mac.const PAGE: usize = 16 * 1024;/// EL1h with DAIF masked.const CPSR_EL1H_MASKED: u64 = 0x3c5;Then steps 1 to 3: the VM, the mapping and the vCPU. VmBuilder::new().create() is the reference's way of creating chapter 01's Vm; call your own constructor instead:
// 1. The VM: one per process, default 36-bit IPA. No interrupt controller (GIC, chapter// 12) is needed for a single trap.let (vm, _no_gic) = VmBuilder::new().create()?;// 2. One page of guest RAM at RAM_BASE holding the three instructions.let ram = OwnedMapping::new(&vm, RAM_BASE, PAGE, MemFlags::RWX)?;ram.write(0, &code_bytes()).map_err(|_| hvf::CallError { call: "write", error: hvf::HvError::BadArgument,})?;out(&format!( "first-exit: mapped {} KiB at IPA {RAM_BASE:#x}", PAGE / 1024));// 3. A vCPU for this thread, pointed at the code.let mut vcpu = Vcpu::create(&vm)?;vcpu.set_reg(Reg::PC, RAM_BASE)?;vcpu.set_reg(Reg::CPSR, CPSR_EL1H_MASKED)?;The first run
Step 4 runs the vCPU and decodes the exit by shifting and masking, as in sitting A's field figure; step 5 reads two registers:
// 4. Run until the guest traps, then decode the syndrome by hand.let exit = vcpu.run()?;let ec = (exit.esr >> 26) & 0x3f;let imm = exit.esr & 0xffff;let reason = exit.reason.name();out(&format!( "first-exit: exit reason={reason} syndrome={:#x} ec={ec:#x} ({}) imm={imm:#x}", exit.esr, ec_name(ec)));if exit.reason != ExitReason::Exception { return Err(hvf::CallError { call: "hv_vcpu_run (expected an exception exit)", error: hvf::HvError::Error, });}// 5. The HVC already advanced PC; x0 holds what `movz` put there.let pc = vcpu.get_reg(Reg::PC)?;let x0 = vcpu.get_reg(Reg::X0)?;out(&format!("first-exit: pc={pc:#x} x0={x0:#x}"));ec_name names the few classes this chapter meets, and run turns the result into an exit status. out and err print one line to standard output and standard error, like println! and eprintln!:
/// A name for the few exception classes this lesson can meet (ARM ARM, ESR_EL2 register/// description, the EC field table). Chapter 07 builds the full decoder, `vmm::arch::esr`.fn ec_name(ec: u64) -> &'static str { match ec { 0x01 => "WFx", 0x16 => "HVC64", 0x17 => "SMC64", 0x18 => "SYS64", 0x20 => "IABT_LOWER", 0x24 => "DABT_LOWER", _ => "other", }}/// Run the demo: exactly three lines on stdout and exit 0 on success; the lines reached so far/// plus an error on stderr and exit 1 otherwise.pub fn run() -> ExitCode { match first_exit() { Ok(()) => ExitCode::SUCCESS, Err(e) => { err(&format!("first-exit: {e}")); if e.error == hvf::HvError::Denied { err("hint: run it through scripts/sign-and-run.sh (`cargo run -p macvmm --"); err(" first-exit` does this) so it carries com.apple.security.hypervisor."); } ExitCode::FAILURE } }}Add the subcommand to your main.rs the way chapter 01 added doctor:
Some("first-exit") => { if let Some(extra) = args.rest.first() { return usage_error(&format!("first-exit: unexpected argument {extra:?}")); } first_exit::run()}Run it from inside learner/, through the signing runner that cargo run uses (chapter 01):
cd learnercargo run -q -p macvmm -- first-exitCheck your Predict entry, then compare with the reference's run:
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x5a000000 ec=0x16 (HVC64) imm=0x0first-exit: pc=0x40000008 x0=0x2aThe syndrome is 0x5a000000: EC 0x16, an hvc, immediate 0. x0=0x2a proves the movz ran. And the PC is 0x40000008: after the hvc. Nobody in our VMM moved it: the hardware saved the preferred return address, and for a call that is the next instruction. If you predicted "at the hvc, so add 4", you were in good company; had your VMM done it, the guest would skip its b . and run off the end.
That is not a universal rule, though.
Try it
Change the second word from 0xD400_0002 (hvc #0) to 0xD400_0003 (smc #0, a call meant for the firmware at EL3) and run again. Look at the class and the PC before you read our run.
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x5e000000 ec=0x17 (SMC64) imm=0x0first-exit: pc=0x40000004 x0=0x2aWe checked this on a real Mac: class 0x17 (SMC64), and the PC is still 0x40000004, at the instruction. The rule holds: the smc never executed. Apple's chips have no EL3, and the software at EL2 intercepts (traps) every smc first. An intercepted instruction has not happened yet, so, like a fault, the saved PC points at it. Executed call: after. Fault or intercepted instruction: at. After an smc, the VMM must advance the PC itself. So look up the return rule for each class; never add 4 out of habit.
Breaking it on purpose
Three deliberate breaks, each predicted first; undo each before the next.
Deliberate breakage 1: delete the hvc. Remove the middle word, leaving movz and b ., and change the array's length to 2. Predict: how many VM exits will you see? Run it, wait ten seconds, then press Ctrl-C. The capture tool stopped our run after ten seconds; macvmm has no timeout yet:
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000One line, then nothing. b . is a valid program that never needs the level above, so hv_vcpu_run never returns, and its thread can do nothing. What you saw: a hang. The misconception it exposes: "a broken guest produces an error". The tool that will find it: an external way to stop a vCPU, which chapter 03 adds as --timeout and chapter 09 as a kick from another thread.
Deliberate breakage 2: delete the b . and run twice. Restore the hvc, delete the third word instead (length 2 again), and wrap steps 4 and 5 (run, decode, then read and print the PC and x0) in a loop that runs twice. The second run starts at 0x40000008, past our program, where the page holds zeros. Predict the second exit's class:
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x5a000000 ec=0x16 (HVC64) imm=0x0first-exit: pc=0x40000008 x0=0x2afirst-exit: exit reason=EXCEPTION syndrome=0x82000006 ec=0x20 (IABT_LOWER) imm=0x6first-exit: pc=0x200 x0=0x2aNot an "undefined instruction" exit: the second stop is class 0x20, printed IABT_LOWER, an instruction abort (the CPU could not fetch the instruction at the PC) from a level lower than EL2: the guest. It happened at pc=0x200. The word 0x00000000 is permanently undefined (udf), so the guest took an exception at its own level, EL1, through its own vector table; nobody set VBAR_EL1, so it is 0, and the CPU went to 0 + 0x200, the entry from sitting A. Nothing is mapped there, so fetching the handler failed, and that reached us. The VMM often sees only the consequence (chapter 06). Ignore imm=0x6 here: only for svc, hvc and smc do the low 16 bits hold the instruction's number; for an abort they describe the fault (nothing mapped), which chapter 05 decodes. The syndrome is data: decode it, never pattern-match it.
Deliberate breakage 3: a vCPU id that is too narrow. In your ffi.rs, declare hv_vcpu_t as u32 (it is 32 bits on Intel Macs, so copied examples sometimes say so) and fix the casts the compiler asks for. Predict: compile error, crash, or nothing visible? To have something to see, our run passed the first of two adjacent u32 slots, holding 0 and 0xdeadbeef, as the id out-pointer, and printed both:
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x5a000000 ec=0x16 (HVC64) imm=0x0first-exit: pc=0x40000008 x0=0x2ahv_vcpu_create: id=0x0 neighbour=0x0The same three lines, yet 0xdeadbeef is gone: the framework wrote the eight-byte id the header promises into a four-byte slot, and the extra bytes (zeros, as the id is 0) landed on the neighbour. In your program, that is whatever the compiler placed next. The checkpoint passes this break too (we ran it); only the header catches it.
Security
The immediate in an hvc, the value in x0, every field of the syndrome: the guest chose them all. Today we only print them. From chapter 03 on, our VMM acts on them, and a hostile or merely buggy guest will send numbers nobody planned for. Treat every value a guest hands over as untrusted input: check its range before you use it to index, allocate or branch.
Your turn
If you typed along (typing, not pasting, is where the questions come from), your workspace holds everything this page showed. Before the checkpoint, check:
cargo run -q -p macvmm -- first-exit, from insidelearner/, prints the reference's three lines.- Your journal has the Predict entry, written before your first run, and question 3, answered during the first break.
Stuck? scripts/learner hint 02 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 02You should see, as the last line:
CHECKPOINT 02 PASSIt runs the contract tests (your exit-record layout and exit-reason values against the header), runs your first-exit and compares its output line by line, checks that every journal heading has an answer, and ends with CHECKPOINT 02 PASS. The run step expects these lines (it runs the binary directly, hence macvmm first-exit):
macvmm first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x5a000000 ec=0x16 (HVC64) imm=0x0first-exit: pc=0x40000008 x0=0x2aWhat now works:
- your crate declares the vCPU half of Hypervisor.framework, checked against the header (by the checkpoint for the exit record, by you for the rest);
- a guest runs three instructions natively on your Mac's CPU and stops on its
hvc; - you can split a syndrome into class, length and immediate, and know why the PC needs adjusting after an
smcbut not after anhvc.
The next chapter starts from this state (the reference at the end of chapter 02).
What's next
Chapter 03 writes a real guest program in Rust, with no operating system under it, gives your VMM a loop that answers exit after exit and a timeout for the hang, and measures what one VM exit costs. The answer is why the second half of this course exists.
Open question
One more experiment: the same three words, but with EL2 offered to the guest (the switch from the Aside) and the vCPU started at EL2. The hvc never reached us as an hvc:
cargo run -q -p macvmm -- first-exitfirst-exit: mapped 16 KiB at IPA 0x40000000first-exit: exit reason=EXCEPTION syndrome=0x82000006 ec=0x20 (IABT_LOWER) imm=0x6first-exit: pc=0x200 x0=0x2afirst-exit: guest ESR_EL2=0x5a000000 ELR_EL2=0x40000008 VBAR_EL2=0x0Compare the exit we did get with the second exit of breakage 2. The guest's own ESR_EL2 holds 0x5a000000, the syndrome our VMM read in the first run, and its ELR_EL2 holds 0x40000008. What changed between the two runs: the instruction, or the routing?
Spec hunt
- ARM ARM (DDI 0487), register page ESR_EL2, Exception Syndrome Register (EL2), the EC field table: which other classes can a guest kernel cause that would reach EL2, and which of them have you now seen?
- ARM ARM, the section on the preferred exception return address in the exception model chapter for AArch64: where does the manual say an
hvcreturns after itself while a trappedsmcreturns to itself? - The SDK header
hv_vcpu.h(withhv_vcpu_types.h): which functions may be called from any thread, and which only by the vCPU's owning thread?