diff --git a/openhcl/virt_mshv_vtl/src/processor/tdx/mod.rs b/openhcl/virt_mshv_vtl/src/processor/tdx/mod.rs index bd163fc36c8..cb1a68bb56a 100644 --- a/openhcl/virt_mshv_vtl/src/processor/tdx/mod.rs +++ b/openhcl/virt_mshv_vtl/src/processor/tdx/mod.rs @@ -75,6 +75,7 @@ use virt_support_apic::ApicClient; use virt_support_apic::OffloadNotSupported; use virt_support_x86emu::emulate::EmulatedMemoryOperation; use virt_support_x86emu::emulate::EmulatorSupport as X86EmulatorSupport; +use virt_support_x86emu::emulate::MemoryOpOutcome; use virt_support_x86emu::emulate::TranslateMode; use virt_support_x86emu::emulate::emulate_insn_memory_op; use virt_support_x86emu::emulate::emulate_io; @@ -674,6 +675,10 @@ impl HardwareIsolatedBacking for TdxBacked { vtl: GuestVtl, event: HvX64PendingExceptionEvent, ) { + if event.vector() == u16::from(x86defs::Exception::PAGE_FAULT.0) { + this.runner.set_cr2(event.exception_parameter()); + } + let new_intr = InterruptionInformation::new() .with_valid(true) .with_deliver_error_code(event.deliver_error_code()) @@ -3426,7 +3431,7 @@ impl UhProcessor<'_, TdxBacked> { vtl, cache: TdxEmulationCache::default(), }; - emulate_insn_memory_op( + if emulate_insn_memory_op( &mut emulation_state, gm, dev, @@ -3435,7 +3440,11 @@ impl UhProcessor<'_, TdxBacked> { x86emu::AlignmentMode::Unaligned, EmulatedMemoryOperation::Write(&buf[..len]), ) - .await?; + .await? + == MemoryOpOutcome::FaultInjected + { + return Ok(()); + } } GdtrOrIdtrInstruction::Lgdt | GdtrOrIdtrInstruction::Lidt => { @@ -3446,7 +3455,7 @@ impl UhProcessor<'_, TdxBacked> { vtl, cache: TdxEmulationCache::default(), }; - emulate_insn_memory_op( + if emulate_insn_memory_op( &mut emulation_state, gm, dev, @@ -3455,7 +3464,11 @@ impl UhProcessor<'_, TdxBacked> { x86emu::AlignmentMode::Unaligned, EmulatedMemoryOperation::Read(&mut buf[..len]), ) - .await?; + .await? + == MemoryOpOutcome::FaultInjected + { + return Ok(()); + } let table = TableRegister { limit: u16::from_le_bytes(buf[..2].try_into().unwrap()), base: u64::from_le_bytes(buf[2..len].try_into().unwrap()), @@ -3534,7 +3547,7 @@ impl UhProcessor<'_, TdxBacked> { vtl, cache: TdxEmulationCache::default(), }; - emulate_insn_memory_op( + if emulate_insn_memory_op( &mut emulation_state, gm, dev, @@ -3543,7 +3556,11 @@ impl UhProcessor<'_, TdxBacked> { x86emu::AlignmentMode::Standard, EmulatedMemoryOperation::Write(&value.to_le_bytes()), ) - .await?; + .await? + == MemoryOpOutcome::FaultInjected + { + return Ok(()); + } } } @@ -3569,7 +3586,7 @@ impl UhProcessor<'_, TdxBacked> { cache: TdxEmulationCache::default(), }; let mut buf = [0u8; 2]; - emulate_insn_memory_op( + if emulate_insn_memory_op( &mut emulation_state, gm, dev, @@ -3578,7 +3595,11 @@ impl UhProcessor<'_, TdxBacked> { x86emu::AlignmentMode::Standard, EmulatedMemoryOperation::Read(&mut buf), ) - .await?; + .await? + == MemoryOpOutcome::FaultInjected + { + return Ok(()); + } u16::from_le_bytes(buf) }; self.runner.write_vmcs16( diff --git a/vmm_core/virt_support_x86emu/src/emulate.rs b/vmm_core/virt_support_x86emu/src/emulate.rs index 2fd78272f4f..bf4a8559713 100644 --- a/vmm_core/virt_support_x86emu/src/emulate.rs +++ b/vmm_core/virt_support_x86emu/src/emulate.rs @@ -541,6 +541,11 @@ async fn emulate_core( /// "As if it had been performed by an emulated instruction" means that the given /// GVA will be translated to a GPA, subject to applicable segmentation, permission, /// and alignment checks, may be determined to be MMIO instead of RAM, etc. +/// +/// Architectural exceptions raised by the access (such as page faults) are +/// injected into the guest and reported as [`MemoryOpOutcome::FaultInjected`]. +/// In that case the caller must not complete the instruction: it must not +/// update guest state or advance the instruction pointer. pub async fn emulate_insn_memory_op( support: &mut T, gm: &GuestMemory, @@ -549,14 +554,14 @@ pub async fn emulate_insn_memory_op( segment: Segment, alignment: AlignmentMode, op: EmulatedMemoryOperation<'_>, -) -> Result<(), VpHaltReason> { +) -> Result { assert!(!support.interruption_pending()); let vendor = support.vendor(); let mut cpu = EmulatorCpu::new(gm, dev, support); let mut emu = x86emu::Emulator::new(&mut cpu, vendor, &[]); - match op { + let result = match op { EmulatedMemoryOperation::Read(data) => { emu.read_memory(segment, gva, alignment, data, ReadKind::ReadOnly) .await @@ -564,10 +569,31 @@ pub async fn emulate_insn_memory_op( EmulatedMemoryOperation::Write(data) => { emu.write_memory(segment, gva, alignment, data).await } - } - .map_err(|e| dev.fatal_error(e.into())) + }; // No need to flush the cache, we have not modified any registers. + + match result { + Ok(()) => Ok(MemoryOpOutcome::Completed), + Err(x86emu::Error::InstructionException(exception, error_code, cause)) => { + tracing::trace!( + ?exception, + ?error_code, + ?cause, + "emulated memory operation caused exception" + ); + support.inject_pending_event(make_exception_event(exception, error_code, None)); + Ok(MemoryOpOutcome::FaultInjected) + } + Err(x86emu::Error::MemoryAccess(addr, kind, err)) => { + if inject_memory_access_fault(&err, support) { + Ok(MemoryOpOutcome::FaultInjected) + } else { + Err(dev.fatal_error(x86emu::Error::MemoryAccess(addr, kind, err).into())) + } + } + Err(err) => Err(dev.fatal_error(err.into())), + } } pub enum EmulatedMemoryOperation<'a> { @@ -575,6 +601,17 @@ pub enum EmulatedMemoryOperation<'a> { Write(&'a [u8]), } +/// The result of a successful [`emulate_insn_memory_op`] call. +#[must_use] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum MemoryOpOutcome { + /// The memory operation completed. + Completed, + /// The memory operation faulted and the exception was injected into the + /// guest. The instruction must not be completed. + FaultInjected, +} + /// For storing gva to gpa translations in a cache in [`EmulatorCpu`] struct GvaGpaCacheEntry { gva_page: u64, diff --git a/vmm_core/virt_support_x86emu/tests/tests/translate.rs b/vmm_core/virt_support_x86emu/tests/tests/translate.rs index 280847cb048..cce244e6613 100644 --- a/vmm_core/virt_support_x86emu/tests/tests/translate.rs +++ b/vmm_core/virt_support_x86emu/tests/tests/translate.rs @@ -1543,3 +1543,191 @@ async fn translate_gva_overlay_page() { validate_gpf_event(support.injected_event().unwrap()); } + +// Descriptor-table exits carry no cached translation, so use an operand +// address outside the mock's initial translation to force a page walk. +const OPERAND_GVA: u64 = 0x5000; + +// Test: Read and write a non-present guest operand through the memory-only +// helper used by TDX descriptor-table instruction emulation. +// Expected: Inject a guest #PF and report FaultInjected, leaving memory and +// RIP unchanged, instead of a fatal error. +#[async_test] +async fn insn_memory_op_page_fault_is_injected_not_fatal() { + for write in [false, true] { + let gm = GuestMemory::allocate(0x4000); + let before = vec![0xa5; 0x4000]; + gm.write_at(0, &before).unwrap(); + let mut support = MockSupport::new( + MockSupportMode::Code(TranslateGvaResultCode::PAGE_NOT_PRESENT), + MockSupportTranslation { + access_gva: OPERAND_GVA, + translate_to_gpa: INITIAL_GPA, + access_info: MockAccess::Read, + }, + false, + &gm, + ); + let rip = support.state.rip; + let mut data = [0x5a; 10]; + let op = if write { + EmulatedMemoryOperation::Write(&data) + } else { + EmulatedMemoryOperation::Read(&mut data) + }; + + let result = emulate_insn_memory_op( + &mut support, + &gm, + &MockCpu, + OPERAND_GVA, + Segment::DS, + x86emu::AlignmentMode::Unaligned, + op, + ) + .await; + + assert!( + matches!(result, Ok(MemoryOpOutcome::FaultInjected)), + "guest page fault was not injected (write: {write}): {result:?}" + ); + let event = hvdef::HvX64PendingExceptionEvent::from(u128::from( + support.injected_event().expect("expected page fault").reg_0, + )); + assert!(event.event_pending()); + assert_eq!(event.event_type(), hvdef::HV_X64_PENDING_EVENT_EXCEPTION); + assert_eq!(event.vector(), x86defs::Exception::PAGE_FAULT.0.into()); + assert!(event.deliver_error_code()); + assert_eq!( + event.error_code(), + u32::from(x86defs::PageFaultErrorCode::new().with_write(write)), + ); + assert_eq!(event.exception_parameter(), OPERAND_GVA); + assert_eq!(support.state.rip, rip); + let mut after = vec![0; before.len()]; + gm.read_at(0, &mut after).unwrap(); + assert!(after == before, "faulting access modified memory"); + } +} + +// Test: Read and write a mapped guest operand through the same helper. +// Expected: The access succeeds, moves the expected bytes, and injects nothing. +#[async_test] +async fn insn_memory_op_mapped_operand_succeeds() { + let gm = GuestMemory::allocate(0x4000); + let mut support = MockSupport::new( + MockSupportMode::Code(TranslateGvaResultCode::SUCCESS), + MockSupportTranslation { + access_gva: OPERAND_GVA, + translate_to_gpa: INITIAL_GPA, + access_info: MockAccess::Read, + }, + false, + &gm, + ); + let written = [0x3f, 0x00, 0x78, 0x56, 0x34, 0x12, 0x9a, 0xbc, 0xde, 0xf0]; + + let outcome = emulate_insn_memory_op( + &mut support, + &gm, + &MockCpu, + OPERAND_GVA, + Segment::DS, + x86emu::AlignmentMode::Unaligned, + EmulatedMemoryOperation::Write(&written), + ) + .await + .unwrap(); + assert_eq!(outcome, MemoryOpOutcome::Completed); + let mut stored = [0; 10]; + gm.read_at(INITIAL_GPA, &mut stored).unwrap(); + assert_eq!(stored, written); + + let mut read = [0; 10]; + let outcome = emulate_insn_memory_op( + &mut support, + &gm, + &MockCpu, + OPERAND_GVA, + Segment::DS, + x86emu::AlignmentMode::Unaligned, + EmulatedMemoryOperation::Read(&mut read), + ) + .await + .unwrap(); + assert_eq!(outcome, MemoryOpOutcome::Completed); + assert_eq!(read, written); + assert!(support.injected_event().is_none()); +} + +// Test: Access a non-canonical operand address through the memory-only helper. +// Expected: Inject #GP(0) and report FaultInjected instead of a fatal error. +#[async_test] +async fn insn_memory_op_segmentation_fault_is_injected_not_fatal() { + const NON_CANONICAL_GVA: u64 = 0x8000_0000_0000_0000; + let gm = GuestMemory::allocate(0x4000); + let mut support = MockSupport::new( + MockSupportMode::Code(TranslateGvaResultCode::SUCCESS), + MockSupportTranslation { + access_gva: OPERAND_GVA, + translate_to_gpa: INITIAL_GPA, + access_info: MockAccess::Read, + }, + false, + &gm, + ); + let mut data = [0; 10]; + + let result = emulate_insn_memory_op( + &mut support, + &gm, + &MockCpu, + NON_CANONICAL_GVA, + Segment::DS, + x86emu::AlignmentMode::Unaligned, + EmulatedMemoryOperation::Read(&mut data), + ) + .await; + + assert!( + matches!(result, Ok(MemoryOpOutcome::FaultInjected)), + "segmentation fault was not injected: {result:?}" + ); + validate_gpf_event(support.injected_event().expect("expected #GP")); +} + +// Test: Access an operand whose translated GPA is outside guest memory. +// Expected: The host-side memory failure remains fatal and nothing is +// injected into the guest. +#[async_test] +async fn insn_memory_op_host_memory_failure_remains_fatal() { + let gm = GuestMemory::allocate(0x4000); + let mut support = MockSupport::new( + MockSupportMode::Code(TranslateGvaResultCode::SUCCESS), + MockSupportTranslation { + access_gva: OPERAND_GVA, + translate_to_gpa: 0x10_0000, + access_info: MockAccess::Read, + }, + false, + &gm, + ); + let mut data = [0; 10]; + + let result = emulate_insn_memory_op( + &mut support, + &gm, + &MockCpu, + OPERAND_GVA, + Segment::DS, + x86emu::AlignmentMode::Unaligned, + EmulatedMemoryOperation::Read(&mut data), + ) + .await; + + assert!( + matches!(result, Err(virt::VpHaltReason::TripleFault { .. })), + "host memory failure was not fatal: {result:?}" + ); + assert!(support.injected_event().is_none()); +}