Study guides · Advanced

Emulating MMIO: validating a stage-2 fault and resuming the guest

Read measured ESR, FAR, and HPFAR values, validate address, width, and direction, emulate one UART byte store, and resume only after success.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: distinguish taking a fault from handling it
  2. Map RAM and leave the UART IPA unmapped
  3. Validate ESR from the broad class inward
  4. Reconstruct and check the target IPA
  5. Execute field and boundary-value checks
  6. Read the measured emulation and resumption
  7. Compare normal, maximum-byte, and unsupported-width runs
  8. Exercise: violate one acceptance condition at a time
  9. Ask Logeia about this articleCheck your understanding

Goal: distinguish taking a fault from handling it

The preceding lessons established EL1 entry and an EL2 synchronous-exception path. A Data Abort alone does not authorize the handler to print a UART character. This lesson validates the exception class, instruction-syndrome validity, access size, direction, and target IPA before emulating one supported operation. Only after those conditions are satisfied may the handler advance the guest’s saved return address. Classification, validation, side effect, and resumption are separate steps with a deliberate order.

The distributed implementation supports an ordinary one-byte store to the virtual UART data register. It does not implement the complete PL011 register interface, interrupts, FIFO behavior, DMA, or virtio. Distinguish the broader concepts explored in earlier explanatory models from the narrower code actually executed under QEMU here. A narrow implementation can still have a strong contract: measure its normal output, exercise the byte-value boundary, and demonstrate rejection of an unsupported access without pretending that it completed.

Map RAM and leave the UART IPA unmapped

The project configures a stage-2 table format with a 4 KiB granule, a level-1 start, and a 39-bit IPA range. L1 index one contains a 1 GiB block mapping beginning at 0x40000000 for RAM. No valid entry covers the UART IPA at 0x09000000. Guest code and stack can therefore execute while an access to that UART address generates a translation fault. The unmapped address is intentional; a missing guest-code mapping would instead prevent the desired instruction stream from reaching the test store.

The recorded settings are VTCR_EL2=0x80023559 and HCR_EL2=0x80000001, with VTTBR_EL2 pointing at the aligned stage-2 table. Table initialization precedes the synchronization and translation-state operations used before enabling the guest regime. The 1 GiB RAM mapping is deliberately coarse to keep the teaching example readable. Host and guest share one ELF image. Do not treat this map as complete isolation from an untrusted guest: the successful single-guest trace demonstrates this execution path, not a production security boundary.

Validate ESR from the broad class inward

The measured normal-store ESR_EL2 is 0x93090045. Its EC is 0x24, identifying a Data Abort from a lower exception level. IL describes the 32-bit instruction length used on this path, while ISV establishes whether the instruction-syndrome fields may be interpreted. SAS=0 selects byte width, SRT=9 identifies saved W9, and WnR=1 identifies a write. DFSC=5 describes the level-1 translation fault observed in this run. Decode broad classification first instead of converting the entire value directly into a presumed device operation.

The shared decode_uart_write function rejects invalid instruction information, unusable FAR information, stage-1-table-walk faults, reads, unsupported widths, and non-translation faults. Trusting SAS or SRT before checking ISV can misclassify an unrelated exception as a UART operation. Register number 31 needs special handling: for this store it denotes the zero register, not a thirty-second element in the saved array. The frame holds thirty-one general registers, so blindly indexing it with every five-bit register number would violate the representation contract.

FieldNormal measured valueDecoder meaning
EC0x24Data Abort from a lower level
IL / ISV1 / 132-bit instruction length and valid instruction syndrome
SAS0One-byte access
SRT9Read the value from saved W9
WnR1Write operation
DFSC5A level-1 translation fault in this recording

Reconstruct and check the target IPA

FAR_EL2 and HPFAR_EL2 are not duplicate copies of one address. For the valid translation-fault category handled by this configuration, the decoder obtains the upper IPA contribution from HPFAR’s FIPA field and combines it with FAR’s low twelve bits. In the normal recording FAR is 0x09000000 and HPFAR is 0x00090000, producing IPA 0x09000000. Validate the exception conditions before using those values; a reconstruction formula alone does not make every exception’s address registers meaningful.

The decoder compares against the exact UART data-register IPA. It does not accept every offset in the same page. Address 0x09000001 is therefore unsupported even though it shares the page with the accepted register. Direction and width also remain part of the operation identity: a read, a byte store, and a word store require different behavior. Checking the address while ignoring those distinctions would turn unsupported guest activity into apparent success and make later register-interface extensions difficult to reason about.

Execute field and boundary-value checks

