Skip to content

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

feat(vmm): export split VM state and RAM snapshots via VmControl (#2966)

lfld28772cfcf717aae
diff --git a/Cargo.lock b/Cargo.lock
index 0dbc27fae..2f3a9fb27 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -821,6 +821,8 @@ dependencies = [
"libc",
"linux-loader",
"mio 1.2.0",
+ "postcard",
+ "serde",
"tempfile",
"thiserror 2.0.18",
"tracing",
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.md
index ca66c1b53..a6712bad6 100644
--- a/docs/contributing/architecture/vmm/README.md
+++ b/docs/contributing/architecture/vmm/README.md
@@ -585,6 +585,47 @@ setup. Its empty disk registry makes `resize_disk()` return `InvalidInput`.
- **SIGTERM.** The shim asks the guest to shut down over gRPC and re-raises
the signal to end the process.
+### Snapshot export
+
+`VmControl::export(state_path, memory_path)` reserves the control slot for a
+paused device-less VM on Linux x86_64. While export is pending or active,
+`request_pause`, `resume`, and another `export` are rejected. `Vm` currently has
+no public device-less constructor (`Vm::new_device_less` is crate-internal for
+tests). Once all vCPUs have completed pending I/O and parked, the driver saves
+the VM platform state.
+If this fails, the driver releases the slot and returns the error without
+dispatching vCPU capture. On success, each vCPU saves its state on its owning
+thread. The driver collects all replies, including failures, and writes the
+platform state and ID-ordered vCPU records only if every capture succeeds.
+Following `boxlite-hypervisor`'s capture exclusions, x86 machine state excludes
+nested virtualization, Hyper-V SynIC, and guest-debug state. Pausing stops
+vCPUs but not KVM's in-kernel timers, so platform capture is non-atomic; PIT
+restore loses sub-tick phase and can re-arm one-shot modes (0, 1, and 4).
+
+The state file has a 32-byte little-endian header containing the eight-byte
+magic `BXLVMST1`, `u32` version `1`, `u32` vCPU count, `u64` RAM length, and
+`u64` machine-state length. Postcard encodes the following vCPU and platform
+state. The memory file contains raw RAM from offset zero in `ram.ranges()`
+order, skipping `[3 GiB, 4 GiB)`. Its length equals the header's RAM length.
+
+The driver creates both files exclusively with `create_new` and mode `0600`
+(subject to the process `umask`) and writes them synchronously without
+interruption by stop requests. Relative paths are resolved against the current
+working directory when the export is admitted. The driver handles a stop after
+an in-flight platform `save_state` or file writeout finishes. If stop is requested
+during a vCPU's `save_state`, the driver abandons the capture request so
+`export()` returns `TerminalOutcome` without waiting, but `run()` still waits
+for the vCPU thread to exit. `finish_export` releases the control slot and
+returns `TerminalOutcome` if the VM is terminal. The driver skips `fsync`, and
+dropping the files ignores delayed `close(2)` errors. `Ok(())` provides no
+guarantee of power-loss durability.
+
+Callers must have exclusive use of both target paths during export. Existing
+targets return `AlreadyExists` and retain their contents. If export fails
+after creating a file, `boxlite-vmm` leaves it in place, even if partially
+written. The caller (runtime or runner) is responsible for cleanup, for example
+by exporting into a temporary directory and atomically renaming it on success.
+
### Where the engine plugs in (M2)
- **Engine choice.** The `native-vmm` experimental token gates
diff --git a/make/coverage.mk b/make/coverage.mk
index 3b6e7f614..a9fbdd0c3 100644
--- a/make/coverage.mk
+++ b/make/coverage.mk
@@ -77,7 +77,7 @@ codecov: coverage\:lcov
coverage\:vmm\:kvm: _ensure-kvm
@cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \
-p boxlite-hypervisor -p boxlite-vmm --lib --run-ignored only --test-threads=1 \
- -E '(package(boxlite-hypervisor) & test(/^kvm::/)) | (package(boxlite-vmm) & (test(/^vm::tests::/) | test(tests::kvm::)))'
+ -E '(package(boxlite-hypervisor) & test(/^kvm::/)) | (package(boxlite-vmm) & (test(/^vm::tests::/) | test(tests::kvm::) | test(snapshot::execution_tests::kvm_)))'
@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.info
# Add the real-kernel boots of VMM_KERNEL to the same profiles, listed the same way.
diff --git a/make/test.mk b/make/test.mk
index 64a15835a..c3599b140 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -308,7 +308,7 @@ test\:integration\:vmm\:kvm: _ensure-kvm
@cargo test -p boxlite-hypervisor -p boxlite-vmm --lib --no-run
@status=0; \
timeout 60s cargo test -p boxlite-hypervisor --lib kvm:: -- --ignored --test-threads=1 || status=1; \
- timeout 60s cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 vm::tests:: tests::kvm:: || status=1; \
+ timeout 60s cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 vm::tests:: tests::kvm:: snapshot::execution_tests::kvm_ || status=1; \
exit $$status
# make vmm:boot produces this kernel by default.
diff --git a/src/vmm/Cargo.toml b/src/vmm/Cargo.toml
index a7c318240..cb6a56cb3 100644
--- a/src/vmm/Cargo.toml
+++ b/src/vmm/Cargo.toml
@@ -33,6 +33,8 @@ virtio-queue = { version = "0.18.0", features = ["test-utils"] }
vm-superio = "0.8.2"
[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]
+serde = { version = "1.0.228", features = ["derive"] }
+postcard = { version = "1", default-features = false, features = ["alloc"] }
linux-loader = { version = "0.14.0", default-features = false, features = ["elf"] }
bitflags = "2"
libc = "0.2"
diff --git a/src/vmm/README.md b/src/vmm/README.md
index c283a7e9e..c200d850f 100644
--- a/src/vmm/README.md
+++ b/src/vmm/README.md
@@ -35,8 +35,9 @@ boxlite-vmm
| Module | Responsibility |
| --- | --- |
| `vm` | `Vm<H>`: validate the configuration, allocate and register RAM on host backend `H`, compose the devices through `build` and `devices::add_all`, load the boot data, and run the vCPUs until the first event; `with_backend` is the test seam |
-| `control` | `VmControl` provides runtime controls for VM status, pause, resume, stop, and disk resize by configured ID |
-| `lifecycle` | `Lifecycle` coordinates the one-shot run, pause epochs, and the shared stop latch |
+| `control` | `VmControl` provides runtime controls for VM status, pause, resume, export, stop, and `resize_disk` by configured ID |
+| `lifecycle` | `Lifecycle` coordinates the one-shot run, pause epochs, the control mailbox, and the shared stop latch |
+| `snapshot` | Captures and exports machine state and raw guest RAM for paused device-less VMs on Linux x86_64 |
| `boot` | Linux x86_64 boot: `prepare` loads the pinned ELF kernel through linux-loader, places an optional initramfs at the top of low RAM, writes the zero page, E820 map, command line and MP table, and sets up the 64-bit entry state (GDT, identity page tables, registers) |
| `config` | `VmConfig`: CPU, RAM, kernel and initramfs, disks, optional filesystem/vsock/network, and virtio console; 1..=64 vCPUs, nonzero `u32` MiB of RAM whose layout must pass host and boot address checks, a printable-ASCII command line under 2048 bytes, and at most 8 disks |
| `error` | VMM errors that keep the hypervisor's cause chain, including a virtio device that cannot continue |
@@ -739,6 +740,50 @@ workers, and finishing the console. A worker join timeout leaves the status at
Dropping the VM handles RAM teardown and publishes `Exited` to surviving
controls, including when the VM never ran.
+### Exporting a paused VM
+
+On Linux x86_64, call `control.export(state_path, memory_path)` from a
+control thread while a device-less VM is paused. `Vm` currently has no public
+device-less constructor (`Vm::new_device_less` is crate-internal for tests).
+Other hosts return `ControlReason::Unsupported`. Other handles can observe the
+pause during capture and I/O. A competing `request_pause`, `resume`, or
+`export` returns `InvalidState`. Relative paths are resolved against the current
+working directory when the export is admitted.
+
+The driver saves platform state first. If it succeeds, each parked vCPU
+saves its state on its owning thread. The driver collects all replies
+and sorts the vCPU records by ID before writing either file. Following
+`boxlite-hypervisor`'s capture exclusions, x86 machine state excludes nested
+virtualization, Hyper-V SynIC, and guest-debug state. Pausing stops vCPUs but
+not KVM's in-kernel timers, so platform capture is non-atomic; PIT restore
+loses sub-tick phase and can re-arm one-shot modes (0, 1, and 4).
+
+Export creates both files exclusively with `create_new` and mode `0600`
+(subject to the process `umask`). It skips `fsync`, and dropping the files
+ignores delayed `close(2)` errors. `Ok(())` provides no guarantee of power-loss
+durability. An existing target, including reuse of the state path for memory,
+returns `Error::Snapshot` with `AlreadyExists` without changing its contents.
+
+Callers must have exclusive use of both target paths during export. If export
+fails after creating a file, `boxlite-vmm` leaves it in place, even if partially
+written. The caller (runtime or runner) is responsible for cleanup, for example
+by exporting into a temporary directory and atomically renaming it on success.
+
+Capture and I/O failures leave a live VM paused. File writeout is synchronous
+and is not interrupted by a stop request. The driver handles the stop after
+an in-flight platform `save_state` or file writeout finishes. If stop is
+requested during a vCPU's `save_state`, the driver abandons the capture request
+so `export()` returns `TerminalOutcome` without waiting, but `run()` still waits
+for the vCPU thread to exit. If the VM is terminal at the final lifecycle check,
+`finish_export` returns `TerminalOutcome`.
+
+The state file starts with a 32-byte little-endian header with the magic
+`BXLVMST1`, followed by Postcard machine state with vCPU records in ID order.
+The memory file contains exactly the header's declared RAM byte count.
+Raw RAM starts at offset zero and follows guest physical address order,
+skipping the `[3 GiB, 4 GiB)` PCI hole. Machine state targets the same host
+and KVM environment.
+
## Long-mode entry
On Linux x86_64, `boot::entry::long_mode_entry(ram, entry, boot_params, plan)`
diff --git a/src/vmm/src/control.rs b/src/vmm/src/control.rs
index 9c11ce33d..d1bc705da 100644
--- a/src/vmm/src/control.rs
+++ b/src/vmm/src/control.rs
@@ -3,7 +3,7 @@
//! Runtime controls for a VM.
-use std::{collections::HashMap, io, sync::Arc, time::Duration};
+use std::{collections::HashMap, io, path::Path, sync::Arc, time::Duration};
use crate::{
MemoryStatus,
@@ -31,6 +31,12 @@ impl VmControl {
}
/// Requests a stop, including before execution starts, without waiting for exit.
+ ///
+ /// A stop request does not interrupt an in-flight platform `save_state` or
+ /// snapshot file writeout. The driver handles the stop after that work
+ /// finishes. If stop is requested during a vCPU's `save_state`, the driver
+ /// abandons the capture request so [`Self::export`] returns `TerminalOutcome`
+ /// without waiting, but `Vm::run()` still waits for the vCPU thread to exit.
pub fn stop(&self) {
self.lifecycle.stop();
}
@@ -47,6 +53,52 @@ impl VmControl {
self.lifecycle.resume()
}
+ /// Exports a paused device-less VM on Linux x86_64 to new state and raw RAM files.
+ /// Pausing stops vCPUs but not KVM's in-kernel timers, so platform capture is
+ /// non-atomic; PIT restore loses sub-tick phase and can re-arm one-shot modes
+ /// (0, 1, and 4).
+ ///
+ /// While export is pending or active, `request_pause`, `resume`, and another
+ /// `export` are rejected. File writeout is synchronous and is not interrupted
+ /// by a stop request. If the VM is terminal at the final lifecycle check,
+ /// export returns `TerminalOutcome`.
+ ///
+ /// Both files are created exclusively with `create_new` and mode `0600`
+ /// (subject to the process `umask`). An existing target returns `AlreadyExists`
+ /// without changing its contents.
+ /// Export skips `fsync`, and dropping the files ignores delayed `close(2)` errors.
+ /// `Ok(())` provides no guarantee of power-loss durability.
+ ///
+ /// `Vm` currently has no public device-less constructor, so `export()` only
+ /// applies to device-less VMs. Callers must have exclusive use of both
+ /// target paths during export. If export fails after creating a file,
+ /// `boxlite-vmm` leaves it in place, even if partially written. The caller
+ /// (runtime or runner) is responsible for cleanup, for example by exporting
+ /// into a temporary directory and atomically renaming it on success.
+ /// Relative paths are resolved against the current working directory when
+ /// the export is admitted.
+ pub fn export(
+ &self,
+ state_path: impl AsRef<Path>,
+ memory_path: impl AsRef<Path>,
+ ) -> Result<()> {
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ {
+ self.lifecycle
+ .submit_export(state_path.as_ref(), memory_path.as_ref())?
+ .recv()
+ .unwrap_or_else(|_| Err(crate::lifecycle::export_terminated()))
+ }
+ #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
+ {
+ let _ = (state_path, memory_path);
+ Err(crate::Error::Control {
+ operation: "export",
+ reason: crate::ControlReason::Unsupported,
+ })
+ }
+ }
+
/// Waits for the current pause epoch, including a reserved or queued pause.
/// A zero timeout checks the current condition while holding the lock.
///
@@ -150,3 +202,7 @@ impl ControlRegistry {
Ok(requests)
}
}
+
+#[cfg(all(test, not(all(target_os = "linux", target_arch = "x86_64"))))]
+#[path = "../tests/snapshot/image.rs"]
+mod snapshot_tests;
diff --git a/src/vmm/src/error.rs b/src/vmm/src/error.rs
index 7d398c871..95e0e3460 100644
--- a/src/vmm/src/error.rs
+++ b/src/vmm/src/error.rs
@@ -10,7 +10,10 @@ pub type Result<T> = std::result::Result<T, Error>;
/// Why a VM control operation was refused or failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[non_exhaustive]
pub enum ControlReason {
+ /// The operation is unavailable on this host platform.
+ Unsupported,
/// The operation is unavailable in the current lifecycle state.
InvalidState,
/// The operation requires a device-less configuration.
@@ -24,6 +27,7 @@ pub enum ControlReason {
impl fmt::Display for ControlReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
+ Self::Unsupported => "operation is unsupported on this host platform",
Self::InvalidState => "invalid state",
Self::UnsupportedDevice => "operation requires a device-less VM",
Self::DeadlineTimeout => "vCPU acknowledgements are still incomplete",
@@ -44,6 +48,8 @@ pub enum Error {
operation: &'static str,
reason: ControlReason,
},
+ /// Encoding or writing a VM snapshot failed.
+ Snapshot(io::Error),
/// The vCPU count is outside `1..=config::MAX_VCPUS`.
InvalidVcpuCount(u8),
/// Opening or configuring filesystem exports failed.
@@ -134,6 +140,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Control { operation, reason } => write!(f, "{operation}: {reason}"),
+ Self::Snapshot(source) => write!(f, "snapshot: {source}"),
Self::Vsock(_) => f.write_str("failed to configure vsock bridges"),
Self::Filesystem(_) => f.write_str("failed to configure virtio-fs exports"),
Self::InvalidVcpuCount(count) => write!(f, "invalid vCPU count: {count}"),
@@ -234,6 +241,7 @@ impl error::Error for Error {
| Self::VcpuPanicked { .. }
| Self::AlreadyRan => None,
Self::Vsock(source)
+ | Self::Snapshot(source)
| Self::Filesystem(source)
| Self::HostMemoryCapability(source)
| Self::PlanHotplugMemory { source, .. }
diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rs
index dcc7f3299..c60039cd0 100644
--- a/src/vmm/src/lib.rs
+++ b/src/vmm/src/lib.rs
@@ -56,6 +56,8 @@ mod hotplug;
mod irq;
pub(crate) mod lifecycle;
mod memory;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+mod snapshot;
#[cfg(any(test, target_arch = "x86_64"))]
mod vcpu;
#[cfg_attr(
diff --git a/src/vmm/src/lifecycle.rs b/src/vmm/src/lifecycle.rs
index a107020cb..a5c8ebf39 100644
--- a/src/vmm/src/lifecycle.rs
+++ b/src/vmm/src/lifecycle.rs
@@ -6,6 +6,16 @@ use std::{
time::Duration,
};
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+use boxlite_hypervisor::{X86Vm, X86VmState};
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+use std::{path::Path, sync::mpsc};
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+use crate::snapshot::{
+ export::Request,
+ state::{MachineState, VcpuRecord},
+};
use crate::{
config::MAX_VCPUS,
error::{ControlReason, Error, Result},
@@ -32,10 +42,22 @@ pub enum VmStatus {
Exited,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Debug)]
enum Command {
Park(u64),
+ #[cfg_attr(not(any(test, target_arch = "x86_64")), expect(dead_code))]
Resume(u64),
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ Export(Request),
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ Capture {
+ pending: u64,
+ request: Request,
+ platform: Box<X86VmState>,
+ replies: Vec<Result<VcpuRecord>>,
+ },
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ Exporting,
}
#[derive(Debug)]
@@ -44,7 +66,7 @@ struct LifecycleState {
#[cfg(any(test, target_arch = "x86_64"))]
run_claimed: bool,
sender: Option<EventSender>,
- /// Exclusive slot for a control operation awaiting the driver.
+ /// Exclusive slot, retained through the final export terminal check.
command: Option<Command>,
epoch: u64,
completed_epoch: u64,
@@ -119,7 +141,6 @@ impl Lifecycle {
// Serialize setting the vCPU stop latch with admitting the first run.
state.sender().send(Event::StopRequested);
state.status = VmStatus::Stopping;
- state.command = None;
self.changed.notify_all();
}
@@ -167,13 +188,107 @@ impl Lifecycle {
Ok(())
}
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ pub(crate) fn submit_export(
+ &self,
+ state_path: &Path,
+ memory_path: &Path,
+ ) -> Result<mpsc::Receiver<Result<()>>> {
+ let mut state = self.state();
+ if state.is_terminal() {
+ return Err(control_error("export", ControlReason::InvalidState));
+ }
+ if !self.device_less {
+ return Err(control_error("export", ControlReason::UnsupportedDevice));
+ }
+ if state.status != VmStatus::Paused || state.command.is_some() {
+ return Err(control_error("export", ControlReason::InvalidState));
+ }
+ let (state_path, memory_path) = if state_path.is_relative() || memory_path.is_relative() {
+ let cwd = std::env::current_dir().map_err(Error::Snapshot)?;
+ (cwd.join(state_path), cwd.join(memory_path))
+ } else {
+ (state_path.into(), memory_path.into())
+ };
+ let (reply, result) = mpsc::channel();
+ state.command = Some(Command::Export(Request {
+ state_path,
+ memory_path,
+ reply,
+ }));
+ state.sender().wake();
+ Ok(result)
+ }
+
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ pub(crate) fn advance_export(
+ &self,
+ host: &impl X86Vm,
+ count: u8,
+ ) -> Option<(Request, Result<MachineState>)> {
+ let mut state = self.state();
+ if state.is_terminal() {
+ return None;
+ }
+ match state.command.take() {
+ Some(Command::Export(request)) => {
+ state.command = Some(Command::Exporting);
+ drop(state);
+ let platform = match host.save_state() {
+ Ok(platform) => platform,
+ Err(error) => return Some((request, Err(error.into()))),
+ };
+ let mut state = self.state();
+ if state.is_terminal() {
+ return Some((request, Err(export_terminated())));
+ }
+ state.command = Some(Command::Capture {
+ pending: u64::MAX,
+ request,
+ platform: Box::new(platform),
+ replies: Vec::with_capacity(count.into()),
+ });
+ self.changed.notify_all();
+ }
+ Some(Command::Capture {
+ request,
+ platform,
+ replies,
+ ..
+ }) if replies.len() == usize::from(count) => {
+ state.command = Some(Command::Exporting);
+ drop(state);
+ let platform = *platform;
+ let machine = replies
+ .into_iter()
+ .collect::<Result<_>>()
+ .map(|vcpus| MachineState { vcpus, platform });
+ return Some((request, machine));
+ }
+ command => state.command = command,
+ }
+ None
+ }
+
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ pub(crate) fn finish_export(&self, result: Result<()>) -> Result<()> {
+ let mut state = self.state();
+ let terminal = state.is_terminal();
+ state.command = None;
+ drop(state);
+ if terminal {
+ return Err(export_terminated());
+ }
+ result
+ }
+
pub(crate) fn wait_paused(&self, timeout: Duration) -> Result<()> {
let state = self.state();
if state.is_terminal() {
return Err(control_error("wait_paused", ControlReason::TerminalOutcome));
}
- let epoch = match (state.status, state.command) {
- (VmStatus::Created | VmStatus::Running, Some(Command::Park(epoch))) => epoch,
+ let epoch = match (state.status, &state.command) {
+ (VmStatus::Created | VmStatus::Running, Some(Command::Park(epoch))) => *epoch,
(VmStatus::Pausing | VmStatus::Paused, _) => state.epoch,
_ => return Err(control_error("wait_paused", ControlReason::InvalidState)),
};
@@ -232,7 +347,9 @@ impl Lifecycle {
if state.is_terminal() {
return false;
}
- match state.command.take() {
+ let pause_or_resume =
+ |command: &mut Command| matches!(command, Command::Park(_) | Command::Resume(_));
+ match state.command.take_if(pause_or_resume) {
Some(Command::Park(epoch)) => {
state.start_pause(epoch);
return true;
@@ -252,11 +369,40 @@ impl Lifecycle {
false
}
- #[cfg(any(test, target_arch = "x86_64"))]
+ #[cfg(any(test, all(not(target_os = "linux"), target_arch = "x86_64")))]
pub(crate) fn checkpoint(
&self,
id: u8,
mut park: impl FnMut() -> Result<Option<Event>>,
+ ) -> Result<Option<Event>> {
+ self.checkpoint_inner(
+ id,
+ &mut (),
+ |_| park(),
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ None,
+ )
+ }
+
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ pub(crate) fn checkpoint_with_capture<V: boxlite_hypervisor::X86Vcpu>(
+ &self,
+ id: u8,
+ vcpu: &mut V,
+ park: impl FnMut(&mut V) -> Result<Option<Event>>,
+ ) -> Result<Option<Event>> {
+ self.checkpoint_inner(id, vcpu, park, Some(crate::vcpu::capture))
+ }
+
+ #[cfg(any(test, target_arch = "x86_64"))]
+ fn checkpoint_inner<V>(
+ &self,
+ id: u8,
+ vcpu: &mut V,
+ mut park: impl FnMut(&mut V) -> Result<Option<Event>>,
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))] capture: Option<
+ fn(&mut V, u8) -> Result<VcpuRecord>,
+ >,
) -> Result<Option<Event>> {
if !self.device_less {
return Ok(None);
@@ -265,7 +411,7 @@ impl Lifecycle {
while matches!(state.status, VmStatus::Pausing | VmStatus::Paused) && !state.is_terminal() {
let epoch = state.epoch;
drop(state);
- if let Some(event) = park()? {
+ if let Some(event) = park(vcpu)? {
return Ok(Some(event));
}
state = self.state();
@@ -273,14 +419,30 @@ impl Lifecycle {
state.acknowledge(epoch, id);
state.sender().wake();
}
- state = self
- .changed
- .wait_while(state, |state| {
- state.epoch == epoch
- && matches!(state.status, VmStatus::Pausing | VmStatus::Paused)
- && !state.is_terminal()
- })
- .unwrap_or_else(PoisonError::into_inner);
+ while state.epoch == epoch
+ && matches!(state.status, VmStatus::Pausing | VmStatus::Paused)
+ && !state.is_terminal()
+ {
+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+ if let Some(capture) = capture
+ && let Some(Command::Capture { pending, .. }) = &mut state.command
+ && *pending & (1 << id) != 0
+ {
+ *pending &= !(1 << id);
+ drop(state);
+ let reply = capture(vcpu, id);
+ state = self.state();
+ if let Some(Command::Capture { replies, .. }) = &mut state.command {
+ replies.push(reply);
+ state.sender().wake();
+ }
+ continue;
+ }
+ state = self
+ .changed
+ .wait(state)
+ .unwrap_or_else(PoisonError::into_inner);
+ }
}
Ok(None)
}
@@ -292,8 +454,9 @@ impl Lifecycle {
state.sender().send(Event::StopRequested);
}
state.status = VmStatus::Stopping;
- state.command = None;
+ let _command = state.command.take();
self.changed.notify_all();
+ drop(state);
}
pub(crate) fn mark_exited(&self) {
@@ -309,6 +472,11 @@ fn control_error(operation: &'static str, reason: ControlReason) -> Error {
Error::Control { operation, reason }
}
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub(crate) fn export_terminated() -> Error {
+ control_error("export", ControlReason::TerminalOutcome)
+}
+
#[cfg(test)]
#[path = "../tests/lifecycle/mod.rs"]
mod tests;
diff --git a/src/vmm/src/memory.rs b/src/vmm/src/memory.rs
index 8b5d6feb8..5c7417fc5 100644
--- a/src/vmm/src/memory.rs
+++ b/src/vmm/src/memory.rs
@@ -53,7 +53,12 @@ impl RamLayout {
/// The RAM start, size and any hole endpoints must be guest-page aligned.
pub(crate) fn ranges(&self, size: u64) -> io::Result<Vec<(GuestAddress, usize)>> {
assert!(self.start.is_multiple_of(GUEST_PAGE_SIZE));
- assert!(size.is_multiple_of(GUEST_PAGE_SIZE));
+ if !size.is_multiple_of(GUEST_PAGE_SIZE) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "guest RAM size is not page-aligned",
+ ));
+ }
let (low_len, high) = if let Some((hole_start, hole_end)) = self.hole {
assert!(hole_start.is_multiple_of(GUEST_PAGE_SIZE));
assert!(hole_end.is_multiple_of(GUEST_PAGE_SIZE));
diff --git a/src/vmm/src/snapshot/export.rs b/src/vmm/src/snapshot/export.rs
new file mode 100644
index 000000000..2f8815146
--- /dev/null
+++ b/src/vmm/src/snapshot/export.rs
@@ -0,0 +1,35 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use std::{path::PathBuf, sync::mpsc};
+
+use boxlite_hypervisor::X86Vm;
+
+use super::image;
+use crate::{Result, lifecycle::Lifecycle, memory::GuestRam};
+
+#[derive(Debug)]
+pub(crate) struct Request {
+ pub(crate) state_path: PathBuf,
+ pub(crate) memory_path: PathBuf,
+ pub(crate) reply: mpsc::Sender<Result<()>>,
+}
+
+pub(crate) fn drive(lifecycle: &Lifecycle, host: &impl X86Vm, ram: &GuestRam, count: u8) {
+ let Some((request, machine)) = lifecycle.advance_export(host, count) else {
+ return;
+ };
+ let result = machine.and_then(|mut state| {
+ state.vcpus.sort_unstable_by_key(|record| record.id);
+ let mut state_file = image::create_new_file(&request.state_path)?;
+ let mut memory_file = image::create_new_file(&request.memory_path)?;
+ image::write_to(
+ &mut state_file,
+ &mut memory_file,
+ state.vcpus.len() as u32,
+ &state.encode()?,
+ ram,
+ )
+ });
+ let _ = request.reply.send(lifecycle.finish_export(result));
+}
diff --git a/src/vmm/src/snapshot/image.rs b/src/vmm/src/snapshot/image.rs
new file mode 100644
index 000000000..70a7b8843
--- /dev/null
+++ b/src/vmm/src/snapshot/image.rs
@@ -0,0 +1,73 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! Version 1 pairs a framed machine state file with a raw packed RAM file.
+
+use std::{
+ fs::{File, OpenOptions},
+ io::{self, Write},
+ os::unix::fs::OpenOptionsExt,
+ path::Path,
+};
+
+use vm_memory::{Bytes, GuestAddress};
+
+use crate::{Error, Result, memory::GuestRam};
+
+pub(super) const MAGIC: &[u8; 8] = b"BXLVMST1";
+pub(super) const VERSION: u32 = 1;
+pub(super) const HEADER_LEN: usize = 32;
+pub(super) const CHUNK: usize = 1 << 20;
+
+pub(super) struct Header {
+ pub(super) vcpus: u32,
+ pub(super) ram_len: u64,
+ machine_len: u64,
+}
+
+pub(crate) fn write_to(
+ state_writer: &mut dyn Write,
+ memory_writer: &mut dyn Write,
+ count: u32,
+ machine: &[u8],
+ ram: &GuestRam,
+) -> Result<()> {
+ let header = Header {
+ vcpus: count,
+ ram_len: ram.ranges().map(|(_, size)| size as u64).sum(),
+ machine_len: machine.len() as u64,
+ };
+ let mut bytes = [0; HEADER_LEN];
+ bytes[..8].copy_from_slice(MAGIC);
+ bytes[8..12].copy_from_slice(&VERSION.to_le_bytes());
+ bytes[12..16].copy_from_slice(&header.vcpus.to_le_bytes());
+ bytes[16..24].copy_from_slice(&header.ram_len.to_le_bytes());
+ bytes[24..32].copy_from_slice(&header.machine_len.to_le_bytes());
+ state_writer.write_all(&bytes).map_err(Error::Snapshot)?;
+ state_writer.write_all(machine).map_err(Error::Snapshot)?;
+ let mut buffer = vec![0; CHUNK];
+ for (start, size) in ram.ranges() {
+ for offset in (0..size).step_by(CHUNK) {
+ let chunk = &mut buffer[..CHUNK.min(size - offset)];
+ ram.boot_memory()
+ .read_slice(chunk, GuestAddress(start.0 + offset as u64))
+ .map_err(|source| Error::Snapshot(io::Error::other(source)))?;
+ memory_writer.write_all(chunk).map_err(Error::Snapshot)?;
+ }
+ }
+ state_writer.flush().map_err(Error::Snapshot)?;
+ memory_writer.flush().map_err(Error::Snapshot)
+}
+
+pub(crate) fn create_new_file(path: &Path) -> Result<File> {
+ OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(path)
+ .map_err(Error::Snapshot)
+}
+
+#[cfg(test)]
+#[path = "../../tests/snapshot/image.rs"]
+pub(super) mod tests;
diff --git a/src/vmm/src/snapshot/mod.rs b/src/vmm/src/snapshot/mod.rs
new file mode 100644
index 000000000..4382852cf
--- /dev/null
+++ b/src/vmm/src/snapshot/mod.rs
@@ -0,0 +1,10 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+pub(crate) mod export;
+pub(crate) mod image;
+pub(crate) mod state;
+
+#[cfg(test)]
+#[path = "../../tests/snapshot/execution.rs"]
+mod execution_tests;
diff --git a/src/vmm/src/snapshot/state.rs b/src/vmm/src/snapshot/state.rs
new file mode 100644
index 000000000..53a001978
--- /dev/null
+++ b/src/vmm/src/snapshot/state.rs
@@ -0,0 +1,25 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use boxlite_hypervisor::{X86VcpuState, X86VmState};
+use serde::{Deserialize, Serialize};
+
+use crate::{Error, Result};
+
+#[derive(Debug, Deserialize, Serialize)]
+pub(crate) struct MachineState {
+ pub(crate) vcpus: Vec<VcpuRecord>,
+ pub(crate) platform: X86VmState,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub(crate) struct VcpuRecord {
+ pub(crate) id: u8,
+ pub(crate) state: X86VcpuState,
+}
+
+impl MachineState {
+ pub(crate) fn encode(&self) -> Result<Vec<u8>> {
+ postcard::to_allocvec(self).map_err(|error| Error::Snapshot(std::io::Error::other(error)))
+ }
+}
diff --git a/src/vmm/src/vcpu.rs b/src/vmm/src/vcpu.rs
index 5533a93d4..67c0ce078 100644
--- a/src/vmm/src/vcpu.rs
+++ b/src/vmm/src/vcpu.rs
@@ -16,6 +16,8 @@ use boxlite_hypervisor::{IoCompletion, Vcpu, VcpuExit};
#[cfg(target_arch = "x86_64")]
use boxlite_hypervisor::{X86BootRegisters, X86Vcpu, X86Vm};
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+use crate::snapshot::state::VcpuRecord;
use crate::{
chipset::Chipset,
error::{Error, Result},
@@ -119,10 +121,15 @@ impl<H: X86Vm> Workers<'_, H> {
/// pending I/O.
fn run_guest(&self, vcpu: &mut H::Vcpu, id: u8) -> Result<Option<Event>> {
loop {
- if let Some(event) = self
+ #[cfg(target_os = "linux")]
+ let checkpoint = self
.lifecycle
- .checkpoint(id, || park_vcpu(self.chipset, vcpu, id))?
- {
+ .checkpoint_with_capture(id, vcpu, |vcpu| park_vcpu(self.chipset, vcpu, id));
+ #[cfg(not(target_os = "linux"))]
+ let checkpoint = self
+ .lifecycle
+ .checkpoint(id, || park_vcpu(self.chipset, vcpu, id));
+ if let Some(event) = checkpoint? {
return Ok(Some(event));
}
// A stop may have released this worker from its checkpoint.
@@ -180,3 +187,9 @@ pub(crate) fn park_vcpu(chipset: &Chipset, vcpu: &mut impl Vcpu, id: u8) -> Resu
}
Ok(None)
}
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub(crate) fn capture(vcpu: &mut impl X86Vcpu, id: u8) -> Result<VcpuRecord> {
+ let state = vcpu.save_state()?;
+ Ok(VcpuRecord { id, state })
+}
diff --git a/src/vmm/src/vm.rs b/src/vmm/src/vm.rs
index 1db26a7b8..3c4a57f48 100644
--- a/src/vmm/src/vm.rs
+++ b/src/vmm/src/vm.rs
@@ -8,6 +8,8 @@ use std::sync::{Arc, Mutex, PoisonError};
use boxlite_hypervisor::Vm as HostVm;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+use crate::snapshot::export;
use crate::{
chipset::{Chipset, ChipsetBuilder},
config::VmConfig,
@@ -391,31 +393,32 @@ impl<H: boxlite_hypervisor::X86Vm> Vm<H> {
Ok(None) => {}
}
let kick_all = self.lifecycle.drive(self.vcpu_count);
- if !kick_all && pending_kicks == 0 {
- continue;
- }
- if self.lifecycle.status() != VmStatus::Pausing || vcpus.sender.is_stopping() {
- pending_kicks = 0;
- continue;
- }
- let kicks = kicks.lock().unwrap_or_else(PoisonError::into_inner);
- // Startup only appends handles, so their indices stay stable.
- for (index, kick) in kicks.iter().enumerate() {
- let bit = 1u64 << index;
- if !kick_all && pending_kicks & bit == 0 {
- continue;
- }
- match kick.kick() {
- Ok(()) => pending_kicks &= !bit,
- Err(error) if retryable_kick(&error) => {
- pending_kicks |= bit;
- }
- Err(error) => {
- vcpus.sender.send(Event::VcpuFailed(error.into()));
- break;
+ if kick_all || pending_kicks != 0 {
+ if self.lifecycle.status() != VmStatus::Pausing || vcpus.sender.is_stopping() {
+ pending_kicks = 0;
+ } else {
+ let kicks = kicks.lock().unwrap_or_else(PoisonError::into_inner);
+ // Startup only appends handles, so their indices stay stable.
+ for (index, kick) in kicks.iter().enumerate() {
+ let bit = 1u64 << index;
+ if !kick_all && pending_kicks & bit == 0 {
+ continue;
+ }
+ match kick.kick() {
+ Ok(()) => pending_kicks &= !bit,
+ Err(error) if retryable_kick(&error) => {
+ pending_kicks |= bit;
+ }
+ Err(error) => {
+ vcpus.sender.send(Event::VcpuFailed(error.into()));
+ break;
+ }
+ }
}
}
}
+ #[cfg(target_os = "linux")]
+ export::drive(vcpus.lifecycle, vcpus.host_vm, &self.ram, self.vcpu_count);
}
});
match event {
diff --git a/src/vmm/tests/lifecycle/mod.rs b/src/vmm/tests/lifecycle/mod.rs
index 82e8db7c7..ff2dde026 100644
--- a/src/vmm/tests/lifecycle/mod.rs
+++ b/src/vmm/tests/lifecycle/mod.rs
@@ -199,7 +199,7 @@ fn checkpoint_reparks_when_it_wakes_in_a_new_pause_epoch() {
{
let mut state = lifecycle.state();
assert_eq!((state.status, state.epoch), (VmStatus::Paused, 1));
- assert_eq!(state.command.take(), Some(Command::Resume(1)));
+ assert!(matches!(state.command.take(), Some(Command::Resume(1))));
// Apply both driver transitions under one lock: separate drive calls
// would let the parked worker observe Running before Pausing(2).
state.status = VmStatus::Running;
@@ -503,7 +503,7 @@ fn running_pause_posts_without_blocking_and_survives_wait_timeouts() {
let wake_wait = Instant::now();
assert!(events.wait(Some(WAIT)).unwrap().is_none());
assert!(wake_wait.elapsed() < WAIT / 2);
- assert_eq!(lifecycle.state().command, Some(Command::Park(1)));
+ assert!(matches!(lifecycle.state().command, Some(Command::Park(1))));
assert!(lifecycle.drive(1));
assert_eq!(control.status(), VmStatus::Pausing);
diff --git a/src/vmm/tests/snapshot/execution.rs b/src/vmm/tests/snapshot/execution.rs
new file mode 100644
index 000000000..44b3b2f76
--- /dev/null
+++ b/src/vmm/tests/snapshot/execution.rs
@@ -0,0 +1,1190 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+use std::{
+ fs, io,
+ marker::PhantomData,
+ os::unix::fs::{OpenOptionsExt, PermissionsExt},
+ path::Path,
+ rc::Rc,
+ sync::{Mutex, mpsc},
+ thread::{self, ThreadId},
+ time::Duration,
+};
+
+use super::{image::Header, state::MachineState};
+use crate::{
+ ControlReason, Error, Vm, VmControl, VmExit, VmStatus,
+ events::EventLoop,
+ lifecycle::Lifecycle,
+ mock_vm::{MockHandle, MockVcpu, MockVm},
+};
+use boxlite_hypervisor::{
+ IoCompletion, MemoryRegion, Vcpu, VcpuExit, X86BootRegisters, X86IrqchipState, X86Vcpu,
+ X86VcpuState, X86Vm, X86VmState,
+};
+use vm_memory::{Bytes, GuestAddress};
+
+const WAIT: Duration = Duration::from_secs(5);
+
+fn cpu(id: u32) -> X86VcpuState {
+ let mut state = X86VcpuState {
+ regs: Default::default(),
+ sregs: Default::default(),
+ fpu: Default::default(),
+ xsave: vec![],
+ cpuid: vec![],
+ msrs: vec![],
+ xcrs: Default::default(),
+ debug_regs: Default::default(),
+ events: Default::default(),
+ mp_state: Default::default(),
+ lapic: Default::default(),
+ tsc_khz: 1000,
+ };
+ state.regs.rax = u64::from(id);
+ state
+}
+
+fn platform() -> X86VmState {
+ X86VmState {
+ irqchips: [
+ X86IrqchipState::pic(0, Default::default()),
+ X86IrqchipState::pic(1, Default::default()),
+ X86IrqchipState::ioapic(Default::default()),
+ ],
+ pit: None,
+ clock: Default::default(),
+ }
+}
+
+#[derive(Debug)]
+enum Capture {
+ Cpu(u32, ThreadId),
+ Done(u32),
+ Failed(u32),
+ Platform(ThreadId),
+}
+struct Backend {
+ inner: MockVm,
+ observed: mpsc::Sender<Capture>,
+ gates: Vec<Mutex<mpsc::Receiver<()>>>,
+ fail_cpu: bool,
+ fail_cpu_once: bool,
+ fail_platform: bool,
+ platform_gate: Option<Mutex<mpsc::Receiver<()>>>,
+}
+struct Cpu {
+ inner: MockVcpu,
+ id: u32,
+ owner: ThreadId,
+ observed: mpsc::Sender<Capture>,
+ gate: mpsc::Receiver<()>,
+ fail: bool,
+ fail_once: bool,
+ // Enforce the backend contract: only its owning thread may access the CPU.
+ local: PhantomData<Rc<()>>,
+}
+impl boxlite_hypervisor::Vm for Backend {
+ type Vcpu = Cpu;
+ unsafe fn map_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ // SAFETY: forwards the caller's unchanged registration contract.
+ unsafe { self.inner.map_memory(region) }
+ }
+ fn unmap_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ self.inner.unmap_memory(region)
+ }
+ fn set_irq_line(&self, line: u32, level: bool) -> boxlite_hypervisor::Result<()> {
+ self.inner.set_irq_line(line, level)
+ }
+ fn create_vcpu(&self, id: u32) -> boxlite_hypervisor::Result<Cpu> {
+ let (_, empty) = mpsc::channel();
+ let gate = std::mem::replace(&mut *self.gates[id as usize].lock().unwrap(), empty);
+ Ok(Cpu {
+ inner: self.inner.create_vcpu(id)?,
+ id,
+ owner: thread::current().id(),
+ observed: self.observed.clone(),
+ gate,
+ fail: self.fail_cpu && id == 0,
+ fail_once: self.fail_cpu_once && id == 0,
+ local: PhantomData,
+ })
+ }
+}
+impl X86Vm for Backend {
+ fn supported_cpuid(&self) -> &[boxlite_hypervisor::X86CpuidEntry] {
+ &[]
+ }
+ fn save_state(&self) -> boxlite_hypervisor::Result<X86VmState> {
+ self.observed
+ .send(Capture::Platform(thread::current().id()))
+ .unwrap();
+ if let Some(gate) = &self.platform_gate {
+ gate.lock().unwrap().recv_timeout(WAIT).unwrap();
+ }
+ if self.fail_platform {
+ return Err(boxlite_hypervisor::Error::CreateVm(io::Error::other(
+ "platform failure",
+ )));
+ }
+ Ok(platform())
+ }
+}
+impl Vcpu for Cpu {
+ type Handle = MockHandle;
+ fn run(&mut self) -> boxlite_hypervisor::Result<VcpuExit<'_>> {
+ self.inner.run()
+ }
+ fn complete_pending_io(&mut self) -> boxlite_hypervisor::Result<IoCompletion<'_>> {
+ self.inner.complete_pending_io()
+ }
+ fn handle(&self) -> MockHandle {
+ self.inner.handle()
+ }
+}
+impl X86Vcpu for Cpu {
+ fn set_cpu_features(
+ &mut self,
+ cpuid: &[boxlite_hypervisor::X86CpuidEntry],
+ msrs: &[boxlite_hypervisor::X86Msr],
+ ) -> boxlite_hypervisor::Result<()> {
+ self.inner.set_cpu_features(cpuid, msrs)
+ }
+ fn set_boot_registers(&mut self, state: &X86BootRegisters) -> boxlite_hypervisor::Result<()> {
+ self.inner.set_boot_registers(state)
+ }
+ fn save_state(&mut self) -> boxlite_hypervisor::Result<X86VcpuState> {
+ assert_eq!(thread::current().id(), self.owner);
+ self.observed
+ .send(Capture::Cpu(self.id, self.owner))
+ .unwrap();
+ self.gate.recv_timeout(WAIT).unwrap();
+ if self.fail || std::mem::take(&mut self.fail_once) {
+ self.observed.send(Capture::Failed(self.id)).unwrap();
+ return Err(boxlite_hypervisor::Error::ConfigureVcpu {
+ id: self.id,
+ operation: "save state",
+ source: io::Error::other("CPU failure"),
+ });
+ }
+ self.observed.send(Capture::Done(self.id)).unwrap();
+ Ok(cpu(self.id))
+ }
+}
+
+fn config() -> crate::VmConfig {
+ crate::VmConfig {
+ vcpu_count: 3,
+ memory_mib: 1,
+ kernel: "unused".into(),
+ cmdline: String::new(),
+ initramfs: None,
+ disks: vec![],
+ filesystem: None,
+ vsock: None,
+ network: None,
+ virtio_console: false,
+ hotplug_mib: 0,
+ }
+}
+fn backend(
+ fail_cpu: bool,
+ fail_platform: bool,
+) -> (Backend, Vec<mpsc::Sender<()>>, mpsc::Receiver<Capture>) {
+ let (observed, rx) = mpsc::channel();
+ let mut gates = vec![];
+ let mut releases = vec![];
+ for _ in 0..3 {
+ let (tx, rx) = mpsc::channel();
+ gates.push(Mutex::new(rx));
+ releases.push(tx);
+ }
+ (
+ Backend {
+ inner: MockVm::new(),
+ observed,
+ gates,
+ fail_cpu,
+ fail_cpu_once: false,
+ fail_platform,
+ platform_gate: None,
+ },
+ releases,
+ rx,
+ )
+}
+fn machine(backend: Backend) -> Vm<Backend> {
+ Vm::with_backend(
+ config(),
+ || Ok(backend),
+ |ram, _| {
+ ram.boot_memory()
+ .write_slice(b"guest RAM", GuestAddress(0))
+ .unwrap();
+ Ok(X86BootRegisters::default())
+ },
+ |_, _| Ok(()),
+ )
+ .unwrap()
+}
+
+struct StopOnDrop<'a>(&'a VmControl);
+impl Drop for StopOnDrop<'_> {
+ fn drop(&mut self) {
+ self.0.stop();
+ }
+}
+
+fn with_paused<H: X86Vm, R>(
+ mut vm: Vm<H>,
+ test: impl FnOnce(&VmControl, &Lifecycle, ThreadId) -> R,
+) -> R {
+ let control = vm.control();
+ let lifecycle = vm.lifecycle().clone();
+ control.request_pause().unwrap();
+ thread::scope(|scope| {
+ let driver = scope.spawn(|| vm.run());
+ let stop = StopOnDrop(&control);
+ control.wait_paused(WAIT).unwrap();
+ let result = test(&control, &lifecycle, driver.thread().id());
+ drop(stop);
+ assert_eq!(driver.join().unwrap().unwrap(), VmExit::StopRequested);
+ result
+ })
+}
+
+fn decode(mut bytes: &[u8], memory: &[u8]) -> (Header, MachineState) {
+ let len = bytes.len() as u64;
+ let header = Header::read_from(&mut bytes, len, memory.len() as u64).unwrap();
+ let (state, tail) = postcard::take_from_bytes(bytes).unwrap();
+ assert!(tail.is_empty());
+ (header, state)
+}
+
+fn expect_export_error<T>(result: crate::Result<T>, reason: ControlReason) {
+ assert!(
+ matches!(result, Err(Error::Control { operation: "export", reason: why }) if why == reason)
+ );
+}
+
+#[test]
+fn driver_captures_platform_first_and_owning_threads_produce_id_ordered_records() {
+ let (backend, releases, observed) = backend(false, false);
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, _, driver| {
+ thread::scope(|scope| {
+ let caller = scope.spawn(|| control.export(&state_path, &memory_path));
+ assert!(
+ matches!(observed.recv_timeout(WAIT).unwrap(), Capture::Platform(owner) if owner == driver)
+ );
+ let mut ids = Vec::new();
+ for _ in 0..3 {
+ let Capture::Cpu(id, owner) = observed.recv_timeout(WAIT).unwrap() else {
+ panic!("expected a vCPU capture after platform capture");
+ };
+ assert_ne!(owner, driver);
+ ids.push(id);
+ }
+ ids.sort_unstable();
+ assert_eq!(ids, [0, 1, 2]);
+ assert!(!state_path.exists() && !memory_path.exists());
+ expect_export_error(
+ control.clone().export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ for id in [2, 1, 0] {
+ releases[id].send(()).unwrap();
+ assert!(
+ matches!(observed.recv_timeout(WAIT).unwrap(), Capture::Done(done) if done == id as u32)
+ );
+ if id != 0 {
+ assert!(matches!(
+ observed.try_recv(),
+ Err(mpsc::TryRecvError::Empty)
+ ));
+ }
+ }
+ caller.join().unwrap().unwrap();
+ });
+ assert_eq!(control.status(), VmStatus::Paused);
+ });
+ let memory = fs::read(&memory_path).unwrap();
+ let (header, state) = decode(&fs::read(&state_path).unwrap(), &memory);
+ assert_eq!(header.vcpus, 3);
+ assert_eq!(header.ram_len, 1 << 20);
+ assert_eq!(&memory[..9], b"guest RAM");
+ assert!(memory[9..].iter().all(|&byte| byte == 0));
+ let probe_path = dir.path().join("umask-probe");
+ fs::OpenOptions::new()
+ .create_new(true)
+ .write(true)
+ .mode(0o777)
+ .open(&probe_path)
+ .unwrap();
+ let probe_mode = fs::metadata(&probe_path).unwrap().permissions().mode() & 0o777;
+ for path in [&state_path, &memory_path] {
+ assert_eq!(
+ fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o600 & probe_mode
+ );
+ }
+ assert_eq!(
+ state
+ .vcpus
+ .iter()
+ .map(|record| (record.id, record.state.regs.rax))
+ .collect::<Vec<_>>(),
+ [(0, 0), (1, 1), (2, 2)]
+ );
+ assert_eq!(state.platform, platform());
+}
+
+#[test]
+fn capture_failures_leave_vm_paused_without_creating_files() {
+ for (fail_cpu, fail_platform) in [(true, false), (false, true)] {
+ let (backend, releases, observed) = backend(fail_cpu, fail_platform);
+ with_paused(machine(backend), |control, _, driver| {
+ for release in releases {
+ release.send(()).unwrap();
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ assert!(matches!(
+ control.export(&state_path, &memory_path),
+ Err(Error::Hypervisor(_))
+ ));
+ if fail_platform {
+ assert!(
+ matches!(observed.try_recv().unwrap(), Capture::Platform(owner) if owner == driver)
+ );
+ assert!(matches!(
+ observed.try_recv(),
+ Err(mpsc::TryRecvError::Empty)
+ ));
+ }
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert!(!state_path.exists() && !memory_path.exists());
+ control.resume().unwrap();
+ });
+ }
+}
+
+#[test]
+fn capture_error_keeps_export_exclusive_until_every_vcpu_replies() {
+ let (backend, releases, observed) = backend(true, false);
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, lifecycle, _| {
+ let reply = lifecycle.submit_export(&state_path, &memory_path).unwrap();
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Platform(_)
+ ));
+ for _ in 0..3 {
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Cpu(..)
+ ));
+ }
+ releases[1].send(()).unwrap();
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Done(1)
+ ));
+ releases[0].send(()).unwrap();
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Failed(0)
+ ));
+
+ let pending = reply.recv_timeout(Duration::from_millis(250));
+ if !matches!(pending, Err(mpsc::RecvTimeoutError::Timeout)) {
+ releases[2].send(()).unwrap();
+ panic!("export completed while vCPU 2 was still capturing: {pending:?}");
+ }
+ assert!(matches!(
+ control.resume(),
+ Err(Error::Control {
+ operation: "resume",
+ reason: ControlReason::InvalidState
+ })
+ ));
+ expect_export_error(
+ control.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+
+ releases[2].send(()).unwrap();
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Done(2)
+ ));
+ assert!(matches!(
+ reply.recv_timeout(WAIT).unwrap(),
+ Err(Error::Hypervisor(
+ boxlite_hypervisor::Error::ConfigureVcpu { id: 0, .. }
+ ))
+ ));
+ control.resume().unwrap();
+ });
+}
+
+struct ReleaseOnDrop(Vec<mpsc::Sender<()>>);
+impl Drop for ReleaseOnDrop {
+ fn drop(&mut self) {
+ for release in self.0.drain(..) {
+ let _ = release.send(());
+ }
+ }
+}
+
+#[test]
+fn vcpu_panic_interrupts_capture_before_a_blocked_vcpu_replies() {
+ let (backend, releases, observed) = backend(false, false);
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let mut vm = machine(backend);
+ let control = vm.control();
+ control.request_pause().unwrap();
+ thread::scope(|scope| {
+ let (driver_done_tx, driver_done_rx) = mpsc::channel();
+ let vm = &mut vm;
+ let driver = scope.spawn(move || {
+ let exit = vm.run();
+ let _ = driver_done_tx.send(());
+ exit
+ });
+ let mut releases = ReleaseOnDrop(releases);
+ let _stop = StopOnDrop(&control);
+ control.wait_paused(WAIT).unwrap();
+ let (reply, result) = mpsc::channel();
+ let control = &control;
+ let (state_path, memory_path) = (&state_path, &memory_path);
+ scope.spawn(move || reply.send(control.export(state_path, memory_path)).unwrap());
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Platform(_)
+ ));
+ for _ in 0..3 {
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Cpu(..)
+ ));
+ }
+
+ // Disconnect vCPU 0's gate so its save_state panics while the others are blocked.
+ drop(releases.0.remove(0));
+ let result = result.recv_timeout(Duration::from_millis(500));
+ for release in releases.0.drain(..) {
+ release.send(()).unwrap();
+ }
+ expect_export_error(
+ result.expect("panic did not wake capture"),
+ ControlReason::TerminalOutcome,
+ );
+ assert!(
+ !matches!(
+ driver_done_rx.recv_timeout(WAIT),
+ Err(mpsc::RecvTimeoutError::Timeout)
+ ),
+ "driver did not exit after vCPU panic"
+ );
+ assert!(matches!(
+ driver.join().unwrap(),
+ Err(Error::VcpuPanicked { vcpu: 0 })
+ ));
+ assert!(!state_path.exists() && !memory_path.exists());
+ });
+}
+
+#[test]
+fn stop_interrupts_capture_before_a_blocked_vcpu_replies() {
+ let (backend, releases, observed) = backend(false, false);
+ let mut releases = ReleaseOnDrop(releases);
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, _, _| {
+ thread::scope(|scope| {
+ let (reply, result) = mpsc::channel();
+ let (state_path, memory_path) = (&state_path, &memory_path);
+ scope.spawn(move || reply.send(control.export(state_path, memory_path)).unwrap());
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Platform(_)
+ ));
+ for _ in 0..3 {
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Cpu(..)
+ ));
+ }
+ control.stop();
+ expect_export_error(
+ result.recv_timeout(Duration::from_millis(500)).unwrap(),
+ ControlReason::TerminalOutcome,
+ );
+ assert!(!state_path.exists() && !memory_path.exists());
+ for release in releases.0.drain(..) {
+ release.send(()).unwrap();
+ }
+ });
+ });
+}
+
+#[test]
+fn retry_export_succeeds_in_same_pause_epoch_after_capture_failure() {
+ let (mut backend, releases, _observed) = backend(false, false);
+ backend.fail_cpu_once = true;
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, _, _| {
+ for release in &releases {
+ release.send(()).unwrap();
+ }
+ assert!(matches!(
+ control.export(&state_path, &memory_path),
+ Err(Error::Hypervisor(_))
+ ));
+ assert!(!state_path.exists() && !memory_path.exists());
+ assert_eq!(control.status(), VmStatus::Paused);
+
+ for release in &releases {
+ release.send(()).unwrap();
+ }
+ control.export(&state_path, &memory_path).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ });
+ let memory = fs::read(&memory_path).unwrap();
+ let (header, state) = decode(&fs::read(&state_path).unwrap(), &memory);
+ assert_eq!(header.vcpus, 3);
+ assert_eq!(header.ram_len, 1 << 20);
+ assert_eq!(&memory[..9], b"guest RAM");
+ assert_eq!(
+ state
+ .vcpus
+ .iter()
+ .map(|record| (record.id, record.state.regs.rax))
+ .collect::<Vec<_>>(),
+ [(0, 0), (1, 1), (2, 2)]
+ );
+ assert_eq!(state.platform, platform());
+}
+
+#[test]
+fn export_rejects_vms_with_devices() {
+ struct Idle;
+ impl crate::bus::BusDevice for Idle {
+ fn read(&mut self, _: u64, _: &mut [u8]) {}
+ fn write(&mut self, _: u64, _: &[u8]) {}
+ }
+
+ let vm = Vm::with_backend(
+ config(),
+ || Ok(MockVm::new()),
+ |_, _| Ok(X86BootRegisters::default()),
+ |chipset, _| chipset.add("idle", |_| Ok(Idle)),
+ )
+ .unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ expect_export_error(
+ vm.control().export(&state_path, &memory_path),
+ ControlReason::UnsupportedDevice,
+ );
+ assert!(!state_path.exists() && !memory_path.exists());
+}
+
+#[test]
+fn stop_during_platform_capture_skips_vcpu_capture_and_file_creation() {
+ let (mut backend, releases, observed) = backend(false, false);
+ let (release_platform, platform_gate) = mpsc::channel();
+ backend.platform_gate = Some(Mutex::new(platform_gate));
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, _, driver| {
+ for release in releases {
+ release.send(()).unwrap();
+ }
+ thread::scope(|scope| {
+ let export = scope.spawn(|| control.export(&state_path, &memory_path));
+ assert!(
+ matches!(observed.recv_timeout(WAIT).unwrap(), Capture::Platform(owner) if owner == driver)
+ );
+ control.stop();
+ assert_eq!(control.status(), VmStatus::Stopping);
+ release_platform.send(()).unwrap();
+ expect_export_error(export.join().unwrap(), ControlReason::TerminalOutcome);
+ });
+ });
+ assert!(matches!(
+ observed.try_recv(),
+ Err(mpsc::TryRecvError::Disconnected)
+ ));
+ assert!(!state_path.exists() && !memory_path.exists());
+}
+
+#[test]
+fn export_holds_the_slot_during_platform_capture_and_reply_survives_resume() {
+ let (mut backend, releases, observed) = backend(false, false);
+ let (release_platform, platform_gate) = mpsc::channel();
+ backend.platform_gate = Some(Mutex::new(platform_gate));
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ with_paused(machine(backend), |control, lifecycle, _| {
+ for release in releases {
+ release.send(()).unwrap();
+ }
+ let reply = lifecycle.submit_export(&state_path, &memory_path).unwrap();
+ assert!(matches!(
+ observed.recv_timeout(WAIT).unwrap(),
+ Capture::Platform(_)
+ ));
+ let competitor = control.clone();
+ assert_eq!(competitor.status(), VmStatus::Paused);
+ competitor.wait_paused(Duration::ZERO).unwrap();
+ assert!(matches!(
+ competitor.resume(),
+ Err(Error::Control {
+ operation: "resume",
+ reason: ControlReason::InvalidState
+ })
+ ));
+ expect_export_error(
+ competitor.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ assert!(!state_path.exists() && !memory_path.exists());
+ assert!(matches!(
+ observed.try_recv(),
+ Err(mpsc::TryRecvError::Empty)
+ ));
+ release_platform.send(()).unwrap();
+
+ // Keep the export reply unread until another handle has resumed.
+ let deadline = std::time::Instant::now() + WAIT;
+ loop {
+ match competitor.resume() {
+ Ok(()) => break,
+ Err(Error::Control {
+ reason: ControlReason::InvalidState,
+ ..
+ }) => {
+ assert!(std::time::Instant::now() < deadline);
+ thread::yield_now();
+ }
+ Err(error) => panic!("resume: {error}"),
+ }
+ }
+ assert_eq!(control.status(), VmStatus::Running);
+ assert!(reply.recv_timeout(WAIT).unwrap().is_ok());
+ expect_export_error(
+ control.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ });
+}
+
+#[test]
+fn export_reports_terminal_state_before_unsupported_devices() {
+ let events = EventLoop::new().unwrap();
+ let lifecycle = Lifecycle::new(events.sender(), false);
+ let state_path = Path::new("state");
+ let memory_path = Path::new("memory");
+
+ expect_export_error(
+ lifecycle.submit_export(state_path, memory_path),
+ ControlReason::UnsupportedDevice,
+ );
+ lifecycle.stop();
+ expect_export_error(
+ lifecycle.submit_export(state_path, memory_path),
+ ControlReason::InvalidState,
+ );
+}
+
+#[test]
+fn file_export_refuses_existing_target_and_unstarted_or_terminal_vm() {
+ let (backend, releases, _observed) = backend(false, false);
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let target = dir.path().join("existing");
+ fs::write(&target, b"existing").unwrap();
+ let vm = machine(backend);
+ let control = vm.control();
+ expect_export_error(
+ control.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ with_paused(vm, |control, _, _| {
+ for release in releases {
+ for _ in 0..3 {
+ release.send(()).unwrap();
+ }
+ }
+ for (state, memory, creates_state) in [
+ (&target, &memory_path, false),
+ (&state_path, &target, true),
+ (&state_path, &state_path, true),
+ ] {
+ assert!(
+ matches!(control.export(state, memory), Err(Error::Snapshot(error))
+ if error.kind() == io::ErrorKind::AlreadyExists)
+ );
+ assert_eq!(control.status(), VmStatus::Paused);
+ if creates_state {
+ assert_eq!(fs::metadata(&state_path).unwrap().len(), 0);
+ fs::remove_file(&state_path).unwrap();
+ } else {
+ assert!(!state_path.exists());
+ }
+ assert!(!memory_path.exists());
+ assert_eq!(fs::read(&target).unwrap(), b"existing");
+ }
+ control.stop();
+ expect_export_error(
+ control.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ });
+ assert_eq!(control.status(), VmStatus::Exited);
+ expect_export_error(
+ control.export(&state_path, &memory_path),
+ ControlReason::InvalidState,
+ );
+ assert!(!state_path.exists() && !memory_path.exists());
+}
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_export_of_parked_device_less_guest() {
+ const PROGRAM: [u8; 2] = [0xeb, 0xfe];
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let vm = Vm::with_backend(
+ config(),
+ boxlite_hypervisor::KvmVm::new,
+ |ram, _| Ok(crate::flat_guest::load(ram.boot_memory(), &PROGRAM)),
+ |_, _| Ok(()),
+ )
+ .unwrap();
+ with_paused(vm, |control, _, _| {
+ control.export(&state_path, &memory_path).unwrap();
+ let memory = fs::read(&memory_path).unwrap();
+ let (header, state) = decode(&fs::read(&state_path).unwrap(), &memory);
+ assert_eq!(header.vcpus, 3);
+ assert_eq!(header.ram_len, 1 << 20);
+ assert_eq!(state.vcpus.len(), 3);
+ let code = crate::flat_guest::CODE as usize;
+ assert_eq!(&memory[code..code + PROGRAM.len()], &PROGRAM);
+ assert_eq!(control.status(), VmStatus::Paused);
+ control.resume().unwrap();
+ });
+}
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_export_captures_executed_guest_state_and_ram() {
+ use std::{sync::atomic::Ordering, time::Instant};
+ use vm_memory::GuestAddressSpace;
+
+ use crate::flat_guest;
+
+ const MARKER_ADDR: GuestAddress = GuestAddress(0x2000);
+ const COUNTER_ADDR: GuestAddress = GuestAddress(0x2004);
+ const MARKER: u32 = 0x1234_5678;
+ #[rustfmt::skip]
+ const PROGRAM: [u8; 19] = [
+ 0xb8, 0x78, 0x56, 0x34, 0x12, // mov eax, 0x12345678
+ 0xa3, 0x00, 0x20, 0x00, 0x00, // mov dword ptr ds:[0x2000], eax
+ 0xf0, 0xff, 0x05, 0x04, 0x20, 0x00, 0x00, // lock inc dword ptr ds:[0x2004]
+ 0xeb, 0xf7, // jmp $-7 (0x100a)
+ ];
+
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let state_path_2 = dir.path().join("state2");
+ let memory_path_2 = dir.path().join("memory2");
+ let state_path_3 = dir.path().join("state3");
+ let memory_path_3 = dir.path().join("memory3");
+ let mut guest_memory = None;
+ let vm = Vm::with_backend(
+ config(),
+ boxlite_hypervisor::KvmVm::new,
+ |ram, _| {
+ guest_memory = Some(ram.memory().clone());
+ Ok(flat_guest::load(ram.boot_memory(), &PROGRAM))
+ },
+ |_, _| Ok(()),
+ )
+ .unwrap();
+ let guest_memory = guest_memory.unwrap();
+ let read_u32 = |addr| {
+ guest_memory
+ .memory()
+ .load::<u32>(addr, Ordering::Relaxed)
+ .unwrap()
+ };
+
+ with_paused(vm, |control, _, _| {
+ assert_eq!(read_u32(MARKER_ADDR), 0);
+ assert_eq!(read_u32(COUNTER_ADDR), 0);
+ control.resume().unwrap();
+ let deadline = Instant::now() + WAIT;
+ while read_u32(MARKER_ADDR) != MARKER || read_u32(COUNTER_ADDR) == 0 {
+ assert!(
+ Instant::now() < deadline,
+ "guest did not write the RAM marker and counter"
+ );
+ thread::sleep(Duration::from_millis(10));
+ }
+ control.request_pause().unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ let paused_counter = read_u32(COUNTER_ADDR);
+ assert!(paused_counter > 0);
+ control.export(&state_path, &memory_path).unwrap();
+
+ let memory = fs::read(&memory_path).unwrap();
+ let (header, state) = decode(&fs::read(&state_path).unwrap(), &memory);
+ assert_eq!(header.vcpus, 3);
+ assert_eq!(header.ram_len, 1 << 20);
+ assert_eq!(state.vcpus.len(), 3);
+ let ids: Vec<_> = state.vcpus.iter().map(|record| record.id).collect();
+ assert_eq!(ids, [0, 1, 2]);
+ assert!(state.platform.pit.is_some());
+ let chip_ids: Vec<_> = state
+ .platform
+ .irqchips
+ .iter()
+ .map(|chip| chip.as_kvm().chip_id)
+ .collect();
+ assert_eq!(chip_ids, [0, 1, 2]);
+ let regs = &state.vcpus[0].state.regs;
+ assert_eq!(regs.rax, u64::from(MARKER));
+ assert!((0x100a..=0x1011).contains(&regs.rip));
+ for vcpu in &state.vcpus[1..] {
+ assert!(!vcpu.state.cpuid.is_empty());
+ assert!(!vcpu.state.xsave.is_empty());
+ }
+ let marker = MARKER_ADDR.0 as usize;
+ assert_eq!(
+ u32::from_le_bytes(memory[marker..marker + 4].try_into().unwrap()),
+ MARKER
+ );
+ let counter = COUNTER_ADDR.0 as usize;
+ assert_eq!(
+ u32::from_le_bytes(memory[counter..counter + 4].try_into().unwrap()),
+ paused_counter
+ );
+ let code = flat_guest::CODE as usize;
+ assert_eq!(&memory[code..code + PROGRAM.len()], &PROGRAM);
+
+ // Re-exporting within the same pause epoch succeeds without changing state.
+ control.export(&state_path_2, &memory_path_2).unwrap();
+ let memory_2 = fs::read(&memory_path_2).unwrap();
+ let (header_2, _) = decode(&fs::read(&state_path_2).unwrap(), &memory_2);
+ assert_eq!(header_2.vcpus, 3);
+ assert_eq!(
+ u32::from_le_bytes(memory_2[counter..counter + 4].try_into().unwrap()),
+ paused_counter
+ );
+
+ assert_eq!(control.status(), VmStatus::Paused);
+ control.resume().unwrap();
+ assert_eq!(control.status(), VmStatus::Running);
+ let deadline = Instant::now() + WAIT;
+ while read_u32(COUNTER_ADDR) <= paused_counter {
+ assert!(
+ Instant::now() < deadline,
+ "guest counter did not advance after resume"
+ );
+ thread::sleep(Duration::from_millis(10));
+ }
+ control.request_pause().unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ let resumed_counter = read_u32(COUNTER_ADDR);
+ assert!(resumed_counter > paused_counter);
+ control.export(&state_path_3, &memory_path_3).unwrap();
+ let memory_3 = fs::read(&memory_path_3).unwrap();
+ let (_, _) = decode(&fs::read(&state_path_3).unwrap(), &memory_3);
+ assert_eq!(
+ u32::from_le_bytes(memory_3[counter..counter + 4].try_into().unwrap()),
+ resumed_counter
+ );
+ });
+}
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_export_after_split_mmio_pause() {
+ use std::{
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ time::Instant,
+ };
+
+ use boxlite_hypervisor::{KvmVcpu, KvmVcpuHandle, KvmVm};
+ use vm_memory::GuestAddressSpace;
+
+ use crate::flat_guest;
+
+ const COUNTER: GuestAddress = GuestAddress(0x2000);
+ const READBACK: GuestAddress = GuestAddress(0x2004);
+ const MMIO_SPLIT_ADDR: u64 = 0xd000_0ffe;
+ #[rustfmt::skip]
+ const PROGRAM: [u8; 29] = [
+ 0xa1, 0xfe, 0x0f, 0x00, 0xd0, // mov eax, [0xd0000ffe]
+ 0xa3, 0x04, 0x20, 0x00, 0x00, // mov [0x2004], eax
+ 0xc7, 0x05, 0xfe, 0x0f, 0x00, 0xd0, 0x78, 0x56, 0x34, 0x12, // mov dword [0xd0000ffe], 0x12345678
+ 0xf0, 0xff, 0x05, 0x00, 0x20, 0x00, 0x00, // lock inc dword [0x2000]
+ 0xeb, 0xe3, // jmp to the start
+ ];
+
+ #[derive(Clone, Copy, Debug)]
+ enum SplitAccess {
+ Read,
+ Write,
+ }
+
+ impl SplitAccess {
+ fn is_fragment(self, exit: &VcpuExit<'_>, addr: u64) -> bool {
+ match (self, exit) {
+ (Self::Read, VcpuExit::MmioRead { guest_addr, bytes }) => {
+ *guest_addr == addr && bytes.len() == 2
+ }
+ (Self::Write, VcpuExit::MmioWrite { guest_addr, bytes }) => {
+ *guest_addr == addr && bytes.len() == 2
+ }
+ _ => false,
+ }
+ }
+ }
+
+ struct ExitGate {
+ arrived: mpsc::Sender<()>,
+ release: Mutex<mpsc::Receiver<()>>,
+ }
+
+ impl ExitGate {
+ fn new() -> (Arc<Self>, mpsc::Receiver<()>, mpsc::Sender<()>) {
+ let (arrived, ready) = mpsc::channel();
+ let (release, resume) = mpsc::channel();
+ (
+ Arc::new(Self {
+ arrived,
+ release: Mutex::new(resume),
+ }),
+ ready,
+ release,
+ )
+ }
+
+ fn wait(&self) {
+ self.arrived.send(()).unwrap();
+ self.release.lock().unwrap().recv_timeout(WAIT).unwrap();
+ }
+ }
+
+ struct SplitMmioVm {
+ vm: KvmVm,
+ gate: Arc<ExitGate>,
+ access: SplitAccess,
+ completed_fragments: Arc<AtomicUsize>,
+ }
+
+ impl boxlite_hypervisor::Vm for SplitMmioVm {
+ type Vcpu = SplitMmioVcpu;
+
+ unsafe fn map_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ // SAFETY: forwards the caller's unchanged registration contract.
+ unsafe { self.vm.map_memory(region) }
+ }
+
+ fn unmap_memory(&self, region: &MemoryRegion) -> boxlite_hypervisor::Result<()> {
+ self.vm.unmap_memory(region)
+ }
+
+ fn create_vcpu(&self, id: u32) -> boxlite_hypervisor::Result<Self::Vcpu> {
+ Ok(SplitMmioVcpu {
+ vcpu: self.vm.create_vcpu(id)?,
+ gate: Some(Arc::clone(&self.gate)),
+ access: self.access,
+ check_completion: false,
+ completed_fragments: Arc::clone(&self.completed_fragments),
+ })
+ }
+
+ fn set_irq_line(&self, line: u32, level: bool) -> boxlite_hypervisor::Result<()> {
+ self.vm.set_irq_line(line, level)
+ }
+ }
+
+ impl X86Vm for SplitMmioVm {
+ fn supported_cpuid(&self) -> &[boxlite_hypervisor::X86CpuidEntry] {
+ self.vm.supported_cpuid()
+ }
+
+ fn save_state(&self) -> boxlite_hypervisor::Result<X86VmState> {
+ self.vm.save_state()
+ }
+ }
+
+ struct SplitMmioVcpu {
+ vcpu: KvmVcpu,
+ gate: Option<Arc<ExitGate>>,
+ access: SplitAccess,
+ check_completion: bool,
+ completed_fragments: Arc<AtomicUsize>,
+ }
+
+ impl Vcpu for SplitMmioVcpu {
+ type Handle = KvmVcpuHandle;
+
+ fn run(&mut self) -> boxlite_hypervisor::Result<VcpuExit<'_>> {
+ let exit = self.vcpu.run()?;
+ if self.access.is_fragment(&exit, MMIO_SPLIT_ADDR)
+ && let Some(gate) = self.gate.take()
+ {
+ self.check_completion = true;
+ gate.wait();
+ }
+ Ok(exit)
+ }
+
+ fn complete_pending_io(&mut self) -> boxlite_hypervisor::Result<IoCompletion<'_>> {
+ let completion = self.vcpu.complete_pending_io()?;
+ if std::mem::take(&mut self.check_completion) {
+ assert!(
+ matches!(&completion, IoCompletion::Exit(exit)
+ if self.access.is_fragment(exit, MMIO_SPLIT_ADDR + 2)),
+ "expected the second {:?} fragment from completion, got {completion:?}",
+ self.access
+ );
+ self.completed_fragments.fetch_add(1, Ordering::Relaxed);
+ }
+ Ok(completion)
+ }
+
+ fn notify_guest_stopped(&mut self) -> boxlite_hypervisor::Result<()> {
+ self.vcpu.notify_guest_stopped()
+ }
+
+ fn handle(&self) -> Self::Handle {
+ self.vcpu.handle()
+ }
+ }
+
+ impl X86Vcpu for SplitMmioVcpu {
+ fn set_cpu_features(
+ &mut self,
+ cpuid: &[boxlite_hypervisor::X86CpuidEntry],
+ msrs: &[boxlite_hypervisor::X86Msr],
+ ) -> boxlite_hypervisor::Result<()> {
+ self.vcpu.set_cpu_features(cpuid, msrs)
+ }
+
+ fn set_boot_registers(
+ &mut self,
+ regs: &X86BootRegisters,
+ ) -> boxlite_hypervisor::Result<()> {
+ self.vcpu.set_boot_registers(regs)
+ }
+
+ fn save_state(&mut self) -> boxlite_hypervisor::Result<X86VcpuState> {
+ self.vcpu.save_state()
+ }
+ }
+
+ for access in [SplitAccess::Read, SplitAccess::Write] {
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let (gate, ready, release) = ExitGate::new();
+ let completed_fragments = Arc::new(AtomicUsize::new(0));
+ let mut guest_memory = None;
+ let mut cfg = config();
+ cfg.vcpu_count = 1;
+ let mut vm = Vm::with_backend(
+ cfg,
+ || {
+ Ok(SplitMmioVm {
+ vm: KvmVm::new()?,
+ gate,
+ access,
+ completed_fragments: Arc::clone(&completed_fragments),
+ })
+ },
+ |ram, _| {
+ guest_memory = Some(ram.memory().clone());
+ let guest = ram.memory().memory();
+ guest.store(0u32, COUNTER, Ordering::Relaxed).unwrap();
+ guest
+ .store(0xdead_beefu32, READBACK, Ordering::Relaxed)
+ .unwrap();
+ Ok(flat_guest::load(&guest, &PROGRAM))
+ },
+ |_, _| Ok(()),
+ )
+ .unwrap();
+ let guest_memory = guest_memory.unwrap();
+ let load = |addr| {
+ guest_memory
+ .memory()
+ .load::<u32>(addr, Ordering::Relaxed)
+ .unwrap()
+ };
+ let control = vm.control();
+ thread::scope(|scope| {
+ let driver = scope.spawn(|| vm.run());
+ let stop = StopOnDrop(&control);
+ ready.recv_timeout(WAIT).unwrap();
+ control.request_pause().unwrap();
+ let deadline = Instant::now() + WAIT;
+ while control.status() != VmStatus::Pausing {
+ assert!(Instant::now() < deadline);
+ thread::sleep(Duration::from_millis(1));
+ }
+ release.send(()).unwrap();
+ control.wait_paused(WAIT).unwrap();
+ assert_eq!(control.status(), VmStatus::Paused);
+ assert_eq!(completed_fragments.load(Ordering::Relaxed), 1);
+
+ control.export(&state_path, &memory_path).unwrap();
+ let memory = fs::read(&memory_path).unwrap();
+ let (header, state) = decode(&fs::read(&state_path).unwrap(), &memory);
+ assert_eq!(header.vcpus, 1);
+ assert_eq!(header.ram_len, 1 << 20);
+ assert_eq!(state.vcpus.len(), 1);
+
+ control.resume().unwrap();
+ let deadline = Instant::now() + WAIT;
+ while load(COUNTER) == 0 {
+ assert!(Instant::now() < deadline);
+ thread::sleep(Duration::from_millis(1));
+ }
+ assert_eq!(load(READBACK), u32::MAX);
+ drop(stop);
+ assert_eq!(driver.join().unwrap().unwrap(), VmExit::StopRequested);
+ });
+ }
+}
diff --git a/src/vmm/tests/snapshot/image.rs b/src/vmm/tests/snapshot/image.rs
new file mode 100644
index 000000000..aed5be9a2
--- /dev/null
+++ b/src/vmm/tests/snapshot/image.rs
@@ -0,0 +1,272 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+mod linux {
+ use std::{
+ fs::{self, File},
+ io::{self, Read, Write},
+ };
+
+ use vm_memory::{Bytes, GuestAddress};
+
+ use crate::{
+ ControlReason, Error, Result,
+ events::EventLoop,
+ lifecycle::Lifecycle,
+ memory::{GuestRam, MMIO_HOLE_START, X86_LAYOUT},
+ snapshot::image::{HEADER_LEN, Header, MAGIC, VERSION, create_new_file, write_to},
+ };
+
+ const MIB: usize = 1 << 20;
+ const PAGE: usize = 4096;
+
+ impl Header {
+ pub(crate) fn read_from(
+ reader: &mut impl Read,
+ state_len: u64,
+ memory_len: u64,
+ ) -> Result<Self> {
+ let mut bytes = [0; HEADER_LEN];
+ reader.read_exact(&mut bytes).map_err(Error::Snapshot)?;
+ let invalid =
+ |reason| Error::Snapshot(io::Error::new(io::ErrorKind::InvalidData, reason));
+ if &bytes[..8] != MAGIC
+ || u32::from_le_bytes(bytes[8..12].try_into().unwrap()) != VERSION
+ {
+ return Err(invalid("unknown snapshot magic or version"));
+ }
+ let header = Self {
+ vcpus: u32::from_le_bytes(bytes[12..16].try_into().unwrap()),
+ ram_len: u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
+ machine_len: u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
+ };
+ if (HEADER_LEN as u64).checked_add(header.machine_len) != Some(state_len)
+ || header.ram_len != memory_len
+ {
+ return Err(invalid("snapshot lengths do not match the files"));
+ }
+ Ok(header)
+ }
+ }
+
+ #[derive(Default)]
+ struct RecordingWriter {
+ output: Vec<u8>,
+ writes: Vec<usize>,
+ flushed: bool,
+ }
+
+ impl Write for RecordingWriter {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.output.extend_from_slice(buf);
+ self.writes.push(buf.len());
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.flushed = true;
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn v1_header_and_packed_ram_skip_mmio_and_respect_chunk_boundaries() {
+ let ranges = X86_LAYOUT.ranges(MMIO_HOLE_START + PAGE as u64).unwrap();
+ assert_eq!(
+ ranges,
+ [
+ (GuestAddress(0), MMIO_HOLE_START as usize),
+ (GuestAddress(1 << 32), PAGE)
+ ]
+ );
+ assert_eq!(
+ X86_LAYOUT.ranges(PAGE as u64 + 1).unwrap_err().kind(),
+ io::ErrorKind::InvalidInput
+ );
+ let low = GuestAddress(MMIO_HOLE_START - (MIB + PAGE) as u64);
+ let high = ranges[1].0;
+ let ram = GuestRam::new(&[(low, MIB + PAGE), (high, PAGE)]).unwrap();
+ ram.boot_memory()
+ .write_slice(&vec![0x35; MIB], low)
+ .unwrap();
+ ram.boot_memory()
+ .write_slice(&[0x4d; PAGE], GuestAddress(low.0 + MIB as u64))
+ .unwrap();
+ ram.boot_memory().write_slice(&[0xc7; PAGE], high).unwrap();
+ let machine = b"machine";
+ let mut state_writer = RecordingWriter::default();
+ let mut memory_writer = RecordingWriter::default();
+
+ write_to(&mut state_writer, &mut memory_writer, 2, machine, &ram).unwrap();
+
+ assert!(state_writer.flushed && memory_writer.flushed);
+ assert_eq!(state_writer.writes, [32, machine.len()]);
+ assert_eq!(memory_writer.writes, [MIB, PAGE, PAGE]);
+ let (header, body) = state_writer.output.split_at(32);
+ assert_eq!(&header[..8], b"BXLVMST1");
+ assert_eq!(&header[8..12], &1u32.to_le_bytes());
+ assert_eq!(&header[12..16], &2u32.to_le_bytes());
+ assert_eq!(&header[16..24], &((MIB + 2 * PAGE) as u64).to_le_bytes());
+ assert_eq!(&header[24..32], &(machine.len() as u64).to_le_bytes());
+ assert_eq!(body, machine);
+ let payload = memory_writer.output;
+ assert_eq!(&payload[..MIB], vec![0x35; MIB]);
+ assert_eq!(&payload[MIB..MIB + PAGE], &[0x4d; PAGE]);
+ assert_eq!(&payload[MIB + PAGE..], &[0xc7; PAGE]);
+ }
+
+ #[test]
+ fn header_reader_rejects_truncation_and_bad_framing() {
+ let ram = GuestRam::new(&[(GuestAddress(0), PAGE)]).unwrap();
+ let mut state = Vec::new();
+ let mut memory = Vec::new();
+ write_to(&mut state, &mut memory, 2, b"state", &ram).unwrap();
+ let state_len = state.len() as u64;
+ let memory_len = memory.len() as u64;
+ let header = Header::read_from(&mut state.as_slice(), state_len, memory_len).unwrap();
+ assert_eq!(
+ (header.vcpus, header.ram_len, header.machine_len),
+ (2, PAGE as u64, 5)
+ );
+
+ assert!(matches!(
+ Header::read_from(&mut &state[..31], 31, memory_len),
+ Err(Error::Snapshot(error)) if error.kind() == io::ErrorKind::UnexpectedEof
+ ));
+ for len in [state_len - 1, state_len + 1] {
+ assert!(Header::read_from(&mut state.as_slice(), len, memory_len).is_err());
+ }
+ for len in [memory_len - 1, memory_len + 1] {
+ assert!(Header::read_from(&mut state.as_slice(), state_len, len).is_err());
+ }
+ for offset in [0, 8] {
+ let mut corrupt = state.clone();
+ corrupt[offset] ^= 0xff;
+ assert!(Header::read_from(&mut corrupt.as_slice(), state_len, memory_len).is_err());
+ }
+ state[24..32].copy_from_slice(&u64::MAX.to_le_bytes());
+ assert!(Header::read_from(&mut state.as_slice(), state_len, memory_len).is_err());
+ }
+
+ #[test]
+ fn memory_write_or_flush_failure_leaves_both_files_in_place() {
+ struct FailingMemory {
+ writer: File,
+ fail_flush: bool,
+ }
+
+ impl Write for FailingMemory {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ if self.fail_flush {
+ self.writer.write(buf)
+ } else {
+ Err(io::Error::other("disk write failed"))
+ }
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Err(io::Error::other("disk flush failed"))
+ }
+ }
+
+ let ram = GuestRam::new(&[(GuestAddress(0), PAGE)]).unwrap();
+ for (fail_flush, message) in [(false, "disk write failed"), (true, "disk flush failed")] {
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let mut state = create_new_file(&state_path).unwrap();
+ let mut memory = FailingMemory {
+ writer: create_new_file(&memory_path).unwrap(),
+ fail_flush,
+ };
+ assert!(matches!(
+ write_to(&mut state, &mut memory, 1, b"state", &ram),
+ Err(Error::Snapshot(error)) if error.to_string() == message
+ ));
+ drop((state, memory));
+ assert_eq!(fs::metadata(&state_path).unwrap().len(), 37);
+ let expected_memory_len = if fail_flush { PAGE as u64 } else { 0 };
+ assert_eq!(
+ fs::metadata(&memory_path).unwrap().len(),
+ expected_memory_len
+ );
+ }
+ }
+
+ #[test]
+ fn stop_during_or_after_writeout_leaves_both_complete_files_in_place() {
+ struct StopOnWrite<'a> {
+ writer: File,
+ stop: Option<&'a Lifecycle>,
+ }
+
+ impl Write for StopOnWrite<'_> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ if let Some(lifecycle) = self.stop.take() {
+ lifecycle.stop();
+ }
+ self.writer.write(buf)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.writer.flush()
+ }
+ }
+
+ let ram = GuestRam::new(&[(GuestAddress(0), MIB + PAGE)]).unwrap();
+ for stop_during_write in [true, false] {
+ let dir = tempfile::tempdir().unwrap();
+ let state_path = dir.path().join("state");
+ let memory_path = dir.path().join("memory");
+ let events = EventLoop::new().unwrap();
+ let lifecycle = Lifecycle::new(events.sender(), true);
+ let mut state = create_new_file(&state_path).unwrap();
+ let mut memory = StopOnWrite {
+ writer: create_new_file(&memory_path).unwrap(),
+ stop: stop_during_write.then_some(&lifecycle),
+ };
+ let result = write_to(&mut state, &mut memory, 1, b"state", &ram);
+ assert!(result.is_ok());
+ drop((state, memory));
+ if !stop_during_write {
+ lifecycle.stop();
+ }
+ assert!(matches!(
+ lifecycle.finish_export(result),
+ Err(Error::Control {
+ operation: "export",
+ reason: ControlReason::TerminalOutcome,
+ })
+ ));
+ assert_eq!(fs::metadata(&state_path).unwrap().len(), 37);
+ assert_eq!(
+ fs::metadata(&memory_path).unwrap().len(),
+ (MIB + PAGE) as u64
+ );
+ }
+ }
+}
+
+#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
+#[test]
+fn export_is_unsupported_on_this_host() {
+ use super::ControlRegistry;
+ use crate::{ControlReason, Error, events::EventLoop, lifecycle::Lifecycle};
+ use std::sync::Arc;
+
+ let events = EventLoop::new().unwrap();
+ let lifecycle = Arc::new(Lifecycle::new(events.sender(), true));
+ let control = ControlRegistry::default().finish(lifecycle);
+ let dir = tempfile::tempdir().unwrap();
+ let state = dir.path().join("state");
+ let memory = dir.path().join("memory");
+ assert!(matches!(
+ control.export(&state, &memory),
+ Err(Error::Control {
+ operation: "export",
+ reason: ControlReason::Unsupported
+ })
+ ));
+ assert!(!state.exists() && !memory.exists());
+}