Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(hypervisor): add x86 VM and vCPU snapshot state types (#2962)

lfld2872eb373c42ffa
diff --git a/Cargo.lock b/Cargo.lock
index 939ea579f..d91cbeece 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -725,6 +725,8 @@ dependencies = [
"kvm-bindings",
"kvm-ioctls",
"libc",
+ "postcard",
+ "serde",
]
[[package]]
@@ -1052,6 +1054,15 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+[[package]]
+name = "cobs"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
+dependencies = [
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -1806,6 +1817,18 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "embedded-io"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
+
+[[package]]
+name = "embedded-io"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
+
[[package]]
name = "encode_unicode"
version = "1.0.0"
@@ -3031,7 +3054,9 @@ version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11cf0ca75d59e9d298647c59cf6c5286fa048120caa77972a7a504a0824d234f"
dependencies = [
+ "serde",
"vmm-sys-util 0.15.0",
+ "zerocopy",
]
[[package]]
@@ -4311,6 +4336,18 @@ version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
+[[package]]
+name = "postcard"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
+dependencies = [
+ "cobs",
+ "embedded-io 0.4.0",
+ "embedded-io 0.6.1",
+ "serde",
+]
+
[[package]]
name = "potential_utf"
version = "0.1.5"
diff --git a/src/hypervisor/Cargo.toml b/src/hypervisor/Cargo.toml
index ad2296234..cecdbe1fa 100644
--- a/src/hypervisor/Cargo.toml
+++ b/src/hypervisor/Cargo.toml
@@ -8,7 +8,11 @@ license.workspace = true
description = "Host hypervisor backends for BoxLite's VMM"
repository = "https://github.com/boxlite-ai/boxlite"
+[dev-dependencies]
+postcard = { version = "1", default-features = false, features = ["alloc"] }
+
[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]
-kvm-bindings = "0.14.1"
+serde = { version = "1.0.228", features = ["derive"] }
+kvm-bindings = { version = "0.14.1", features = ["serde"] }
kvm-ioctls = "0.25.0"
libc = "0.2"
diff --git a/src/hypervisor/README.md b/src/hypervisor/README.md
index 91463ba22..a8476309c 100644
--- a/src/hypervisor/README.md
+++ b/src/hypervisor/README.md
@@ -22,6 +22,7 @@ machine layout and device emulation belong to `boxlite-vmm`.
| `error` | `Error`: the failed operation, its resource, and the host cause |
| `arm64` | `Arm64Vcpu`, `Arm64BootRegisters` and `CpuOnResult`: the arm64 boot registers and the VMM's answer to `CPU_ON` |
| `hvf` | macOS arm64: the VM and its in-kernel GICv3, memory, vCPU execution and kicks, with `syndrome` decoding exceptions and emulating trapped system registers, and `psci` serving PSCI 0.2 |
+| `x86` | Boot configuration and Linux x86_64 VM/vCPU state images with Serde encoding |
| `kvm` | x86_64 VM creation, memory slots, registers, CPUID/MSRs, execution, kicks and pending-I/O completion; arm64 follows |
| `whp` / `whp::emulator` | WHP operations and x86 instruction decoding for memory-access exits (reserved for M10) |
@@ -73,6 +74,29 @@ which `KvmVm` and `KvmVcpu` implement, so the VMM's vCPU workers and its mock
backend use one interface. On arm64, `Arm64Vcpu` sets MPIDR_EL1 (`set_mpidr`) and
the entry PC, X0 and PSTATE (`set_boot_registers`).
+## Linux x86_64 snapshot state
+
+`X86VmState` and `X86VcpuState` are owned KVM state images for the same host
+and KVM environment. Their wire format is unstable. Both implement Serde for
+`postcard::to_allocvec` and `postcard::from_bytes`. Callers own the snapshot
+container, RAM, device state and persistence.
+
+| Image | State |
+| --- | --- |
+| `X86VmState` | PIC master/slave and IOAPIC as `X86IrqchipState`, optional PIT, and KVM clock |
+| `X86VcpuState` | General and special registers, FPU, XSAVE, CPUID, MSRs, XCRs, debug registers, events, MP state, LAPIC, and TSC frequency |
+
+The vCPU decoder rejects truncated input and FPU payloads with a length other
+than the KVM ABI size. It checks the declared sequence lengths before reading
+elements and accepts up to 65,536 XSAVE words (256 KiB), 256 CPUID entries,
+and 4,096 MSR entries. These limits apply to decoding. The caller handles
+host compatibility and validation of register values.
+
+On Linux x86_64, `make test:unit:vmm` checks Postcard round trips, truncated
+input, and decode limits without `/dev/kvm`.
+
+## Host execution
+
macOS arm64 exports `HvfVm` and thread-bound `HvfVcpu`, which implement `Vm`,
`Vcpu` and `Arm64Vcpu` on Hypervisor.framework with the in-kernel GICv3 of
macOS 15. Design and research: [#2103](https://github.com/boxlite-ai/boxlite/issues/2103).
diff --git a/src/hypervisor/src/error.rs b/src/hypervisor/src/error.rs
index 5b8ebf0e0..ae6580c06 100644
--- a/src/hypervisor/src/error.rs
+++ b/src/hypervisor/src/error.rs
@@ -20,6 +20,11 @@ pub type Result<T> = std::result::Result<T, Error>;
pub enum Error {
/// Creating the VM or its interrupt controller failed.
CreateVm(io::Error),
+ /// Saving or restoring global VM state failed.
+ VmState {
+ operation: &'static str,
+ source: io::Error,
+ },
/// Mapping host memory into the guest failed.
MapMemory {
guest_addr: u64,
@@ -61,6 +66,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CreateVm(_) => f.write_str("failed to create the VM"),
+ Self::VmState { operation, .. } => write!(f, "failed to {operation} VM state"),
Self::MapMemory {
guest_addr, size, ..
} => write!(
@@ -94,6 +100,7 @@ impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::CreateVm(source)
+ | Self::VmState { source, .. }
| Self::MapMemory { source, .. }
| Self::UnmapMemory { source, .. }
| Self::CreateVcpu { source, .. }
@@ -182,6 +189,38 @@ mod tests {
}
}
+ #[test]
+ fn vm_state_errors_preserve_the_original_errno_and_kind() {
+ for operation in ["save", "restore"] {
+ // EACCES on both Linux and macOS.
+ let source = io::Error::from_raw_os_error(13);
+ let kind = source.kind();
+ let error = Error::VmState { operation, source };
+ let cause = error
+ .source()
+ .and_then(|source| source.downcast_ref::<io::Error>())
+ .expect("original host error");
+
+ assert!(
+ matches!(error, Error::VmState { operation: actual, .. } if actual == operation)
+ );
+ assert_eq!(cause.raw_os_error(), Some(13));
+ assert_eq!(cause.kind(), kind);
+ assert!(cause.source().is_none());
+ }
+ }
+
+ #[test]
+ fn vm_state_errors_identify_save_and_restore() {
+ for operation in ["save", "restore"] {
+ let error = Error::VmState {
+ operation,
+ source: io::Error::from_raw_os_error(13),
+ };
+ assert_eq!(error.to_string(), format!("failed to {operation} VM state"));
+ }
+ }
+
#[test]
fn unhandled_exit_identifies_the_vcpu_and_reason_without_a_host_cause() {
let error = Error::UnhandledExit {
diff --git a/src/hypervisor/src/lib.rs b/src/hypervisor/src/lib.rs
index 77651eb90..f0f62bc6e 100644
--- a/src/hypervisor/src/lib.rs
+++ b/src/hypervisor/src/lib.rs
@@ -27,6 +27,8 @@ pub use arm64::{Arm64BootRegisters, Arm64Vcpu, CpuOnResult};
mod x86;
#[cfg(target_arch = "x86_64")]
pub use x86::{X86BootRegisters, X86CpuidEntry, X86Msr, X86Segment, X86Vcpu, X86Vm};
+#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
+pub use x86::{X86IrqchipState, X86VcpuState, X86VmState};
pub use error::{Error, Result};
pub use exit::VcpuExit;
@@ -34,6 +36,13 @@ pub use memory::MemoryRegion;
pub use vcpu::{Vcpu, VcpuHandle};
pub use vm::Vm;
+/// One captured CPUID entry; `X86VcpuState::cpuid` is a vector of these.
+///
+/// Re-exported so callers can name the entry type without depending on
+/// `kvm-bindings` directly.
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub use kvm_bindings::kvm_cpuid_entry2;
+
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
mod hvf;
diff --git a/src/hypervisor/src/x86.rs b/src/hypervisor/src/x86.rs
index ca7198ab5..7759a5b69 100644
--- a/src/hypervisor/src/x86.rs
+++ b/src/hypervisor/src/x86.rs
@@ -77,3 +77,401 @@ pub trait X86Vcpu: Vcpu {
/// keep their reset state until INIT/SIPI.
fn set_boot_registers(&mut self, state: &X86BootRegisters) -> Result<()>;
}
+
+#[cfg(target_os = "linux")]
+const MAX_SNAPSHOT_CPUID_ENTRIES: usize = 256;
+
+/// VM-global KVM x86 platform state for the same host and KVM environment.
+/// The wire format is unstable. RAM, per-vCPU state, IRQ routing and
+/// device/irqfd configuration are separate.
+#[cfg(target_os = "linux")]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct X86VmState {
+ /// PIC master (0), PIC slave (1), IOAPIC (2), in that order.
+ pub irqchips: [X86IrqchipState; 3],
+ /// None only when the source never created an in-kernel PIT.
+ pub pit: Option<kvm_bindings::kvm_pit_state2>,
+ /// Full KVM clock image with guest nanoseconds, flags, realtime and host TSC.
+ pub clock: kvm_bindings::kvm_clock_data,
+}
+
+/// An owned IRQ-chip image with fully initialized backing storage.
+///
+/// Unlike a public raw union, the private image cannot be replaced with a
+/// partially initialized member. Constructors zero it before writing a payload;
+/// deserialization zero-fills the backing buffer. Exposes only shared access.
+#[cfg(target_os = "linux")]
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(transparent)]
+pub struct X86IrqchipState(kvm_bindings::kvm_irqchip);
+
+#[cfg(target_os = "linux")]
+impl X86IrqchipState {
+ /// Builds a PIC image (chip ID 0 or 1).
+ pub fn pic(chip_id: u32, pic: kvm_bindings::kvm_pic_state) -> Self {
+ let mut image = kvm_bindings::kvm_irqchip {
+ chip_id,
+ ..Default::default()
+ };
+ image.chip.pic = pic;
+ Self(image)
+ }
+
+ /// Builds the IOAPIC image (chip ID 2).
+ pub fn ioapic(ioapic: kvm_bindings::kvm_ioapic_state) -> Self {
+ let mut image = kvm_bindings::kvm_irqchip {
+ chip_id: 2,
+ ..Default::default()
+ };
+ image.chip.ioapic = ioapic;
+ Self(image)
+ }
+
+ /// Immutable ioctl image; mutable access would break initialization guarantees.
+ pub fn as_kvm(&self) -> &kvm_bindings::kvm_irqchip {
+ &self.0
+ }
+}
+
+#[cfg(target_os = "linux")]
+impl PartialEq for X86IrqchipState {
+ fn eq(&self, other: &Self) -> bool {
+ let (a, b) = (&self.0, &other.0);
+ if a.chip_id != b.chip_id || a.pad != b.pad {
+ return false;
+ }
+ // Compare the active payload, not the inactive union tail. The private
+ // image's constructors/decoder initialize every backing byte,
+ // even if a caller supplies a mismatched tag via pic() or decoding.
+ // SAFETY: that enforced invariant makes every union view initialized.
+ unsafe {
+ match a.chip_id {
+ 0 | 1 => a.chip.pic == b.chip.pic,
+ 2 => {
+ let (a, b) = (&a.chip.ioapic, &b.chip.ioapic);
+ a.base_address == b.base_address
+ && a.ioregsel == b.ioregsel
+ && a.id == b.id
+ && a.irr == b.irr
+ && a.pad == b.pad
+ && a.redirtbl
+ .iter()
+ .zip(&b.redirtbl)
+ .all(|(a, b)| a.bits == b.bits)
+ }
+ // Unknown IDs remain comparable; KVM handles ioctl validation.
+ _ => a.chip.dummy == b.chip.dummy,
+ }
+ }
+ }
+}
+
+/// A paused KVM x86 CPU image specific to the host CPU and KVM/kernel version.
+/// The wire format is unstable.
+///
+/// Includes the entire XSAVE area (including AVX and newer enabled components)
+/// in addition to the dedicated FPU image. CPUID/MSR flexible arrays are owned.
+/// The LAPIC image represents the x2APIC register range. The TSC frequency is
+/// per-vCPU. Nested virtualization, Hyper-V SynIC, guest-debug configuration,
+/// VM-wide state and RAM are outside this image.
+#[cfg(target_os = "linux")]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct X86VcpuState {
+ pub regs: kvm_bindings::kvm_regs,
+ pub sregs: kvm_bindings::kvm_sregs,
+ #[serde(with = "fpu_serde")]
+ pub fpu: kvm_bindings::kvm_fpu,
+ /// Complete XSAVE buffer, including the kernel-sized flexible tail.
+ /// Decoding permits at most 65536 u32 words (256 KiB), a policy ceiling
+ /// with room for host XSTATE components beyond the fixed KVM region.
+ #[serde(deserialize_with = "vcpu_state_serde::words::<_, _, 65536>")]
+ pub xsave: Vec<u32>,
+ /// Captured CPUID leaves, with a decode limit of 256 entries matching KVM.
+ #[serde(deserialize_with = "vcpu_state_serde::entries::<_, _, MAX_SNAPSHOT_CPUID_ENTRIES>")]
+ pub cpuid: Vec<kvm_bindings::kvm_cpuid_entry2>,
+ /// Readable KVM-advertised MSRs; decoding permits at most 4096 entries.
+ /// This is a decoding policy, not KVM's per-ioctl MSR batch limit.
+ #[serde(deserialize_with = "vcpu_state_serde::entries::<_, _, 4096>")]
+ pub msrs: Vec<kvm_bindings::kvm_msr_entry>,
+ pub xcrs: kvm_bindings::kvm_xcrs,
+ pub debug_regs: kvm_bindings::kvm_debugregs,
+ pub events: kvm_bindings::kvm_vcpu_events,
+ pub mp_state: kvm_bindings::kvm_mp_state,
+ pub lapic: kvm_bindings::kvm_lapic_state,
+ pub tsc_khz: u32,
+}
+
+// Bounds are checked before reading elements; never reserve from an untrusted
+// length. These guards also protect callers that decode X86VcpuState directly.
+#[cfg(target_os = "linux")]
+mod vcpu_state_serde {
+ use serde::{
+ Deserialize, Deserializer,
+ de::{self, SeqAccess, Visitor},
+ };
+ use std::{fmt, marker::PhantomData};
+
+ fn bounded<'de, D, T, const N: usize>(d: D) -> Result<Vec<T>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: Deserialize<'de>,
+ {
+ struct Bounded<T, const N: usize>(PhantomData<T>);
+ impl<'de, T: Deserialize<'de>, const N: usize> Visitor<'de> for Bounded<T, N> {
+ type Value = Vec<T>;
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "at most {N} CPU entries with an exact declared length")
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
+ let len = seq
+ .size_hint()
+ .filter(|&len| len <= N)
+ .ok_or_else(|| de::Error::custom("CPU sequence too long"))?;
+ let mut values = Vec::new();
+ for i in 0..len {
+ values.push(
+ seq.next_element()?
+ .ok_or_else(|| de::Error::invalid_length(i, &self))?,
+ );
+ }
+ if seq.next_element::<de::IgnoredAny>()?.is_some() {
+ return Err(de::Error::invalid_length(len + 1, &self));
+ }
+ Ok(values)
+ }
+ }
+ d.deserialize_seq(Bounded::<T, N>(PhantomData))
+ }
+
+ pub(super) fn words<'de, D, T, const N: usize>(d: D) -> Result<Vec<T>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: Deserialize<'de>,
+ {
+ bounded::<D, T, N>(d)
+ }
+
+ pub(super) fn entries<'de, D, T, const N: usize>(d: D) -> Result<Vec<T>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: Deserialize<'de>,
+ {
+ bounded::<D, T, N>(d)
+ }
+}
+
+// kvm-bindings omits kvm_fpu serde. Encode explicit fields into an exact ABI-
+// sized byte buffer rather than reading C padding or using variable-width ints.
+#[cfg(target_os = "linux")]
+mod fpu_serde {
+ use kvm_bindings::kvm_fpu;
+ use serde::{Deserialize, Deserializer, Serializer, de};
+
+ pub(super) fn serialize<S: Serializer>(f: &kvm_fpu, s: S) -> Result<S::Ok, S::Error> {
+ let mut bytes = [0u8; size_of::<kvm_fpu>()];
+ let mut offset = 0;
+ macro_rules! put {
+ ($value:expr) => {{
+ let value = $value;
+ bytes[offset..offset + value.len()].copy_from_slice(&value);
+ offset += value.len();
+ }};
+ }
+ for v in f.fpr {
+ put!(v);
+ }
+ put!(f.fcw.to_le_bytes());
+ put!(f.fsw.to_le_bytes());
+ put!([f.ftwx, f.pad1]);
+ put!(f.last_opcode.to_le_bytes());
+ put!(f.last_ip.to_le_bytes());
+ put!(f.last_dp.to_le_bytes());
+ for v in f.xmm {
+ put!(v);
+ }
+ put!(f.mxcsr.to_le_bytes());
+ put!(f.pad2.to_le_bytes());
+ debug_assert_eq!(offset, bytes.len());
+ s.serialize_bytes(&bytes)
+ }
+
+ pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<kvm_fpu, D::Error> {
+ // Borrow first: no declared length causes allocation, even usize::MAX.
+ let bytes = <&[u8]>::deserialize(d)?;
+ if bytes.len() != size_of::<kvm_fpu>() {
+ return Err(de::Error::custom("incorrect FPU ABI size"));
+ }
+ let mut offset = 0;
+ macro_rules! get {
+ ($n:expr) => {{
+ let mut value = [0u8; $n];
+ value.copy_from_slice(&bytes[offset..offset + $n]);
+ offset += $n;
+ value
+ }};
+ }
+ let mut f = kvm_fpu::default();
+ for v in &mut f.fpr {
+ *v = get!(16);
+ }
+ f.fcw = u16::from_le_bytes(get!(2));
+ f.fsw = u16::from_le_bytes(get!(2));
+ f.ftwx = get!(1)[0];
+ f.pad1 = get!(1)[0];
+ f.last_opcode = u16::from_le_bytes(get!(2));
+ f.last_ip = u64::from_le_bytes(get!(8));
+ f.last_dp = u64::from_le_bytes(get!(8));
+ for v in &mut f.xmm {
+ *v = get!(16);
+ }
+ f.mxcsr = u32::from_le_bytes(get!(4));
+ f.pad2 = u32::from_le_bytes(get!(4));
+ debug_assert_eq!(offset, bytes.len());
+ Ok(f)
+ }
+}
+
+#[cfg(all(test, target_os = "linux"))]
+mod tests {
+ #[test]
+ fn cpu_sequences_enforce_declared_count_and_bound_before_elements() {
+ use serde::{
+ Deserializer,
+ de::{
+ DeserializeSeed, SeqAccess, Visitor,
+ value::{Error, U8Deserializer},
+ },
+ };
+ struct Sequence {
+ declared: usize,
+ actual: usize,
+ reads: usize,
+ }
+ impl<'de> SeqAccess<'de> for &mut Sequence {
+ type Error = Error;
+ fn size_hint(&self) -> Option<usize> {
+ Some(self.declared)
+ }
+ fn next_element_seed<T: DeserializeSeed<'de>>(
+ &mut self,
+ seed: T,
+ ) -> Result<Option<T::Value>, Error> {
+ self.reads += 1;
+ if self.actual == 0 {
+ return Ok(None);
+ }
+ self.actual -= 1;
+ seed.deserialize(U8Deserializer::new(42)).map(Some)
+ }
+ }
+ impl<'de> Deserializer<'de> for &mut Sequence {
+ type Error = Error;
+ fn deserialize_any<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Error> {
+ v.visit_seq(self)
+ }
+ serde::forward_to_deserialize_any! {
+ bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
+ }
+ }
+ for bound in [65536, 256, 4096] {
+ // No element can be read, hence no element storage can be allocated.
+ let mut seq = Sequence {
+ declared: bound + 1,
+ actual: 1,
+ reads: 0,
+ };
+ let error = match bound {
+ 65536 => super::vcpu_state_serde::words::<_, u32, 65536>(&mut seq).unwrap_err(),
+ 256 => super::vcpu_state_serde::entries::<_, kvm_bindings::kvm_cpuid_entry2, 256>(
+ &mut seq,
+ )
+ .unwrap_err(),
+ _ => super::vcpu_state_serde::entries::<_, kvm_bindings::kvm_msr_entry, 4096>(
+ &mut seq,
+ )
+ .unwrap_err(),
+ };
+ assert!(error.to_string().contains("too long"));
+ assert_eq!(seq.reads, 0);
+ }
+ for (declared, actual) in [(0, 1), (1, 0), (1, 2), (1, 1)] {
+ let mut seq = Sequence {
+ declared,
+ actual,
+ reads: 0,
+ };
+ let result = super::vcpu_state_serde::words::<_, u8, 2>(&mut seq);
+ assert_eq!(result.is_ok(), declared == actual);
+ }
+ }
+
+ #[test]
+ fn snapshot_state_supports_serde_and_equality() {
+ fn assert_traits<T: serde::Serialize + for<'de> serde::Deserialize<'de> + PartialEq>() {}
+ assert_traits::<super::X86VcpuState>();
+ }
+ #[test]
+ fn vm_snapshot_state_supports_serde_and_equality() {
+ fn assert_traits<T: serde::Serialize + for<'de> serde::Deserialize<'de> + PartialEq>() {}
+ assert_traits::<super::X86VmState>();
+ }
+
+ #[test]
+ fn vm_snapshot_pic_only_input_compares_active_payload() {
+ use super::{X86IrqchipState, X86VmState};
+ use kvm_bindings::{kvm_ioapic_state, kvm_pic_state};
+ let mut state = X86VmState {
+ // Only PIC payloads are supplied, never a full raw union image.
+ irqchips: [
+ X86IrqchipState::pic(
+ 0,
+ kvm_pic_state {
+ imr: 0xa5,
+ ..Default::default()
+ },
+ ),
+ X86IrqchipState::pic(1, kvm_pic_state::default()),
+ X86IrqchipState::ioapic(kvm_ioapic_state::default()),
+ ],
+ pit: None,
+ clock: Default::default(),
+ };
+ let same = state.clone();
+ assert_eq!(state, same);
+ state.irqchips[0] = X86IrqchipState::pic(
+ 0,
+ kvm_pic_state {
+ imr: 0x5a,
+ ..Default::default()
+ },
+ );
+ assert_ne!(state, same);
+ // A mismatched constructor tag is also initialized: equality must not
+ // read uninitialized bytes even when the tag selects another payload.
+ state.irqchips[0] = X86IrqchipState::pic(2, kvm_pic_state::default());
+ assert_eq!(state, state.clone());
+ // Inactive PIC-tail bytes do not affect equality after decoding.
+ use serde::{
+ Deserialize,
+ de::value::{BorrowedBytesDeserializer, Error},
+ };
+ let mut bytes = vec![0u8; size_of::<kvm_bindings::kvm_irqchip>()];
+ let zero =
+ X86IrqchipState::deserialize(BorrowedBytesDeserializer::<Error>::new(&bytes)).unwrap();
+ *bytes.last_mut().unwrap() = 0x7f;
+ let tail =
+ X86IrqchipState::deserialize(BorrowedBytesDeserializer::<Error>::new(&bytes)).unwrap();
+ assert_eq!(zero, tail);
+ let mut ioapic = kvm_ioapic_state::default();
+ ioapic.redirtbl[7].bits = 0x71 | (1 << 16) | (3 << 56);
+ let mut different_ioapic = same.clone();
+ different_ioapic.irqchips[2] = X86IrqchipState::ioapic(ioapic);
+ assert_ne!(different_ioapic, same);
+ }
+}
+
+#[cfg(all(test, target_os = "linux"))]
+#[path = "../tests/snapshot/mod.rs"]
+mod codec_tests;
diff --git a/src/hypervisor/tests/snapshot/mod.rs b/src/hypervisor/tests/snapshot/mod.rs
new file mode 100644
index 000000000..b8d09dc54
--- /dev/null
+++ b/src/hypervisor/tests/snapshot/mod.rs
@@ -0,0 +1,175 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! Postcard coverage for the host-specific state images, without a VMM envelope.
+
+use super::{X86IrqchipState, X86VcpuState, X86VmState};
+
+fn cpu() -> X86VcpuState {
+ let mut state = X86VcpuState {
+ regs: Default::default(),
+ sregs: Default::default(),
+ fpu: Default::default(),
+ xsave: vec![0, 1, 2, 3],
+ cpuid: vec![],
+ msrs: vec![],
+ xcrs: Default::default(),
+ debug_regs: Default::default(),
+ events: Default::default(),
+ mp_state: Default::default(),
+ lapic: Default::default(),
+ tsc_khz: 1234,
+ };
+ let s = &mut state;
+ s.regs.rax = 0x123456789;
+ s.regs.rip = 0x876543210;
+ s.sregs.cs.selector = 16;
+ s.sregs.cr3 = 0x5000;
+ s.fpu.fpr[3] = [17; 16];
+ s.fpu.xmm[15] = [42; 16];
+ s.fpu.fcw = 0x37f;
+ s.fpu.fsw = 0x1234;
+ s.fpu.ftwx = 0x5a;
+ s.fpu.last_opcode = 0xabcd;
+ s.fpu.last_ip = 0x1234567887654321;
+ s.fpu.last_dp = 0xfedcba9876543210;
+ s.fpu.mxcsr = 0x1f80;
+ s.fpu.pad1 = 1;
+ s.fpu.pad2 = 2;
+ s.xsave = vec![0x12345678; 1024];
+ s.cpuid.resize(2, Default::default());
+ s.cpuid[0].function = 7;
+ s.cpuid[0].index = 1;
+ s.cpuid[0].flags = 3;
+ s.cpuid[0].eax = 5;
+ s.cpuid[0].ebx = 7;
+ s.cpuid[0].ecx = 9;
+ s.cpuid[0].edx = 11;
+ s.cpuid[0].padding = [13, 15, 17];
+ s.cpuid[1].function = 0xd;
+ s.cpuid[1].eax = 7;
+ s.cpuid[1].ebx = 832;
+ s.cpuid[1].ecx = 4096;
+ s.msrs.resize(2, Default::default());
+ s.msrs[0].index = 0x10;
+ s.msrs[0].data = 0x123456789;
+ s.msrs[0].reserved = 7;
+ s.msrs[1].index = 0x1b;
+ s.xcrs.nr_xcrs = 1;
+ s.xcrs.xcrs[0].value = 7;
+ s.debug_regs.dr7 = 0x400;
+ s.events.exception.nr = 14;
+ s.mp_state.mp_state = 3;
+ s.lapic.regs[0] = 42;
+ s.tsc_khz = 2345678;
+ state
+}
+
+fn round_trip<T>(state: &T)
+where
+ T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
+{
+ let bytes = postcard::to_allocvec(state).unwrap();
+ assert_eq!(&postcard::from_bytes::<T>(&bytes).unwrap(), state);
+ for end in 0..bytes.len() {
+ assert!(
+ postcard::from_bytes::<T>(&bytes[..end]).is_err(),
+ "truncated at {end}"
+ );
+ }
+}
+
+#[test]
+fn cpu_postcard_round_trips_every_state_field_and_rejects_truncation() {
+ round_trip(&cpu());
+}
+
+#[test]
+fn platform_postcard_round_trips_created_and_absent_pit() {
+ let mut state = X86VmState {
+ irqchips: [
+ X86IrqchipState::pic(
+ 0,
+ kvm_bindings::kvm_pic_state {
+ imr: 0xa5,
+ ..Default::default()
+ },
+ ),
+ X86IrqchipState::pic(
+ 1,
+ kvm_bindings::kvm_pic_state {
+ irr: 0x24,
+ ..Default::default()
+ },
+ ),
+ X86IrqchipState::ioapic(Default::default()),
+ ],
+ pit: Some(Default::default()),
+ clock: Default::default(),
+ };
+ let mut ioapic = kvm_bindings::kvm_ioapic_state::default();
+ ioapic.redirtbl[7].bits = 0x71 | (1 << 16) | (3 << 56);
+ state.irqchips[2] = X86IrqchipState::ioapic(ioapic);
+ state.pit.as_mut().unwrap().channels[2].count = 0x7654;
+ state.clock.clock = 0x23456789;
+ state.clock.realtime = 0x3456789;
+ state.clock.host_tsc = 0x456789;
+ round_trip(&state);
+ state.pit = None;
+ round_trip(&state);
+}
+
+#[test]
+fn cpu_postcard_enforces_flexible_array_bounds() {
+ let mut state = cpu();
+ for count in [0, 65535, 65536, 65537] {
+ state.xsave.resize(count, 0x12345678);
+ let bytes = postcard::to_allocvec(&state).unwrap();
+ assert_eq!(
+ postcard::from_bytes::<X86VcpuState>(&bytes).is_ok(),
+ count <= 65536
+ );
+ }
+ state.xsave.clear();
+ for count in [0, 255, 256, 257] {
+ state.cpuid.resize(count, Default::default());
+ let bytes = postcard::to_allocvec(&state).unwrap();
+ assert_eq!(
+ postcard::from_bytes::<X86VcpuState>(&bytes).is_ok(),
+ count <= 256
+ );
+ }
+ state.cpuid.clear();
+ for count in [0, 4095, 4096, 4097] {
+ state.msrs.resize(count, Default::default());
+ let bytes = postcard::to_allocvec(&state).unwrap();
+ assert_eq!(
+ postcard::from_bytes::<X86VcpuState>(&bytes).is_ok(),
+ count <= 4096
+ );
+ }
+}
+
+#[test]
+fn fpu_postcard_rejects_non_abi_lengths() {
+ #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+ struct Fpu(#[serde(with = "super::fpu_serde")] kvm_bindings::kvm_fpu);
+ struct Blob<'a>(&'a [u8]);
+ impl serde::Serialize for Blob<'_> {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_bytes(self.0)
+ }
+ }
+ let state = Fpu(cpu().fpu);
+ let encoded = postcard::to_allocvec(&state).unwrap();
+ assert_eq!(postcard::from_bytes::<Fpu>(&encoded).unwrap(), state);
+ // Obtain the ABI payload from the production serializer, not a second
+ // implementation of the FPU layout or its postcard length prefix.
+ let payload: &[u8] = postcard::from_bytes(&encoded).unwrap();
+ for len in [0, payload.len() - 1, payload.len() + 1] {
+ let mut wrong = payload.to_vec();
+ wrong.resize(len, 0);
+ let bytes = postcard::to_allocvec(&Blob(&wrong)).unwrap();
+ assert!(postcard::from_bytes::<Fpu>(&bytes).is_err(), "length {len}");
+ }
+}