The host program below checks the recorded fields and shows how changing the page offset changes the reconstructed IPA. Inspect the complete acceptance policy in the project’s src/lib.rs decode_uart_write function and its native tests. This shorter example makes two representation details explicit: extracting a byte from 0x141 yields 0x41, and register thirty-one must not index beyond the saved array. Think about byte width as an integer constraint as well as the character eventually displayed by the console.

The normal value is A, or 0x41. Boundary values include 0xff and the zero register. A one-byte address change and a changed SAS field demonstrate why exact checks matter. This program neither accesses UART nor generates an exception. Correct field arithmetic and evidence that QEMU generated the measured fault are different claims. Read the host assertions alongside the native decoder tests and the actual recording so the numerical explanation remains connected to an executed instruction rather than becoming a substitute for one.

rust
// Host-side interpretation of measured fields; not a machine handler.
fn ipa(far: u64, hpfar: u64) -> u64 {
    ((hpfar & 0x0000_ffff_ffff_fff0) << 8) | (far & 0xfff)
}
fn stored_byte(register: usize, saved: &[u64;31]) -> u8 {
    if register == 31 { 0 } else { saved[register] as u8 }
}
fn main() {
    let esr = 0x9309_0045u64;
    assert_eq!((esr >> 26) & 63, 0x24);
    assert_eq!((esr >> 24) & 1, 1);
    assert_eq!((esr >> 22) & 3, 0);
    assert_eq!((esr >> 16) & 31, 9);
    assert_eq!((esr >> 6) & 1, 1);
    assert_eq!(esr & 63, 5);
    assert_eq!(ipa(0x0900_0000, 0x0009_0000), 0x0900_0000);
    assert_ne!(ipa(0x0900_0001, 0x0009_0000), 0x0900_0000);
    let mut saved = [0u64;31]; saved[9] = 0x141;
    assert_eq!(stored_byte(9, &saved), b'A');
    saved[9] = 255;
    assert_eq!(stored_byte(9, &saved), 255);
    assert_eq!(stored_byte(31, &saved), 0);
    assert_eq!(((esr | (2 << 22)) >> 22) & 3, 2);
}

Read the measured emulation and resumption

In the measured normal build, the compiler-generated guest STRB attempts to store A from W9 at the UART address held in X8. Stage 2 faults. EL2 retrieves the byte from saved register nine and writes it through the host UART access path. It is not rerunning the guest store against the same unmapped address; it performs the supported side effect once on the guest’s behalf. Explain this distinction while following TRAP, EMULATE, and RESUME in order.

Only successful emulation advances ELR_EL2 by four. ERET returns to the guest, and a subsequent HVC produces GUEST_RESUMED. Another build may choose different registers or place the store at another address. W9 and X8 describe this recording, not hard-coded requirements of the decoder. The SRT field connects the compiler’s chosen source register to the saved frame. This is why retaining source identity, machine-code evidence, and the measured syndrome together is more robust than assuming a particular register allocation will never change.

Compare normal, maximum-byte, and unsupported-width runs

The normal run emulates byte 0x41, then reaches guest resumption and completion. The boundary run uses 0xff to test the maximum byte value without changing access width. That byte is not necessarily a readable standalone UTF-8 character, so inspect the hexadecimal BYTE field rather than judging its appearance alone. Preserve the raw console bytes alongside a decoded display. This separates a text decoder’s replacement character from the actual value produced by the guest.

The unsupported-width run performs a four-byte store. Its measured ESR is 0x93890045, with SAS=2. The project rejects the width, does not advance ELR, does not print GUEST_RESUMED, and exits as a failure. Native tests additionally cover reads, wrong addresses, invalid syndrome information, and the zero register. Rounding an unsupported value into A, or doing nothing while advancing the PC, would falsely claim that the guest operation completed. Rejection is a defined result of this implementation, not a partially successful UART write.

Exercise: violate one acceptance condition at a time

Make a table for decode_uart_write containing each acceptance condition, its rejection reason, and the test that exercises it. Run the existing normal, boundary, and failure cases before changing one condition at a time. Incrementing the address, changing a write into a read, and clearing ISV investigate different contracts. If several conditions are broken together, the first rejection may prevent the later checks from being exercised. Keep the inputs independent so each result answers a specific question.

For an extension, specify a read operation or another access width before implementing it. Decide the returned value, extension rules, register-thirty-one behavior, side-effect count, and rejected-operation PC policy. Website question scores and self-reported local implementation completion remain separate. For the local exercise, compare the finished reference with your implementation and retain normal, boundary, and failure evidence. The objective is a small operation whose accepted and rejected behavior you can explain from source, tests, and measured execution.

QEMU recording: guest MMIO and resume

Loading experiment checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Choose a learning path