Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-vmm): support Windows 11 ARM64 guests with an automatic swtpm TPM (#5506)

injaneity56725dd7e47d
diff --git a/docs/content/docs/cua-sdk/guides/local-runtimes.mdx b/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
index b2d05cc64e..ffa3b92627 100644
--- a/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
+++ b/docs/content/docs/cua-sdk/guides/local-runtimes.mdx
@@ -94,6 +94,46 @@ runtime="qemu")`); cua-sandbox still accepts a `Runtime` object
- VM images without cua-spacesd fall back to the runtime's agentless path (QMP,
VNC, SSH or ADB) where there is one.
+## Windows on ARM
+
+A Windows 11 on ARM guest (`os="windows"`, `arch="aarch64"`) runs on the QEMU
+runtime of an arm64 macOS or Linux host. Windows 11 needs 4 GB: a guest started
+with less is given 4096 MB.
+
+**TPM.** The guest gets a persistent software TPM 2.0 automatically. It needs
+`swtpm` on the host's `PATH`:
+
+```bash skip="host-install"
+brew install swtpm # macOS
+sudo apt-get install swtpm # Debian, Ubuntu
+```
+
+**Secure Boot firmware.** The guest needs `AAVMF_CODE.secboot.fd` and
+`AAVMF_VARS.ms.fd`, both in one directory. cua looks, in order, at
+`CUA_QEMU_AAVMF_DIR` (when set, nowhere else), `~/.cua/firmware/aavmf`, the
+QEMU prefix's `share/AAVMF`, then `/usr/share/AAVMF`. On Linux:
+
+```bash skip="host-install"
+sudo apt-get install qemu-efi-aarch64
+```
+
+Homebrew's QEMU does not ship this pair. On macOS, download Debian's
+architecture-independent `qemu-efi-aarch64` package, unpack it, and copy the
+two files (following links) into the cua directory:
+
+```bash skip="host-install"
+mkdir -p ~/.cua/firmware/aavmf
+cp -L usr/share/AAVMF/AAVMF_CODE.secboot.fd usr/share/AAVMF/AAVMF_VARS.ms.fd ~/.cua/firmware/aavmf/
+```
+
+**Network.** Windows 11 on ARM has no inbox virtio-net driver, so the guest has
+no network during Setup. Finish OOBE offline, then install NetKVM from the
+virtio-win ISO (`NetKVM\w11\ARM64`). cua does not ship or download it.
+
+**Fork and checkpoint** need the VM stopped, so its TPM state is copied
+consistently. A checkpoint with TPM state stays on the host that made it: it is
+not exported or imported.
+
## Many VMs on one machine
Local QEMU VMs (`kind="vm"`) are admitted by what they really use, not by
diff --git a/libs/cua/crates/cua-cli/tests/cache.rs b/libs/cua/crates/cua-cli/tests/cache.rs
index 88168a4edd..3705a393a4 100644
--- a/libs/cua/crates/cua-cli/tests/cache.rs
+++ b/libs/cua/crates/cua-cli/tests/cache.rs
@@ -70,6 +70,7 @@ fn qemu_state(h: &Home, name: &str, disk: &Path, created_at: u64) {
shared_memory: false,
pinned: false,
bulk: false,
+ tpm: false,
};
std::fs::write(dir.join("state.json"), serde_json::to_vec(&st).unwrap()).unwrap();
}
diff --git a/libs/cua/crates/cua-disk/tests/gc.rs b/libs/cua/crates/cua-disk/tests/gc.rs
index f3c4ba00ac..abead734e1 100644
--- a/libs/cua/crates/cua-disk/tests/gc.rs
+++ b/libs/cua/crates/cua-disk/tests/gc.rs
@@ -102,6 +102,7 @@ fn qemu_sandbox(l: &Layout, name: &str, backing: &Path) {
shared_memory: false,
pinned: false,
bulk: false,
+ tpm: false,
};
std::fs::write(dir.join("state.json"), serde_json::to_vec(&st).unwrap()).unwrap();
}
diff --git a/libs/cua/crates/cua-vmm/src/host.rs b/libs/cua/crates/cua-vmm/src/host.rs
index a3a1658c97..db131de8d0 100644
--- a/libs/cua/crates/cua-vmm/src/host.rs
+++ b/libs/cua/crates/cua-vmm/src/host.rs
@@ -461,6 +461,25 @@ fn windows_pid_alive(pid: u32) -> bool {
}
}
+/// The command line of a process, or `None` when it is gone (or off Unix).
+pub fn pid_command(pid: u32) -> Option<String> {
+ #[cfg(unix)]
+ {
+ let out = std::process::Command::new("ps")
+ .args(["-o", "command=", "-p", &pid.to_string()])
+ .stderr(Stdio::null())
+ .output()
+ .ok()?;
+ let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ (out.status.success() && !text.is_empty()).then_some(text)
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = pid;
+ None
+ }
+}
+
/// Send a signal (`TERM`, `KILL`, ...) to a pid.
pub fn signal(pid: u32, sig: &str) {
let _ = std::process::Command::new("kill")
diff --git a/libs/cua/crates/cua-vmm/src/qemu/args.rs b/libs/cua/crates/cua-vmm/src/qemu/args.rs
index 34e80ba938..3f85398c03 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/args.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/args.rs
@@ -59,6 +59,8 @@ pub struct LaunchConfig {
pub seed_iso: Option<PathBuf>,
/// Installer ISO attached as CD-ROM and booted first.
pub install_iso: Option<PathBuf>,
+ /// Optional swtpm control socket.
+ pub tpm_socket: Option<PathBuf>,
pub firmware: Firmware,
/// `(host_port, guest_port)` TCP forwards on 127.0.0.1.
pub forwards: Vec<(u16, u16)>,
@@ -134,6 +136,7 @@ impl LaunchConfig {
/// Build the argv (excluding the binary itself).
pub fn build(cfg: &LaunchConfig) -> Vec<String> {
+ let windows_arm = cfg.os == GuestOs::Windows && cfg.arch == Arch::Aarch64;
let mut a: Vec<String> = Vec::new();
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
@@ -235,7 +238,10 @@ pub fn build(cfg: &LaunchConfig) -> Vec<String> {
// virtio storage driver is not a boot driver there, so over virtio-blk
// it cannot find its system volume and lands in WinRE. Everything else
// boots virtio.
- if cfg.os == GuestOs::Windows {
+ if windows_arm {
+ push(&["-device", "nvme,drive=disk0,serial=cua-disk0,bootindex=1"]);
+ push(&["-device", "qemu-xhci,id=xhci"]);
+ } else if cfg.os == GuestOs::Windows {
push(&[
"-device",
"ahci,id=ahci",
@@ -266,12 +272,12 @@ pub fn build(cfg: &LaunchConfig) -> Vec<String> {
iso.display()
),
]);
- push(&[
- "-device",
- "virtio-scsi-pci,id=scsi0",
- "-device",
- "scsi-cd,drive=cd0,bootindex=0",
- ]);
+ if windows_arm {
+ push(&["-device", "usb-storage,drive=cd0,bus=xhci.0,bootindex=0"]);
+ } else {
+ push(&["-device", "virtio-scsi-pci,id=scsi0"]);
+ push(&["-device", "scsi-cd,drive=cd0,bootindex=0"]);
+ }
}
}
}
@@ -328,6 +334,22 @@ pub fn build(cfg: &LaunchConfig) -> Vec<String> {
display(&mut a, cfg);
}
+ // The TPM is independent of the display: a headless restart keeps it.
+ if let Some(socket) = &cfg.tpm_socket {
+ a.extend([
+ "-chardev".to_string(),
+ format!("socket,id=chrtpm,path={}", socket.display()),
+ "-tpmdev".into(),
+ "emulator,id=tpm0,chardev=chrtpm".into(),
+ "-device".into(),
+ match cfg.arch {
+ Arch::Aarch64 => "tpm-tis-device,tpmdev=tpm0",
+ Arch::X86_64 => "tpm-tis,tpmdev=tpm0",
+ }
+ .into(),
+ ]);
+ }
+
// Management.
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
push(&[
@@ -357,22 +379,20 @@ pub fn build(cfg: &LaunchConfig) -> Vec<String> {
/// The display and input devices, VNC and the display backend.
fn display(a: &mut Vec<String>, cfg: &LaunchConfig) {
+ let windows_arm = cfg.os == GuestOs::Windows && cfg.arch == Arch::Aarch64;
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
match (&cfg.virgl_render_node, cfg.arch) {
+ _ if windows_arm => push(&["-device", "ramfb"]),
// virgl: the guest's 3D goes to the host GPU; the headless EGL
// display still feeds VNC and screendump.
(Some(_), _) => push(&["-device", "virtio-gpu-gl-pci"]),
(None, Arch::Aarch64) => push(&["-device", "virtio-gpu-pci"]),
(None, Arch::X86_64) => push(&["-vga", "std"]),
}
- push(&[
- "-device",
- "qemu-xhci,id=xhci",
- "-device",
- "usb-kbd",
- "-device",
- "usb-tablet",
- ]);
+ if !windows_arm {
+ push(&["-device", "qemu-xhci,id=xhci"]);
+ }
+ push(&["-device", "usb-kbd", "-device", "usb-tablet"]);
match &cfg.virgl_render_node {
Some(node) => push(&[
"-display",
@@ -419,6 +439,7 @@ mod tests {
disk_format: "qcow2".into(),
seed_iso: Some(PathBuf::from("/s/vm1/seed.iso")),
install_iso: None,
+ tpm_socket: None,
firmware: Firmware::Bios,
forwards: vec![(40022, 22), (40080, 8080)],
restrict_network: false,
@@ -548,6 +569,94 @@ mod tests {
assert!(has(&build(&cfg(Arch::X86_64, "kvm")), ["-display", "none"]));
}
+ #[test]
+ fn windows_arm_devices_and_tpm() {
+ let mut c = cfg(Arch::Aarch64, "hvf");
+ c.os = GuestOs::Windows;
+ c.seed_iso = None;
+ c.install_iso = Some("/install.iso".into());
+ let a = build(&c);
+ assert_eq!(
+ a,
+ serde_json::from_str::<Vec<String>>(include_str!("../../tests/argv/windows-arm.json"))
+ .unwrap()
+ );
+ for device in [
+ "ramfb",
+ "nvme,drive=disk0,serial=cua-disk0,bootindex=1",
+ "virtio-net-pci,netdev=net0",
+ "usb-storage,drive=cd0,bus=xhci.0,bootindex=0",
+ ] {
+ assert!(has(&a, ["-device", device]));
+ }
+ let controller = a.iter().position(|s| s == "qemu-xhci,id=xhci").unwrap();
+ for (i, arg) in a.iter().enumerate() {
+ if arg.contains("bus=xhci.0") {
+ assert!(controller < i);
+ }
+ assert!(
+ !arg.contains("virtio-gpu")
+ && !arg.contains("virtio-scsi")
+ && !arg.contains("ahci")
+ );
+ assert!(!arg.contains("tpm") && arg != "-chardev");
+ }
+ c.seed_iso = Some("/seed.iso".into());
+ let seeded = build(&c);
+ assert!(has(&seeded, ["-device", "virtio-blk-pci,drive=cidata"]));
+ assert_eq!(
+ seeded.iter().filter(|s| *s == "qemu-xhci,id=xhci").count(),
+ 1
+ );
+ for arch in [Arch::Aarch64, Arch::X86_64] {
+ c.arch = arch;
+ c.tpm_socket = Some("/vm/tpm/swtpm.sock".into());
+ let a = build(&c);
+ assert!(has(
+ &a,
+ ["-chardev", "socket,id=chrtpm,path=/vm/tpm/swtpm.sock"]
+ ));
+ assert!(has(&a, ["-tpmdev", "emulator,id=tpm0,chardev=chrtpm"]));
+ let mut h = c.clone();
+ h.headless = true;
+ assert!(has(
+ &build(&h),
+ ["-tpmdev", "emulator,id=tpm0,chardev=chrtpm"]
+ ));
+ assert!(has(
+ &a,
+ [
+ "-device",
+ if arch == Arch::Aarch64 {
+ "tpm-tis-device,tpmdev=tpm0"
+ } else {
+ "tpm-tis,tpmdev=tpm0"
+ }
+ ]
+ ));
+ }
+ }
+
+ #[test]
+ fn unchanged_vectors() {
+ for (name, arch, os, iso, virgl) in [
+ ("windows-x86", Arch::X86_64, GuestOs::Windows, true, false),
+ ("linux-arm", Arch::Aarch64, GuestOs::Linux, true, false),
+ ("linux-x86", Arch::X86_64, GuestOs::Linux, false, false),
+ ("virgl-arm", Arch::Aarch64, GuestOs::Linux, false, true),
+ ("virgl-x86", Arch::X86_64, GuestOs::Linux, false, true),
+ ] {
+ let mut c = cfg(arch, "kvm");
+ c.os = os;
+ c.install_iso = iso.then(|| "/install.iso".into());
+ c.virgl_render_node = virgl.then(|| "/dev/dri/renderD128".into());
+ let actual = serde_json::to_string_pretty(&build(&c)).unwrap();
+ let path =
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("tests/argv/{name}.json"));
+ assert_eq!(actual, std::fs::read_to_string(path).unwrap(), "{name}");
+ }
+ }
+
fn has(args: &[String], pair: [&str; 2]) -> bool {
args.windows(2).any(|w| w[0] == pair[0] && w[1] == pair[1])
}
diff --git a/libs/cua/crates/cua-vmm/src/qemu/export.rs b/libs/cua/crates/cua-vmm/src/qemu/export.rs
index 1d25b6c266..601fead0ca 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/export.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/export.rs
@@ -74,6 +74,12 @@ fn is_qcow2(p: &Path) -> bool {
&& m == *b"QFI\xfb"
}
+fn tpm_not_copied(name: &str) -> VmmError {
+ VmmError::invalid(format!(
+ "checkpoint '{name}' holds TPM state, which is not copied between hosts"
+ ))
+}
+
impl QemuRuntime {
/// The checkpoint ABIs this host restores: the native accelerator for
/// the host's own architecture, when memory restores work here.
@@ -100,6 +106,9 @@ impl QemuRuntime {
"'{name}' is not a checkpoint (only checkpoints are copied to other hosts)"
)));
}
+ if st.tpm {
+ return Err(tpm_not_copied(name));
+ }
let state = serde_json::to_value(&st)?;
let mut named = BTreeSet::new();
paths_in(&state, &mut named);
@@ -198,10 +207,14 @@ impl QemuRuntime {
if self.state_path(name).exists() {
return Err(VmmError::AlreadyExists(name.to_string()));
}
+ let has_tpm = state["tpm"] == true;
let mut st: QemuState = serde_json::from_value(state)?;
if st.kind != EntryKind::Checkpoint {
return Err(VmmError::invalid("only checkpoints are imported"));
}
+ if has_tpm {
+ return Err(tpm_not_copied(name));
+ }
let here = self.restorable_abis();
let theirs = abi(&st.accel, st.arch);
if !here.contains(&theirs) {
diff --git a/libs/cua/crates/cua-vmm/src/qemu/firmware.rs b/libs/cua/crates/cua-vmm/src/qemu/firmware.rs
index b4dd5c485a..11129b46b0 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/firmware.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/firmware.rs
@@ -126,6 +126,47 @@ pub fn find_uefi_with(arch: Arch, qemu_bin: &Path, exists: impl Fn(&Path) -> boo
None
}
+/// Environment variable naming the only directory searched for the Windows
+/// on ARM Secure Boot firmware pair.
+pub const AAVMF_DIR_ENV: &str = "CUA_QEMU_AAVMF_DIR";
+
+/// Directories searched for the Secure Boot pair, best first. A set
+/// override is exclusive.
+pub fn windows_arm_dirs(
+ override_dir: Option<&Path>,
+ cua_dir: &Path,
+ bin: &Path,
+ real_bin: &Path,
+) -> Vec<PathBuf> {
+ if let Some(d) = override_dir {
+ return vec![d.to_path_buf()];
+ }
+ let mut dirs = vec![cua_dir.to_path_buf()];
+ for b in [real_bin, bin] {
+ if let Some(prefix) = b.parent().and_then(Path::parent) {
+ let d = prefix.join("share/AAVMF");
+ if !dirs.contains(&d) {
+ dirs.push(d);
+ }
+ }
+ }
+ dirs.push(PathBuf::from("/usr/share/AAVMF"));
+ dirs
+}
+
+/// The first directory holding both `AAVMF_CODE.secboot.fd` and
+/// `AAVMF_VARS.ms.fd`.
+pub fn find_windows_arm(dirs: &[PathBuf], exists: impl Fn(&Path) -> bool) -> Option<Uefi> {
+ dirs.iter().find_map(|dir| {
+ let code = dir.join("AAVMF_CODE.secboot.fd");
+ let vars = dir.join("AAVMF_VARS.ms.fd");
+ (exists(&code) && exists(&vars)).then_some(Uefi {
+ code,
+ vars_template: Some(vars),
+ })
+ })
+}
+
/// Find UEFI firmware on the real filesystem.
pub fn find_uefi(arch: Arch, qemu_bin: &Path) -> Option<Uefi> {
// Resolve symlinks: Homebrew's /opt/homebrew/bin/qemu-system-* links into
@@ -173,6 +214,64 @@ mod tests {
move |p: &Path| set.contains(p)
}
+ #[test]
+ fn windows_arm_lookup_order() {
+ let d = |s: &str| PathBuf::from(s);
+ let bin = Path::new("/opt/homebrew/bin/qemu-system-aarch64");
+ let real = Path::new("/opt/homebrew/Cellar/qemu/11/bin/qemu-system-aarch64");
+ let cua = Path::new("/h/.cua/firmware/aavmf");
+ let pair = |dir: &str| {
+ [
+ format!("{dir}/AAVMF_CODE.secboot.fd"),
+ format!("{dir}/AAVMF_VARS.ms.fd"),
+ ]
+ };
+ let find = |over: Option<&Path>, dirs: &[&str]| {
+ let files: Vec<String> = dirs.iter().flat_map(|x| pair(x)).collect();
+ let refs: Vec<&str> = files.iter().map(String::as_str).collect();
+ find_windows_arm(&windows_arm_dirs(over, cua, bin, real), fs(&refs))
+ .map(|u| u.code.parent().unwrap().to_path_buf())
+ };
+ // An override is exclusive.
+ let over = Path::new("/o");
+ assert_eq!(windows_arm_dirs(Some(over), cua, bin, real), vec![d("/o")]);
+ assert_eq!(find(Some(over), &["/h/.cua/firmware/aavmf"]), None);
+ assert_eq!(find(Some(over), &["/o"]), Some(d("/o")));
+ // The cua directory beats the prefixes and the system one.
+ assert_eq!(
+ find(
+ None,
+ &[
+ "/usr/share/AAVMF",
+ "/opt/homebrew/share/AAVMF",
+ "/h/.cua/firmware/aavmf"
+ ]
+ ),
+ Some(d("/h/.cua/firmware/aavmf"))
+ );
+ // Homebrew's as-invoked prefix, when the Cellar lacks the pair.
+ assert_eq!(
+ find(None, &["/opt/homebrew/share/AAVMF"]),
+ Some(d("/opt/homebrew/share/AAVMF"))
+ );
+ assert_eq!(
+ find(
+ None,
+ &[
+ "/opt/homebrew/Cellar/qemu/11/share/AAVMF",
+ "/usr/share/AAVMF"
+ ]
+ ),
+ Some(d("/opt/homebrew/Cellar/qemu/11/share/AAVMF"))
+ );
+ // Halves from different directories never mix.
+ let split = fs(&[
+ "/h/.cua/firmware/aavmf/AAVMF_CODE.secboot.fd",
+ "/usr/share/AAVMF/AAVMF_VARS.ms.fd",
+ ]);
+ assert!(find_windows_arm(&windows_arm_dirs(None, cua, bin, real), split).is_none());
+ }
+
#[test]
fn homebrew_layout_is_found_relative_to_binary() {
let bin = Path::new("/opt/homebrew/Cellar/qemu/11.0.0/bin/qemu-system-aarch64");
diff --git a/libs/cua/crates/cua-vmm/src/qemu/mod.rs b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
index 3393b3fd59..a54f1e8b4c 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
@@ -21,7 +21,7 @@ pub mod img;
pub mod qmp;
pub mod snapshot;
-use std::collections::{BTreeMap, BTreeSet};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
@@ -274,6 +274,54 @@ pub struct QemuState {
/// cold; a memory restore keeps the device set of the snapshot it loads.
#[serde(default)]
pub bulk: bool,
+ /// swtpm TPM 2.0 with state in `tpm/` of the entry directory; set at
+ /// creation for Windows on ARM; forks and checkpoints keep it.
+ #[serde(default)]
+ pub tpm: bool,
+}
+
+/// Windows 11 on ARM: the guest that needs Secure Boot firmware and a TPM.
+fn is_windows_arm(os: GuestOs, arch: Arch) -> bool {
+ os == GuestOs::Windows && arch == Arch::Aarch64
+}
+
+/// Whether this host can run a Windows-on-ARM guest.
+fn windows_arm_host(os: GuestOs, guest: Arch, host: Arch, host_os: host::HostOs) -> Result<()> {
+ if !is_windows_arm(os, guest) {
+ return Ok(());
+ }
+ if host != Arch::Aarch64 {
+ return Err(VmmError::invalid(format!(
+ "Windows on ARM guests need an arm64 host (Apple silicon, or arm64 Linux with KVM); this host is {host}"
+ )));
+ }
+ if host_os == host::HostOs::Windows {
+ return Err(VmmError::invalid(
+ "Windows on ARM guests need swtpm for their TPM, which runs on macOS and Linux hosts only",
+ ));
+ }
+ Ok(())
+}
+
+/// Windows 11 needs 4 GB; `cua-vmm` cannot tell the 2048 MB default from an
+/// explicit 2048, so a smaller ask is raised.
+fn guest_memory_mb(os: GuestOs, arch: Arch, asked: u64) -> u64 {
+ if is_windows_arm(os, arch) {
+ asked.max(4096)
+ } else {
+ asked
+ }
+}
+
+/// A TPM VM's state cannot follow `what`: refuse before anything changes.
+fn refuse_tpm(st: &QemuState, what: &str) -> Result<()> {
+ if st.tpm {
+ return Err(VmmError::invalid(format!(
+ "'{}' has a TPM, whose state cannot follow {what}; stop it first",
+ st.name
+ )));
+ }
+ Ok(())
}
/// What `qemu` (a `qemu-system-*` binary) offers for virgl on this host:
@@ -321,6 +369,8 @@ pub async fn virgl_host(qemu: &std::path::Path) -> crate::gpu::VirglHost {
pub struct QemuRuntime {
cfg: QemuConfig,
lock: Mutex<()>,
+ /// One lock per VM name (see [`Self::own`]).
+ vm_locks: std::sync::Mutex<HashMap<String, Arc<Mutex<()>>>>,
/// Serializes recording golden snapshots.
golden_lock: Mutex<()>,
/// VMs admitted whose launch has not finished (within
@@ -349,10 +399,23 @@ const LAYERS: &str = "_layers";
const RUN_LINKS: &str = "_run";
impl QemuRuntime {
+ /// Serializes whatever starts, stops, saves or copies VM `name`. Taken
+ /// before `self.lock`, never while holding it, and never while holding
+ /// another VM lock.
+ async fn own(&self, name: &str) -> Owner {
+ let lock = {
+ let mut locks = self.vm_locks.lock().unwrap_or_else(|e| e.into_inner());
+ locks.retain(|_, l| Arc::strong_count(l) > 1);
+ locks.entry(name.to_string()).or_default().clone()
+ };
+ Arc::new(lock.lock_owned().await)
+ }
+
pub fn new(cfg: QemuConfig) -> Self {
Self {
cfg,
lock: Mutex::new(()),
+ vm_locks: Default::default(),
golden_lock: Mutex::new(()),
pending: Default::default(),
gc_asked: Default::default(),
@@ -612,13 +675,42 @@ impl QemuRuntime {
return Ok(Firmware::Bios);
}
let bin = self.binary(arch).await?;
- let fw = firmware::find_uefi(arch, &bin).ok_or_else(|| {
+ let windows_arm = is_windows_arm(os, arch);
+ let cua_dir = host::cua_home().join("firmware").join("aavmf");
+ let override_dir = std::env::var_os(firmware::AAVMF_DIR_ENV)
+ .filter(|d| !d.is_empty())
+ .map(PathBuf::from);
+ let fw = (if windows_arm {
+ let real = std::fs::canonicalize(&bin).unwrap_or_else(|_| bin.clone());
+ let dirs = firmware::windows_arm_dirs(override_dir.as_deref(), &cua_dir, &bin, &real);
+ firmware::find_windows_arm(&dirs, |p| p.is_file())
+ } else {
+ firmware::find_uefi(arch, &bin)
+ })
+ .ok_or_else(|| {
VmmError::missing(
format!("UEFI firmware for {arch}"),
- format!(
- "install edk2 (Homebrew qemu ships it; {})",
- QemuPackageManager::linux_hint()
- ),
+ if let (true, Some(dir)) = (windows_arm, &override_dir) {
+ format!(
+ "{}={} does not hold AAVMF_CODE.secboot.fd and AAVMF_VARS.ms.fd",
+ firmware::AAVMF_DIR_ENV,
+ dir.display()
+ )
+ } else if windows_arm {
+ format!(
+ "Windows on ARM needs a Secure Boot UEFI pair, AAVMF_CODE.secboot.fd and \
+ AAVMF_VARS.ms.fd (Debian's qemu-efi-aarch64 package has them): put both \
+ in {} or set {} to their directory; see \
+ https://cua.ai/docs/cua-sdk/guides/local-runtimes#windows-on-arm",
+ cua_dir.display(),
+ firmware::AAVMF_DIR_ENV
+ )
+ } else {
+ format!(
+ "install edk2 (Homebrew qemu ships it; {})",
+ QemuPackageManager::linux_hint()
+ )
+ },
)
})?;
match fw.vars_template {
@@ -665,6 +757,18 @@ impl QemuRuntime {
}
let (os, want) = boot_hints(backing, arch, spec_like).await;
let firmware = self.setup_firmware(&dir, arch, os, want).await?;
+ let tpm = is_windows_arm(os, arch);
+ if tpm {
+ std::fs::create_dir_all(dir.join("tpm"))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(
+ dir.join("tpm"),
+ std::fs::Permissions::from_mode(0o700),
+ )?;
+ }
+ }
Ok(QemuState {
name: name.to_string(),
kind: EntryKind::Instance,
@@ -702,6 +806,7 @@ impl QemuRuntime {
shared_memory: spec_like.forkable,
pinned: false,
bulk: false,
+ tpm,
})
}
.await;
@@ -752,6 +857,22 @@ impl QemuRuntime {
boot: Boot,
persist: bool,
) -> Result<()> {
+ windows_arm_host(st.os, st.arch, Arch::host(), host::HostOs::current())?;
+ let floored;
+ let spec = if guest_memory_mb(st.os, st.arch, spec.memory_mb) > spec.memory_mb {
+ tracing::info!(
+ sandbox = %st.name,
+ asked = spec.memory_mb,
+ "Windows 11 needs 4 GB; giving the VM 4096 MB"
+ );
+ floored = StartSpec {
+ memory_mb: guest_memory_mb(st.os, st.arch, spec.memory_mb),
+ ..spec.clone()
+ };
+ &floored
+ } else {
+ spec
+ };
self.admit_waiting(
&st.name,
spec.cpus,
@@ -969,12 +1090,36 @@ impl QemuRuntime {
persist: bool,
force_tcg: bool,
) -> Result<()> {
+ let owner = boot.owner.clone();
let bin = self.binary(st.arch).await?;
- let dir = st
- .disk
- .parent()
- .map(Path::to_path_buf)
- .unwrap_or_else(|| self.dir(&st.name));
+ let dir = self.run_dir(st);
+ let tpm_dir = dir.join("tpm");
+ let tpm_env: Option<(PathBuf, PathBuf)> = if st.tpm {
+ #[cfg(not(unix))]
+ return Err(VmmError::invalid("TPM requires a Unix host"));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if owner.is_none() {
+ return Err(VmmError::invalid(format!(
+ "the TPM of '{}' is only launched by a start that owns the VM",
+ st.name
+ )));
+ }
+ let bin = host::which("swtpm").ok_or_else(|| {
+ VmmError::missing(
+ "swtpm",
+ "install it (macOS: brew install swtpm; Debian/Ubuntu: sudo apt-get install swtpm) and add it to PATH",
+ )
+ })?;
+ self.stop_tpm(st).await?;
+ std::fs::create_dir_all(&tpm_dir)?;
+ std::fs::set_permissions(&tpm_dir, std::fs::Permissions::from_mode(0o700))?;
+ Some((bin, tpm_dir.clone()))
+ }
+ } else {
+ None
+ };
let mut guest_ports: Vec<u16> = spec.ports.clone();
if st.ssh.is_some() && !guest_ports.contains(&22) {
guest_ports.push(22);
@@ -1095,6 +1240,7 @@ impl QemuRuntime {
disk_format: st.disk_format.clone(),
seed_iso: st.seed_iso.clone(),
install_iso: st.install_iso.clone(),
+ tpm_socket: tpm_env.as_ref().map(|_| tpm_dir.join("swtpm.sock")),
firmware: st.firmware.clone(),
forwards: st.ports.iter().map(|(g, h)| (*h, *g)).collect(),
restrict_network: st.restrict_network,
@@ -1127,7 +1273,13 @@ impl QemuRuntime {
// A create cancelled between the launch and the moment its pid is
// recorded would leave a running QEMU nothing knows about: the
// guard ends whatever its pid file names unless the start finished.
- let mut launch_guard = LaunchGuard::new(dir.join("qemu.pid"));
+ let mut launch_guard = LaunchGuard::new();
+ launch_guard.owner = owner.clone();
+ // Each launch has its own swtpm record, so cleanup can never reach
+ // another launch's TPM through a shared pidfile.
+ let record = tpm_env
+ .as_ref()
+ .map(|_| dir.join(format!("swtpm.{}.pid", unique_suffix())));
// Launch detached: on Unix a throwaway `sh` backgrounds QEMU and exits,
// so QEMU is re-parented to init (no zombie in long-lived callers) and
@@ -1164,40 +1316,62 @@ impl QemuRuntime {
}
None => (bin.clone(), argv.clone()),
};
- // The launch runs in its own task: a cancel that drops this
- // future after the shell started QEMU but before we have its
- // pid must still end that QEMU (the task checks the flag).
- let abandoned = launch_guard.abandoned.clone();
- let pid_cell = launch_guard.pid_cell.clone();
+ // The shell runs to completion even when this future is dropped;
+ // then the undo ends exactly this launch's QEMU and TPM record.
+ let tpm_log = tpm_env.as_ref().map_or(String::new(), |_| {
+ format!("; see {}", dir.join("swtpm.log").display())
+ });
let (program2, args2, log2, dir2) =
(program.clone(), args.clone(), log_path.clone(), dir.clone());
- let pid = tokio::spawn(async move {
- let out = tokio::process::Command::new("/bin/sh")
+ let (record2, tpm_dir2) = (record.clone(), tpm_dir.clone());
+ let (record3, tpm_dir3) = (record.clone(), tpm_dir.clone());
+ let create = async move {
+ let mut command = tokio::process::Command::new("/bin/sh");
+ if let (Some((swtpm, tpm_dir)), Some(record)) = (&tpm_env, &record2) {
+ command
+ .env("CUA_SWTPM", swtpm)
+ .env("CUA_TPM_DIR", tpm_dir)
+ .env("CUA_TPM_RECORD", record);
+ }
+ let out = command
.arg("-c")
- .arg("\"$0\" \"$@\" </dev/null >>\"$CUA_QEMU_LOG\" 2>&1 & echo $!")
+ .arg(if tpm_env.is_some() {
+ TPM_LAUNCH
+ } else {
+ QEMU_LAUNCH
+ })
.arg(&program2)
.args(&args2)
.env("CUA_QEMU_LOG", &log2)
.current_dir(&dir2)
.output()
- .await?;
- let pid = String::from_utf8_lossy(&out.stdout)
- .trim()
- .parse::<u32>()
- .map_err(|e| {
- VmmError::other(format!("could not launch {}: {e}", program2.display()))
- })?;
- // Publish the pid, then look at the flag: the guard sets the
- // flag, then looks at the pid; one of the two sees the other.
- pid_cell.store(pid, std::sync::atomic::Ordering::SeqCst);
- if abandoned.load(std::sync::atomic::Ordering::SeqCst) {
- end_launched(pid).await;
+ .await;
+ let failed = match out {
+ Ok(out) => match String::from_utf8_lossy(&out.stdout).trim().parse::<u32>() {
+ Ok(pid) => return Ok::<u32, VmmError>(pid),
+ Err(e) => VmmError::other(format!(
+ "could not launch {}: {e}{tpm_log}",
+ program2.display()
+ )),
+ },
+ Err(e) => e.into(),
+ };
+ if let Some(record) = &record2 {
+ let _ = end_record(record, &tpm_dir2).await;
}
- Ok::<u32, VmmError>(pid)
- })
- .await
- .map_err(|e| VmmError::other(format!("launching qemu: {e}")))??;
+ Err(failed)
+ };
+ let owner2 = owner.clone();
+ let undo = move |pid: u32| async move {
+ let _owner = owner2;
+ end_launched(pid).await;
+ if let Some(record) = &record3 {
+ let _ = end_record(record, &tpm_dir3).await;
+ }
+ };
+ let pid = crate::cleanup::complete_or_undo(create, undo).await?;
launch_guard.pid = Some(pid);
+ launch_guard.tpm = record.map(|r| (r, tpm_dir.clone()));
st.pid = Some(pid);
if netns_rules.is_some() {
st.pasta_pid = Some(pid);
@@ -1208,12 +1382,14 @@ impl QemuRuntime {
{
// Off Linux a policy is refused before this (egress::check).
debug_assert!(netns_rules.is_none());
+ let _ = &record; // TPM VMs are refused above off Unix.
let log = std::fs::File::create(&log_path)?;
let child = std::process::Command::new(&bin)
.args(&argv)
.stdout(log.try_clone()?)
.stderr(log)
.spawn()?;
+ launch_guard.pid = Some(child.id());
st.pid = Some(child.id());
}
if persist {
@@ -1327,6 +1503,10 @@ impl QemuRuntime {
/// Restore an internal snapshot taken by [`Runtime::checkpoint`] on a
/// running instance (in place, RAM included).
pub async fn restore(&self, name: &str, snapshot: &str) -> Result<()> {
+ refuse_tpm(
+ &self.load(name)?,
+ "an in-place restore (restore by forking a stopped checkpoint)",
+ )?;
let mut q = self.qmp(name).await?;
q.loadvm(snapshot).await?;
let mut st = self.load(name)?;
@@ -1369,6 +1549,40 @@ impl QemuRuntime {
})
}
+ /// Copy the TPM state of `from` (stopped) into `to_dir/tpm`. Files are
+ /// copied, never linked; anything but plain files is an error.
+ fn copy_tpm(&self, from: &QemuState, to_dir: &Path) -> Result<()> {
+ if !from.tpm {
+ return Ok(());
+ }
+ // The disk of a checkpoint lives in the layer store: use the entry.
+ let src = self.dir(&from.name).join("tpm");
+ self.tpm_stopped(from)?;
+ let dst = to_dir.join("tpm");
+ std::fs::create_dir_all(&dst)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700))?;
+ }
+ for entry in std::fs::read_dir(&src)? {
+ let entry = entry?;
+ let name = entry.file_name();
+ if name == "swtpm.sock" || name == ".lock" {
+ continue;
+ }
+ if !entry.file_type()?.is_file() {
+ return Err(VmmError::other(format!(
+ "TPM state of '{}' holds {}, which is not a plain file",
+ from.name,
+ name.to_string_lossy()
+ )));
+ }
+ std::fs::copy(entry.path(), dst.join(&name))?;
+ }
+ Ok(())
+ }
+
/// Collects unreferenced layers after a removal. The collection reads
/// every entry's backing chain, so deleting N VMs one collection each is
/// quadratic. Deletes that wait together share collections: a delete
@@ -1458,6 +1672,51 @@ impl QemuRuntime {
!host::pid_alive(pid)
}
+ /// The directory a VM runs in (where its pidfiles and `tpm/` live). A
+ /// checkpoint's or base's disk lives in a shared store, so those use
+ /// their entry.
+ fn run_dir(&self, st: &QemuState) -> PathBuf {
+ match st.kind {
+ EntryKind::Instance => st.disk.parent().map(Path::to_path_buf),
+ EntryKind::Base | EntryKind::Checkpoint => None,
+ }
+ .unwrap_or_else(|| self.dir(&st.name))
+ }
+
+ /// End every swtpm this VM launched; a record goes only once its swtpm
+ /// has exited. The first failure is returned after trying them all.
+ async fn stop_tpm(&self, st: &QemuState) -> Result<()> {
+ let tpm_dir = self.run_dir(st).join("tpm");
+ let mut first = None;
+ for record in tpm_records(&self.run_dir(st))? {
+ if let Err(e) = end_record(&record, &tpm_dir).await {
+ first.get_or_insert(e);
+ }
+ }
+ first.map_or(Ok(()), Err)
+ }
+
+ /// Refuse while any swtpm of this VM is alive (or cannot be told apart
+ /// from one). Signals and removes nothing.
+ fn tpm_stopped(&self, st: &QemuState) -> Result<()> {
+ if !st.tpm {
+ return Ok(());
+ }
+ let run = self.run_dir(st);
+ let tpm_dir = run.join("tpm");
+ for record in tpm_records(&run)? {
+ if let Some(pid) = record_pid(&record)?
+ && swtpm_state(pid, &record, &tpm_dir) != Tpm::Gone
+ {
+ return Err(VmmError::invalid(format!(
+ "the TPM of '{}' is still running (swtpm {pid}); stop the VM first",
+ st.name
+ )));
+ }
+ }
+ Ok(())
+ }
+
async fn force_stop(&self, st: &mut QemuState, graceful: Duration) -> Result<()> {
// A stopped VM holds no memory, whatever it was still expected to
// grow to.
@@ -1466,7 +1725,7 @@ impl QemuRuntime {
st.pid = None;
self.drop_aliases(Some(&self.dir(&st.name)));
Self::end_netns(st);
- return Ok(());
+ return self.stop_tpm(st).await;
};
if !graceful.is_zero() {
let wait = if let Ok(mut q) = self.qmp(&st.name).await {
@@ -1482,7 +1741,7 @@ impl QemuRuntime {
st.pid = None;
self.drop_aliases(Some(&self.dir(&st.name)));
Self::end_netns(st);
- return Ok(());
+ return self.stop_tpm(st).await;
}
}
let quit = match self.qmp(&st.name).await {
@@ -1501,7 +1760,7 @@ impl QemuRuntime {
st.pid = None;
self.drop_aliases(Some(&self.dir(&st.name)));
Self::end_netns(st);
- Ok(())
+ self.stop_tpm(st).await
}
/// pasta exits with QEMU; one left behind (a VM killed with it) goes.
@@ -1522,6 +1781,7 @@ impl QemuRuntime {
/// The guest's disk, ports and token are kept; its memory and running
/// processes are not. A VM forked from a memory snapshot boots cold.
async fn boot_from_disk(&self, name: &str, shape: &Resize) -> Result<Instance> {
+ let owner = self.own(name).await;
let mut st = self.load(name)?;
{
let _g = self.lock.lock().await;
@@ -1570,6 +1830,8 @@ impl QemuRuntime {
spec.probes = shape.probes.clone();
spec.labels.insert(KEEP_SEED_LABEL.into(), "1".into());
spec.labels.insert(KEEP_PORTS_LABEL.into(), "1".into());
+ // `start` takes the VM lock again and reloads the state.
+ drop(owner);
self.start(&spec).await
}
@@ -1757,8 +2019,13 @@ pub(crate) struct Boot {
/// Keep the host ports (forwards, QMP, VNC) of the last run: the same
/// VM moved into a new process.
pub keep_ports: bool,
+ /// The VM's lock; kept by the launch's own cleanup; a TPM launch needs it.
+ pub owner: Option<Owner>,
}
+/// A held per-VM lock (see [`QemuRuntime::own`]).
+pub(crate) type Owner = Arc<tokio::sync::OwnedMutexGuard<()>>;
+
/// The script pasta runs in a VM's namespace ([`netns_script`]).
#[cfg_attr(not(unix), allow(dead_code))]
const NETNS_SCRIPT: &str = "netns.sh";
@@ -2112,6 +2379,7 @@ impl Runtime for QemuRuntime {
shared_memory: false,
pinned: false,
bulk: false,
+ tpm: false,
};
self.save(&st)?;
Ok(CheckpointInfo::now(base_name, BackendKind::Qemu, source))
@@ -2145,6 +2413,13 @@ impl Runtime for QemuRuntime {
crate::types::reject_injection(BackendKind::Qemu, spec)?;
crate::egress::check(BackendKind::Qemu, &spec.egress)?;
crate::cloudinit::check_guest_support(spec)?;
+ windows_arm_host(
+ spec.os,
+ spec.effective_arch(),
+ Arch::host(),
+ host::HostOs::current(),
+ )?;
+ let owner = self.own(&spec.name).await;
let (mut st, fresh_backing) = {
let _g = self.lock.lock().await;
match self.load(&spec.name) {
@@ -2289,6 +2564,7 @@ impl Runtime for QemuRuntime {
free_page_reporting: None,
headless: None,
keep_ports: spec.labels.contains_key(KEEP_PORTS_LABEL),
+ owner: Some(owner.clone()),
};
if let Err(e) = self.launch(&mut st, spec, boot, true).await {
let _ = self.force_stop(&mut st, Duration::ZERO).await;
@@ -2299,6 +2575,7 @@ impl Runtime for QemuRuntime {
self.save(&st)?;
}
}
+ drop(owner);
let inst = self.instance(&st);
if !spec.probes.is_empty() {
crate::progress::report(crate::progress::Progress::phase(
@@ -2314,6 +2591,7 @@ impl Runtime for QemuRuntime {
}
async fn stop(&self, name: &str) -> Result<()> {
+ let _owner = self.own(name).await;
let mut st = self.load(name)?;
let graceful = self.cfg.graceful_stop;
self.force_stop(&mut st, graceful).await?;
@@ -2322,6 +2600,7 @@ impl Runtime for QemuRuntime {
}
async fn suspend(&self, name: &str) -> Result<()> {
+ let _owner = self.own(name).await;
let mut q = self.qmp(name).await?;
q.stop().await?;
let mut st = self.load(name)?;
@@ -2333,8 +2612,10 @@ impl Runtime for QemuRuntime {
/// ended; its disk is kept) boots again from its own disk, in the shape
/// it had, as [`Self::resize`] boots it.
async fn resume(&self, name: &str) -> Result<Instance> {
+ let owner = self.own(name).await;
let st = self.load(name)?;
if st.kind == EntryKind::Instance && !Self::is_running(&st) {
+ drop(owner);
return self.boot_from_disk(name, &Resize::default()).await;
}
let mut q = self.qmp(name).await?;
@@ -2399,6 +2680,11 @@ impl Runtime for QemuRuntime {
"'{member}' is not a running VM, so it cannot be claimed"
)));
}
+ if st.tpm {
+ return Err(VmmError::invalid(format!(
+ "'{member}' has a TPM, whose swtpm is bound to the VM's directory; it cannot be claimed"
+ )));
+ }
if self.dir(new_name).exists() {
return Err(VmmError::AlreadyExists(new_name.to_string()));
}
@@ -2450,16 +2736,23 @@ impl Runtime for QemuRuntime {
async fn fork(&self, source: &str, new_name: &str) -> Result<()> {
validate_name(new_name)?;
- let _g = self.lock.lock().await;
- if self.state_path(new_name).exists() {
- return Err(VmmError::AlreadyExists(new_name.to_string()));
- }
// `vm@snapshot` forks from an internal snapshot (disk state only).
let (src_name, snapshot) = match source.split_once('@') {
Some((a, b)) => (a, Some(b)),
None => (source, None),
};
+ let _owner = self.own(src_name).await;
+ let _g = self.lock.lock().await;
+ if self.state_path(new_name).exists() {
+ return Err(VmmError::AlreadyExists(new_name.to_string()));
+ }
let mut src = self.load(src_name)?;
+ if src.tpm && snapshot.is_some() {
+ return refuse_tpm(&src, "a disk snapshot (fork a stopped checkpoint instead)");
+ }
+ if Self::is_running(&src) {
+ refuse_tpm(&src, "a live fork")?;
+ }
let dir = self.dir(new_name);
// A running VM forks with its memory: a one-time snapshot in the
// fork's own directory, restored at the fork's first start.
@@ -2508,6 +2801,7 @@ impl Runtime for QemuRuntime {
"'{src_name}' is running; stop it (or checkpoint it) before forking"
)));
}
+ self.tpm_stopped(&src)?;
let backing = match (snapshot, src.kind) {
(Some(snap), _) => {
// A full copy of the disk at that snapshot.
@@ -2555,6 +2849,10 @@ impl Runtime for QemuRuntime {
EntryKind::Base => self.setup_firmware(&dir, src.arch, src.os, None).await?,
_ => self.copy_vars(&src.firmware, &dir)?,
};
+ if let Err(e) = self.copy_tpm(&src, &dir) {
+ let _ = std::fs::remove_dir_all(&dir);
+ return Err(e);
+ }
let st = QemuState {
name: new_name.into(),
kind: EntryKind::Instance,
@@ -2593,8 +2891,12 @@ impl Runtime for QemuRuntime {
async fn checkpoint(&self, name: &str, checkpoint: &str) -> Result<CheckpointInfo> {
validate_name(checkpoint)?;
+ let _owner = self.own(name).await;
let _g = self.lock.lock().await;
let mut st = self.load(name)?;
+ if Self::is_running(&st) {
+ refuse_tpm(&st, "a live checkpoint")?;
+ }
if Self::is_running(&st) && self.restores_memory() {
// Live: a memory checkpoint entry (RAM, devices, a copy of the
// disk layer); forks of it restore that memory with their own
@@ -2680,10 +2982,15 @@ impl Runtime for QemuRuntime {
if self.state_path(checkpoint).exists() {
return Err(VmmError::AlreadyExists(checkpoint.to_string()));
}
+ self.tpm_stopped(&st)?;
let layer = self.freeze(&mut st).await?;
self.save(&st)?;
let dir = self.dir(checkpoint);
let firmware = self.copy_vars(&st.firmware, &dir)?;
+ if let Err(e) = self.copy_tpm(&st, &dir) {
+ let _ = std::fs::remove_dir_all(&dir);
+ return Err(e);
+ }
let ck = QemuState {
name: checkpoint.into(),
kind: EntryKind::Checkpoint,
@@ -2724,11 +3031,15 @@ impl Runtime for QemuRuntime {
policy: &crate::egress::EgressPolicy,
) -> Result<crate::egress::Enforcement> {
let rules = crate::egress::check(BackendKind::Qemu, policy)?;
+ let _owner = self.own(name).await;
let _g = self.lock.lock().await;
let mut st = self.load(name)?;
if st.kind != EntryKind::Instance {
return Err(VmmError::invalid(format!("'{name}' is not a VM instance")));
}
+ if Self::is_running(&st) && !st.netns && rules.blocks_anything() {
+ refuse_tpm(&st, "a move into a new network namespace")?;
+ }
let previous = st.egress.replace(policy.clone());
if Self::is_running(&st) {
let applied = if st.netns {
@@ -2831,6 +3142,7 @@ impl Runtime for QemuRuntime {
}
async fn delete(&self, name: &str) -> Result<()> {
+ let owner = self.own(name).await;
let st = self.load(name)?;
// A fork made but not started yet restores this checkpoint's memory.
if st.kind == EntryKind::Checkpoint {
@@ -2855,6 +3167,7 @@ impl Runtime for QemuRuntime {
self.force_stop(&mut st, Duration::ZERO).await?;
std::fs::remove_dir_all(self.dir(name))?;
drop(_g);
+ drop(owner);
return self.collect_layers().await;
}
// Stopping a VM waits on its own process, so it runs outside the
@@ -2869,6 +3182,7 @@ impl Runtime for QemuRuntime {
}
std::fs::remove_dir_all(self.dir(name))?;
}
+ drop(owner);
self.collect_layers().await
}
@@ -2895,6 +3209,16 @@ impl Runtime for QemuRuntime {
}
}
+#[cfg(unix)]
+const QEMU_LAUNCH: &str = "\"$0\" \"$@\" </dev/null >>\"$CUA_QEMU_LOG\" 2>&1 & echo $!";
+
+#[cfg(unix)]
+const TPM_LAUNCH: &str = r#""$CUA_SWTPM" socket --daemon --tpm2 --terminate --ctrl "type=unixio,path=$CUA_TPM_DIR/swtpm.sock" --pid "file=$CUA_TPM_RECORD" --tpmstate "dir=$CUA_TPM_DIR" </dev/null >>"$CUA_TPM_DIR/../swtpm.log" 2>&1 || exit 1
+"$0" "$@" </dev/null >>"$CUA_QEMU_LOG" 2>&1 & echo $!"#;
+
+#[cfg(all(test, unix))]
+mod tpm_tests;
+
/// The snapshot RAM file a VM shares with others, as admission counts it
/// ([`crate::density`]): a file mapped copy-on-write (`share=off`, a
/// restore or a fork) is counted once for every VM mapping it, on top of
@@ -3160,6 +3484,281 @@ mod tests {
assert_eq!(left, 0, "unreferenced layers should be garbage-collected");
}
+ #[test]
+ fn windows_arm_host_policy() {
+ use host::HostOs::*;
+ let x86 = "Windows on ARM guests need an arm64 host (Apple silicon, or arm64 Linux with KVM); this host is x86_64";
+ let win = "Windows on ARM guests need swtpm for their TPM, which runs on macOS and Linux hosts only";
+ let msg = |r: Result<()>| match r.unwrap_err() {
+ VmmError::Invalid(m) => m,
+ e => panic!("{e:?}"),
+ };
+ let (w, a) = (GuestOs::Windows, Arch::Aarch64);
+ assert_eq!(msg(windows_arm_host(w, a, Arch::X86_64, Linux)), x86);
+ assert_eq!(msg(windows_arm_host(w, a, Arch::Aarch64, Windows)), win);
+ assert!(windows_arm_host(w, a, Arch::Aarch64, Macos).is_ok());
+ assert!(windows_arm_host(w, a, Arch::Aarch64, Linux).is_ok());
+ assert!(windows_arm_host(GuestOs::Linux, a, Arch::X86_64, Linux).is_ok());
+ assert!(windows_arm_host(w, Arch::X86_64, Arch::X86_64, Linux).is_ok());
+ }
+
+ #[test]
+ fn windows_arm_memory_floor() {
+ let (w, a) = (GuestOs::Windows, Arch::Aarch64);
+ assert_eq!(guest_memory_mb(w, a, 2048), 4096);
+ assert_eq!(guest_memory_mb(w, a, 4096), 4096);
+ assert_eq!(guest_memory_mb(w, a, 8192), 8192);
+ assert_eq!(guest_memory_mb(GuestOs::Linux, a, 2048), 2048);
+ assert_eq!(guest_memory_mb(w, Arch::X86_64, 2048), 2048);
+ }
+
+ #[cfg(unix)]
+ fn invalid(r: Result<impl std::fmt::Debug>) -> String {
+ match r.unwrap_err() {
+ VmmError::Invalid(m) => m,
+ e => panic!("{e:?}"),
+ }
+ }
+
+ #[cfg(unix)]
+ /// A runtime with a base, a stopped TPM VM `vm1`, and its TPM files.
+ async fn tpm_runtime(tmp: &Path) -> Option<QemuRuntime> {
+ if img::qemu_img().is_err() {
+ eprintln!("qemu-img missing; skipping");
+ return None;
+ }
+ let root = tmp.join("qemu");
+ let r = rt(&root);
+ let image = tmp.join("image.qcow2");
+ img::create_blank(&image, 1).await.unwrap();
+ r.ensure_base(&ImageSource::disk(&image), "base")
+ .await
+ .unwrap();
+ let mut base = r.load("base").unwrap();
+ base.arch = Arch::X86_64;
+ r.save(&base).unwrap();
+ r.fork("base", "vm1").await.unwrap();
+ let mut vm = r.load("vm1").unwrap();
+ vm.tpm = true;
+ r.save(&vm).unwrap();
+ let tpm = root.join("vm1/tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ std::fs::write(tpm.join("tpm2-00.permall"), b"keys-1").unwrap();
+ Some(r)
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn tpm_state_follows_stopped_fork_and_checkpoint() {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ let root = tmp.path().join("qemu");
+ let _sock =
+ std::os::unix::net::UnixListener::bind(root.join("vm1/tpm/swtpm.sock")).unwrap();
+ r.checkpoint("vm1", "ck1").await.unwrap();
+ let (src, ck) = (
+ root.join("vm1/tpm/tpm2-00.permall"),
+ root.join("ck1/tpm/tpm2-00.permall"),
+ );
+ assert_eq!(std::fs::read(&ck).unwrap(), b"keys-1");
+ assert!(!root.join("ck1/tpm/swtpm.sock").exists());
+ assert!(r.load("ck1").unwrap().tpm);
+ assert_ne!(
+ std::fs::metadata(&src).unwrap().ino(),
+ std::fs::metadata(&ck).unwrap().ino()
+ );
+ std::fs::write(&src, b"keys-2").unwrap();
+ assert_eq!(std::fs::read(&ck).unwrap(), b"keys-1");
+ r.fork("ck1", "f1").await.unwrap();
+ assert_eq!(
+ std::fs::read(root.join("f1/tpm/tpm2-00.permall")).unwrap(),
+ b"keys-1"
+ );
+ assert!(r.load("f1").unwrap().tpm);
+ for d in ["ck1", "f1"] {
+ let m = std::fs::metadata(root.join(d).join("tpm")).unwrap();
+ assert_eq!(m.permissions().mode() & 0o777, 0o700, "{d}");
+ }
+ // A stopped fork of the VM itself carries the current state.
+ r.fork("vm1", "f2").await.unwrap();
+ assert_eq!(
+ std::fs::read(root.join("f2/tpm/tpm2-00.permall")).unwrap(),
+ b"keys-2"
+ );
+
+ let msg = "holds TPM state, which is not copied between hosts";
+ let err = invalid(r.export("ck1").await);
+ assert_eq!(err, format!("checkpoint 'ck1' {msg}"));
+ let mut state = serde_json::to_value(r.load("ck1").unwrap()).unwrap();
+ state["tpm"] = true.into();
+ let err = invalid(r.import("ck2", state, vec![]).await);
+ assert_eq!(err, format!("checkpoint 'ck2' {msg}"));
+ }
+
+ /// A stopped checkpoint's disk lives in the shared layer store; deleting
+ /// it must not treat that store as its run directory.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn deleting_a_checkpoint_leaves_a_swtpm_in_the_layer_store_alone() {
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ r.checkpoint("vm1", "ck1").await.unwrap();
+ let shared = r.load("ck1").unwrap().disk.parent().unwrap().to_path_buf();
+ assert_ne!(shared, r.dir("ck1"), "the checkpoint's disk is shared");
+ let link = super::tpm_tests::fake_swtpm_link(tmp.path());
+ let mut other = super::tpm_tests::spawn_fake(
+ &link,
+ &shared.join("swtpm.other.pid"),
+ &shared.join("tpm"),
+ );
+ r.delete("ck1").await.unwrap();
+ assert!(r.load("ck1").is_err());
+ assert!(
+ other.try_wait().unwrap().is_none(),
+ "a swtpm that is not the checkpoint's was stopped"
+ );
+ other.kill().unwrap();
+ other.wait().unwrap();
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn tpm_copy_fails_closed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ let root = tmp.path().join("qemu");
+ std::fs::create_dir(root.join("vm1/tpm/nested")).unwrap();
+ assert!(r.checkpoint("vm1", "ck1").await.is_err());
+ assert!(!root.join("ck1").exists());
+ std::fs::remove_dir_all(root.join("vm1/tpm")).unwrap();
+ assert!(r.checkpoint("vm1", "ck2").await.is_err());
+ assert!(!root.join("ck2").exists());
+ assert!(r.load("ck1").is_err() && r.load("ck2").is_err());
+ assert!(r.load("vm1").is_ok());
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn fork_and_checkpoint_refuse_a_live_tpm_before_freezing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ let root = tmp.path().join("qemu");
+ let link = super::tpm_tests::fake_swtpm_link(tmp.path());
+ let mut fake = super::tpm_tests::spawn_fake(
+ &link,
+ &root.join("vm1/swtpm.a.pid"),
+ &root.join("vm1/tpm"),
+ );
+ let disk = r.load("vm1").unwrap().disk;
+ let count = |r: &QemuRuntime| std::fs::read_dir(r.layers_dir()).map_or(0, |d| d.count());
+ let layers = count(&r);
+ let e = r.checkpoint("vm1", "ck1").await.unwrap_err().to_string();
+ assert!(e.contains("still running"), "{e}");
+ let e = r.fork("vm1", "vm2").await.unwrap_err().to_string();
+ assert!(e.contains("still running"), "{e}");
+ assert_eq!(r.load("vm1").unwrap().disk, disk);
+ assert_eq!(count(&r), layers);
+ assert!(r.load("ck1").is_err() && r.load("vm2").is_err());
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_copy_waiting_for_its_vm_lets_unrelated_vms_proceed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ let r = Arc::new(r);
+ let root = tmp.path().join("qemu");
+ // Each copy of vm1 waits behind its owner while a fork of another
+ // source completes; the copy finishes once vm1 is released.
+ for (other, checkpoint) in [("other1", false), ("other2", true)] {
+ let owner = r.own("vm1").await;
+ let r2 = r.clone();
+ let copy = tokio::spawn(async move {
+ match checkpoint {
+ true => r2.checkpoint("vm1", "ck1").await.map(drop),
+ false => r2.fork("vm1", "f1").await,
+ }
+ });
+ // The single-threaded test runtime runs the copy until it waits.
+ for _ in 0..10 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::timeout(Duration::from_secs(10), r.fork("base", other))
+ .await
+ .expect("an unrelated fork completes while a copy waits")
+ .unwrap();
+ assert!(!copy.is_finished(), "the copy waits for vm1");
+ drop(owner);
+ copy.await.unwrap().unwrap();
+ }
+ assert!(root.join("f1/tpm/tpm2-00.permall").exists());
+ assert!(root.join("ck1/tpm/tpm2-00.permall").exists());
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn live_tpm_vm_refusals() {
+ let tmp = tempfile::tempdir().unwrap();
+ let Some(r) = tpm_runtime(tmp.path()).await else {
+ return;
+ };
+ let root = tmp.path().join("qemu");
+ let names = |r: &QemuRuntime| {
+ let mut v: Vec<_> = std::fs::read_dir(&r.cfg.root)
+ .unwrap()
+ .map(|e| e.unwrap().file_name())
+ .collect();
+ v.sort();
+ v
+ };
+ let before = names(&r);
+ let refused = |what: &str| {
+ format!("'vm1' has a TPM, whose state cannot follow {what}; stop it first")
+ };
+ // A stopped TPM VM refuses a disk-snapshot fork.
+ assert_eq!(
+ invalid(r.fork("vm1@snap", "x").await),
+ refused("a disk snapshot (fork a stopped checkpoint instead)")
+ );
+ let mut vm = r.load("vm1").unwrap();
+ vm.pid = Some(std::process::id());
+ r.save(&vm).unwrap();
+ assert_eq!(invalid(r.fork("vm1", "x").await), refused("a live fork"));
+ assert_eq!(
+ invalid(r.checkpoint("vm1", "x").await),
+ refused("a live checkpoint")
+ );
+ assert_eq!(
+ invalid(r.restore("vm1", "s").await),
+ refused("an in-place restore (restore by forking a stopped checkpoint)")
+ );
+ let block = crate::egress::EgressPolicy {
+ deny: vec!["all".into()],
+ ..Default::default()
+ };
+ assert_eq!(
+ invalid(r.set_egress("vm1", &block).await),
+ refused("a move into a new network namespace")
+ );
+ // A policy that blocks nothing needs no namespace, so it is saved.
+ r.set_egress("vm1", &Default::default()).await.unwrap();
+ assert_eq!(names(&r), before);
+ assert!(!root.join("x").exists());
+ }
+
#[tokio::test]
async fn disk_chain_bookkeeping_without_booting() {
if img::qemu_img().is_err() {
@@ -4083,18 +4682,156 @@ mod tests {
}
}
-/// Ends the QEMU a start launched when the start does not finish (its
-/// future dropped by a cancel, or an early error): the pid file QEMU writes
-/// names it even before the caller recorded the pid.
+/// What a recorded pid is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Tpm {
+ /// The swtpm of that record.
+ Ours,
+ /// Not alive, or something else now (a reused pid, a zombie).
+ Gone,
+ /// Alive, but `ps` cannot say what it is: never signalled.
+ Unknown,
+}
+
+/// Whether `pid` is the swtpm launched with `record` for `tpm_dir`.
+fn swtpm_state(pid: u32, record: &Path, tpm_dir: &Path) -> Tpm {
+ if pid < 2 {
+ return Tpm::Gone;
+ }
+ let Some(cmd) = host::pid_command(pid) else {
+ return if host::pid_alive(pid) {
+ Tpm::Unknown
+ } else {
+ Tpm::Gone
+ };
+ };
+ // The shared pidfile earlier builds passed, spelled as they spelled it.
+ let file = if record.file_name().is_some_and(|n| n == "swtpm.pid") {
+ format!("file={}/../swtpm.pid", tpm_dir.display())
+ } else {
+ format!("file={}", record.display())
+ };
+ let dir = format!("dir={}", tpm_dir.display());
+ // Linux keeps argument boundaries (and a path with spaces): the program
+ // and arguments must be exactly ours. Elsewhere the program is the text
+ // before the `socket` subcommand.
+ let (is_swtpm, ours) = if let Ok(raw) = std::fs::read(format!("/proc/{pid}/cmdline")) {
+ let args: Vec<&[u8]> = raw.split(|b| *b == 0).collect();
+ let exe = std::str::from_utf8(args[0]).unwrap_or_default();
+ (
+ Path::new(exe).file_name().is_some_and(|n| n == "swtpm"),
+ args.contains(&file.as_bytes()) && args.contains(&dir.as_bytes()),
+ )
+ } else {
+ text_identity(&cmd, &file, &dir)
+ };
+ if is_swtpm && ours {
+ Tpm::Ours
+ } else {
+ Tpm::Gone
+ }
+}
+
+/// Without argument boundaries the record and directory must be the last
+/// options, in the launch script's order, so no longer path (`tpm -backup`,
+/// `tpm backup`) can pass for it.
+fn names_dir_text(cmd: &str, file: &str, dir: &str) -> bool {
+ cmd.ends_with(&format!("--pid {file} --tpmstate {dir}"))
+}
+
+/// (is swtpm, is this launch's) from `ps` text: the program is the text
+/// before the `socket` subcommand.
+fn text_identity(cmd: &str, file: &str, dir: &str) -> (bool, bool) {
+ let exe = cmd.split_once(" socket ").map_or_else(
+ || cmd.split_whitespace().next().unwrap_or_default(),
+ |(e, _)| e,
+ );
+ (
+ Path::new(exe).file_name().is_some_and(|n| n == "swtpm"),
+ names_dir_text(cmd, file, dir),
+ )
+}
+
+/// The pid a swtpm record holds.
+/// A vanished record is `None`; an unreadable or malformed one is an error,
+/// never "no TPM".
+fn record_pid(record: &Path) -> Result<Option<u32>> {
+ let text = match std::fs::read_to_string(record) {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ r => r?,
+ };
+ text.trim().parse::<u32>().map(Some).map_err(|_| {
+ VmmError::other(format!(
+ "the swtpm record {} is malformed; remove it once its TPM is gone",
+ record.display()
+ ))
+ })
+}
+
+/// The swtpm records in a VM's run directory. Only a missing directory is
+/// empty: anything that cannot be listed is an error, never "no TPM".
+fn tpm_records(dir: &Path) -> Result<Vec<PathBuf>> {
+ let entries = match std::fs::read_dir(dir) {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ r => r?,
+ };
+ let mut out = Vec::new();
+ for e in entries {
+ let e = e?;
+ let n = e.file_name();
+ let n = n.to_string_lossy();
+ if n.starts_with("swtpm.") && n.ends_with(".pid") {
+ out.push(e.path());
+ }
+ }
+ Ok(out)
+}
+
+/// End the swtpm a record names: TERM, then KILL. The record is removed only
+/// once that swtpm is gone; otherwise it stays and this is an error.
+async fn end_record(record: &Path, tpm_dir: &Path) -> Result<()> {
+ let Some(pid) = record_pid(record)? else {
+ return Ok(());
+ };
+ for (sig, polls) in [("TERM", 20), ("KILL", 10)] {
+ if swtpm_state(pid, record, tpm_dir) != Tpm::Ours {
+ break;
+ }
+ host::signal(pid, sig);
+ for _ in 0..polls {
+ if swtpm_state(pid, record, tpm_dir) != Tpm::Ours {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+ if swtpm_state(pid, record, tpm_dir) == Tpm::Gone {
+ let _ = std::fs::remove_file(record);
+ return Ok(());
+ }
+ Err(VmmError::other(format!(
+ "the TPM of '{}' (swtpm {pid}) did not exit",
+ tpm_dir
+ .parent()
+ .and_then(Path::file_name)
+ .unwrap_or_default()
+ .to_string_lossy()
+ )))
+}
+
+/// Ends the QEMU (and the TPM record) a start launched when the start does
+/// not finish, keeping the VM locked until that has run (its future dropped by a cancel, or an early error). The
+/// launch shell itself is covered by `complete_or_undo`; this covers the
+/// time from the reported pid until the start succeeds. It ends only the
+/// pid and record it was handed.
struct LaunchGuard {
- pidfile: PathBuf,
armed: bool,
- /// Set when dropped armed, for a launch task still in flight.
- abandoned: Arc<std::sync::atomic::AtomicBool>,
/// The launched process, once known.
pid: Option<u32>,
- /// The pid as the launch task learned it (0: not yet).
- pid_cell: Arc<std::sync::atomic::AtomicU32>,
+ /// The swtpm record and TPM directory of this launch.
+ tpm: Option<(PathBuf, PathBuf)>,
+ /// The VM's lock, kept until the clean-up has run.
+ owner: Option<Owner>,
}
/// TERM, then KILL, a QEMU nobody will use.
@@ -4110,13 +4847,12 @@ async fn end_launched(pid: u32) {
}
impl LaunchGuard {
- fn new(pidfile: PathBuf) -> Self {
+ fn new() -> Self {
Self {
- pidfile,
armed: true,
- abandoned: Arc::new(std::sync::atomic::AtomicBool::new(false)),
pid: None,
- pid_cell: Arc::new(std::sync::atomic::AtomicU32::new(0)),
+ tpm: None,
+ owner: None,
}
}
@@ -4127,41 +4863,17 @@ impl LaunchGuard {
impl Drop for LaunchGuard {
fn drop(&mut self) {
- if !self.armed {
+ if !self.armed || (self.pid.is_none() && self.tpm.is_none()) {
return;
}
- self.abandoned
- .store(true, std::sync::atomic::Ordering::SeqCst);
- let known =
- self.pid.or_else(
- || match self.pid_cell.load(std::sync::atomic::Ordering::SeqCst) {
- 0 => None,
- p => Some(p),
- },
- );
- if let Some(pid) = known {
- crate::cleanup::spawn(async move { end_launched(pid).await });
- return;
- }
- let pidfile = self.pidfile.clone();
+ let (pid, tpm, owner) = (self.pid, self.tpm.take(), self.owner.take());
crate::cleanup::spawn(async move {
- // QEMU writes the file a moment after it starts.
- for _ in 0..40 {
- if let Some(pid) = std::fs::read_to_string(&pidfile)
- .ok()
- .and_then(|t| t.trim().parse::<u32>().ok())
- {
- host::signal(pid, "TERM");
- for _ in 0..20 {
- if !host::pid_alive(pid) {
- return;
- }
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- host::signal(pid, "KILL");
- return;
- }
- tokio::time::sleep(Duration::from_millis(100)).await;
+ let _owner = owner;
+ if let Some(p) = pid {
+ end_launched(p).await;
+ }
+ if let Some((r, d)) = tpm {
+ let _ = end_record(&r, &d).await;
}
});
}
@@ -4178,7 +4890,7 @@ mod launch_guard_tests {
.spawn()
.unwrap();
let pid = child.id();
- let mut g = LaunchGuard::new(PathBuf::from("/nonexistent/qemu.pid"));
+ let mut g = LaunchGuard::new();
g.pid = Some(pid);
drop(g);
assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
@@ -4193,7 +4905,7 @@ mod launch_guard_tests {
.arg("30")
.spawn()
.unwrap();
- let mut g = LaunchGuard::new(PathBuf::from("/nonexistent/qemu.pid"));
+ let mut g = LaunchGuard::new();
g.pid = Some(child.id());
g.disarm();
drop(g);
diff --git a/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs b/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
index 7a67a9c563..f0e33bceb1 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/snapshot.rs
@@ -358,6 +358,7 @@ impl QemuRuntime {
(spec.gpu.is_some(), "a GPU"),
(!spec.extra_args.is_empty(), "extra QEMU arguments"),
(st.install_iso.is_some(), "an installer ISO"),
+ (st.tpm, "a TPM"),
(st.arch != Arch::host(), "an emulated architecture"),
(accel == "tcg", "no hardware acceleration"),
];
@@ -554,6 +555,7 @@ impl QemuRuntime {
// do the VMs restoring it.
free_page_reporting: Some(false),
headless: Some(super::no_desktop(&tspec)),
+ owner: None,
};
self.launch(&mut tpl, &tspec, boot, false).await?;
let ep = self.endpoints_of(&tpl);
@@ -656,12 +658,7 @@ impl QemuRuntime {
.filter(|pid| host::pid_alive(*pid))
// Only the template VM itself (a pid may have been reused).
.filter(|pid| {
- std::process::Command::new("ps")
- .args(["-o", "command=", "-p", &pid.to_string()])
- .output()
- .is_ok_and(|o| {
- String::from_utf8_lossy(&o.stdout).contains(&p.display().to_string())
- })
+ host::pid_command(*pid).is_some_and(|c| c.contains(&p.display().to_string()))
})
{
host::signal(pid, "KILL");
@@ -769,6 +766,7 @@ impl QemuRuntime {
keep_ports: false,
free_page_reporting: Some(snap.free_page_reporting),
headless: Some(snap.headless),
+ owner: None,
};
self.launch(st, spec, boot, true).await?;
let t_launch = started.elapsed();
@@ -1001,6 +999,7 @@ impl QemuRuntime {
// The same VM: the device set it runs with.
free_page_reporting: Some(st.free_page_reporting),
headless: Some(st.headless),
+ owner: None,
};
let moved: Result<()> = async {
self.launch(st, &spec, boot, true).await?;
@@ -1115,6 +1114,7 @@ impl QemuRuntime {
free_page_reporting: Some(snap.free_page_reporting),
headless: Some(snap.headless),
keep_ports: false,
+ owner: None,
};
self.launch(&mut helper, &spec, boot, false).await?;
let mut q = self.qmp_at(&helper).await?;
@@ -1330,6 +1330,7 @@ mod tests {
ram_file: None,
headless: false,
bulk: false,
+ tpm: false,
egress: None,
netns: false,
pasta_pid: None,
diff --git a/libs/cua/crates/cua-vmm/src/qemu/tpm_tests.rs b/libs/cua/crates/cua-vmm/src/qemu/tpm_tests.rs
new file mode 100644
index 0000000000..55b2f348a1
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/qemu/tpm_tests.rs
@@ -0,0 +1,985 @@
+use super::*;
+use std::os::unix::fs::PermissionsExt;
+
+#[test]
+fn fake_swtpm() {
+ // Runs only with swtpm's own options, which a normal test run never has.
+ let args: Vec<String> = std::env::args().collect();
+ if !args.iter().any(|a| a == "--tpmstate") {
+ return;
+ }
+ let arg = |key: &str| {
+ args.iter()
+ .find_map(|a| a.strip_prefix(key))
+ .map(PathBuf::from)
+ .unwrap()
+ };
+ let (record, dir) = (arg("file="), arg("dir="));
+ std::fs::create_dir_all(&dir).unwrap();
+ let _listener = std::os::unix::net::UnixListener::bind(dir.join("swtpm.sock")).unwrap();
+ std::fs::write(record, std::process::id().to_string()).unwrap();
+ std::thread::sleep(Duration::from_secs(30));
+}
+
+#[tokio::test]
+async fn daemon_script_success_failure_and_force_stop() {
+ for mode in ["success", "failure"] {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().into(),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(dir.join("tpm")).unwrap();
+ let tpm = dir.join("swtpm");
+ let body = match mode {
+ "failure" => "#!/bin/sh\nexit 1\n",
+ _ => {
+ "#!/bin/sh\nfor a; do case \"$a\" in file=*) f=\"${a#file=}\";; dir=*) d=\"${a#dir=}\";; esac; done\n\"$CUA_FAKE_SWTPM\" --exact qemu::tpm_tests::fake_swtpm --nocapture -- --pid \"file=$f\" --tpmstate \"dir=$d\" </dev/null >/dev/null 2>&1 &\nwhile [ ! -S \"$d/swtpm.sock\" ] || [ ! -s \"$f\" ]; do sleep 0.01; done\n"
+ }
+ };
+ std::fs::write(&tpm, body).unwrap();
+ std::fs::set_permissions(&tpm, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let output = tokio::time::timeout(
+ Duration::from_secs(4),
+ tokio::process::Command::new("/bin/sh")
+ .arg("-c")
+ .arg(TPM_LAUNCH)
+ .arg("/bin/sh")
+ .args([
+ "-c",
+ "[ -S \"$CUA_TPM_DIR/swtpm.sock\" ] && touch \"$CUA_TPM_DIR/../started\"",
+ ])
+ .env("CUA_FAKE_SWTPM", fake_swtpm_link(tmp.path()))
+ .env("CUA_SWTPM", &tpm)
+ .env("CUA_TPM_DIR", dir.join("tpm"))
+ .env("CUA_TPM_RECORD", dir.join("swtpm.test.pid"))
+ .env("CUA_QEMU_LOG", dir.join("qemu.log"))
+ .output(),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ if mode == "success" {
+ assert!(output.status.success());
+ for _ in 0..100 {
+ if dir.join("started").exists() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert!(dir.join("started").exists());
+ // stop_tpm only needs the persisted instance name.
+ let mut st: QemuState = serde_json::from_value(serde_json::json!({
+ "name":"vm", "kind":"instance", "arch":"aarch64", "os":"windows",
+ "disk":dir.join("disk"), "disk_format":"qcow2", "firmware":{"type":"bios"},
+ "cpus":2, "memory_mb":4096, "created_at":0, "tpm":true
+ }))
+ .unwrap_or_else(|_| panic!("state fixture must deserialize"));
+ let pid: u32 = std::fs::read_to_string(dir.join("swtpm.test.pid"))
+ .unwrap()
+ .parse()
+ .unwrap();
+ assert!(host::pid_alive(pid));
+ st.pid = None;
+ runtime.force_stop(&mut st, Duration::ZERO).await.unwrap();
+ assert!(!dir.join("swtpm.test.pid").exists());
+ assert!(!host::pid_alive(pid));
+ } else {
+ assert!(!output.status.success());
+ assert!(!dir.join("started").exists());
+ }
+ }
+}
+
+#[tokio::test]
+async fn launch_once_wiring_child() {
+ let Ok(root) = std::env::var("CUA_WIRING_ROOT") else {
+ return;
+ };
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: root.into(),
+ vnc: false,
+ allow_install: false,
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut st: QemuState = serde_json::from_value(serde_json::json!({
+ "name":"vm", "kind":"instance", "arch":"aarch64", "os":"windows",
+ "disk":dir.join("disk"), "disk_format":"qcow2", "firmware":{"type":"bios"},
+ "cpus":2, "memory_mb":4096, "created_at":0, "tpm":true
+ }))
+ .unwrap();
+ let spec = StartSpec::new("vm", ImageSource::Existing);
+ // A TPM launch without the VM lock is refused before anything is made.
+ let error = runtime
+ .launch_once(&mut st, &spec, Boot::default(), true, true)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "invalid request: the TPM of 'vm' is only launched by a start that owns the VM"
+ );
+ assert!(!dir.join("tpm").exists());
+ assert!(tpm_records(&dir).unwrap().is_empty());
+ let owned = || async {
+ Boot {
+ owner: Some(runtime.own("vm").await),
+ ..Default::default()
+ }
+ };
+ if std::env::var("CUA_WIRING_MODE").unwrap() == "missing" {
+ // A machine with a system-wide swtpm cannot exercise missing discovery.
+ if host::which("swtpm").is_some() {
+ return;
+ }
+ let error = runtime
+ .launch_once(&mut st, &spec, owned().await, true, true)
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ VmmError::Missing { ref what, ref hint }
+ if what == "swtpm" && hint.starts_with("install it (macOS: brew install swtpm;")
+ ));
+ assert!(!dir.join("tpm").exists());
+ } else {
+ let error = runtime
+ .launch_once(&mut st, &spec, owned().await, true, true)
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("swtpm.log"), "{error}");
+ assert!(error.to_string().contains("could not launch"));
+ let argv = std::fs::read_to_string(dir.join("cmdline")).unwrap();
+ assert!(argv.contains(&format!(
+ "socket,id=chrtpm,path={}",
+ dir.join("tpm/swtpm.sock").display()
+ )));
+ assert!(argv.contains("tpm-tis-device,tpmdev=tpm0"));
+ }
+}
+
+#[test]
+fn launch_once_wiring() {
+ for mode in ["missing", "persisted"] {
+ let tmp = tempfile::tempdir().unwrap();
+ let bin = tmp.path().join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ for name in if mode == "missing" {
+ vec!["qemu-system-aarch64"]
+ } else {
+ vec!["qemu-system-aarch64", "swtpm"]
+ } {
+ let path = bin.join(name);
+ std::fs::write(&path, "#!/bin/sh\nexit 1\n").unwrap();
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "qemu::tpm_tests::launch_once_wiring_child",
+ "--nocapture",
+ ])
+ .env("PATH", &bin)
+ .env("CUA_WIRING_ROOT", tmp.path().join("state"))
+ .env("CUA_WIRING_MODE", mode)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ }
+}
+
+#[test]
+fn tpm_state_defaults_off() {
+ let st: QemuState = serde_json::from_value(serde_json::json!({
+ "name":"vm", "kind":"instance", "arch":"aarch64", "os":"windows",
+ "disk":"/d", "disk_format":"qcow2", "firmware":{"type":"bios"},
+ "cpus":2, "memory_mb":4096, "created_at":0
+ }))
+ .unwrap();
+ assert!(!st.tpm);
+}
+
+/// The test binary behind a symlink named `swtpm`, so its argv passes the
+/// production identity check.
+pub(super) fn fake_swtpm_link(dir: &Path) -> PathBuf {
+ let link = dir.join("swtpm");
+ if !link.exists() {
+ std::os::unix::fs::symlink(std::env::current_exe().unwrap(), &link).unwrap();
+ }
+ link
+}
+
+/// The arguments a fake swtpm runs with: they satisfy the `/proc` check and
+/// the `ps`-text check (which must end with the record and directory).
+fn fake_args(record: &Path, tpm_dir: &Path) -> Vec<String> {
+ [
+ "socket",
+ "--exact",
+ "qemu::tpm_tests::fake_swtpm",
+ "--nocapture",
+ "--",
+ "--pid",
+ ]
+ .iter()
+ .map(|s| s.to_string())
+ .chain([
+ format!("file={}", record.display()),
+ "--tpmstate".into(),
+ format!("dir={}", tpm_dir.display()),
+ ])
+ .collect()
+}
+
+fn wait_started(child: &mut std::process::Child, record: &Path, tpm_dir: &Path) {
+ for _ in 0..500 {
+ if tpm_dir.join("swtpm.sock").exists() && record_pid(record).ok().flatten().is_some() {
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let _ = child.kill();
+ let _ = child.wait();
+ panic!("fake swtpm did not start");
+}
+
+/// A running fake swtpm serving `tpm_dir`, recorded in `record`.
+pub(super) fn spawn_fake(link: &Path, record: &Path, tpm_dir: &Path) -> std::process::Child {
+ let mut child = std::process::Command::new(link)
+ .args(fake_args(record, tpm_dir))
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ wait_started(&mut child, record, tpm_dir);
+ child
+}
+
+/// The same, with TERM ignored (an ignored signal survives `exec`).
+fn spawn_fake_ignoring_term(link: &Path, record: &Path, tpm_dir: &Path) -> std::process::Child {
+ let mut child = std::process::Command::new("/bin/sh")
+ .args(["-c", "trap \"\" TERM; exec \"$0\" \"$@\""])
+ .arg(link)
+ .args(fake_args(record, tpm_dir))
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ wait_started(&mut child, record, tpm_dir);
+ child
+}
+
+pub(super) fn tpm_state(name: &str, dir: &Path) -> QemuState {
+ serde_json::from_value(serde_json::json!({
+ "name":name, "kind":"instance", "arch":"aarch64", "os":"windows",
+ "disk":dir.join("disk"), "disk_format":"qcow2", "firmware":{"type":"bios"},
+ "cpus":2, "memory_mb":4096, "created_at":0, "tpm":true
+ }))
+ .unwrap()
+}
+
+#[test]
+fn fake_matches_the_identity_contract() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let (record, tpm) = (tmp.path().join("swtpm.a.pid"), tmp.path().join("tpm"));
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ assert_eq!(swtpm_state(fake.id(), &record, &tpm), Tpm::Ours);
+ // The macOS rule, on the `ps` text.
+ let cmd = host::pid_command(fake.id()).unwrap();
+ assert!(names_dir_text(
+ &cmd,
+ &format!("file={}", record.display()),
+ &format!("dir={}", tpm.display())
+ ));
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+}
+
+#[tokio::test]
+async fn stop_tpm_leaves_other_processes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(dir.join("tpm")).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ let other = tmp.path().join("other/tpm");
+ let prefix = dir.join("tpm-other");
+ let mut sleeper = std::process::Command::new("sleep")
+ .arg("30")
+ .spawn()
+ .unwrap();
+ let mut elsewhere = spawn_fake(&link, &tmp.path().join("r1.pid"), &other);
+ let mut prefixed = spawn_fake(&link, &tmp.path().join("r2.pid"), &prefix);
+ let mut spaced = spawn_fake(&link, &tmp.path().join("r3.pid"), &dir.join("tpm backup"));
+ // The same directory, another launch's record.
+ let mut sibling = spawn_fake(&link, &tmp.path().join("r4.pid"), &dir.join("tpm"));
+ for pid in [
+ sleeper.id().to_string(),
+ elsewhere.id().to_string(),
+ prefixed.id().to_string(),
+ spaced.id().to_string(),
+ sibling.id().to_string(),
+ "0".into(),
+ "1".into(),
+ ] {
+ let record = dir.join("swtpm.mine.pid");
+ std::fs::write(&record, &pid).unwrap();
+ st.pid = None;
+ runtime.force_stop(&mut st, Duration::ZERO).await.unwrap();
+ assert!(!record.exists(), "{pid}");
+ }
+ for child in [
+ &mut sleeper,
+ &mut elsewhere,
+ &mut prefixed,
+ &mut spaced,
+ &mut sibling,
+ ] {
+ assert!(child.try_wait().unwrap().is_none(), "survives");
+ child.kill().unwrap();
+ child.wait().unwrap();
+ }
+}
+
+#[tokio::test]
+async fn stop_tpm_kills_a_swtpm_that_ignores_term() {
+ use std::os::unix::process::ExitStatusExt;
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ let tpm = dir.join("tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake_ignoring_term(&link, &record, &tpm);
+ let st = tpm_state("vm", &dir);
+ runtime.stop_tpm(&st).await.unwrap();
+ assert!(!record.exists());
+ assert_eq!(fake.wait().unwrap().signal(), Some(9));
+}
+
+#[test]
+fn copy_refused_until_the_tpm_exits() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ let tpm = dir.join("tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ let st = tpm_state("vm", &dir);
+ let dst = tmp.path().join("dst");
+ for _ in 0..2 {
+ let e = runtime.copy_tpm(&st, &dst).unwrap_err().to_string();
+ assert!(e.contains("still running"), "{e}");
+ assert!(record.exists());
+ assert!(!dst.join("tpm").exists());
+ }
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+ runtime.copy_tpm(&st, &dst).unwrap();
+ assert!(dst.join("tpm").exists());
+}
+
+/// Stand-ins for `swtpm` (starts the fake after a delay) and QEMU (sleeps)
+/// on a PATH of their own.
+#[tokio::test]
+async fn cancelled_launch_child() {
+ let Ok(root) = std::env::var("CUA_CANCEL_ROOT") else {
+ return;
+ };
+ let root = PathBuf::from(root);
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: root.join("state"),
+ vnc: false,
+ allow_install: false,
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ let spec = StartSpec::new("vm", ImageSource::Existing);
+ let boot = Boot {
+ owner: Some(runtime.own("vm").await),
+ ..Default::default()
+ };
+ let launch = runtime.launch_once(&mut st, &spec, boot, true, true);
+ // Early: cancelled while the launch shell runs. Late: cancelled after the
+ // pid is persisted, while the launch waits for QMP.
+ let late = std::env::var("CUA_CANCEL_LATE").is_ok();
+ let wait = if late {
+ Duration::from_secs(2)
+ } else {
+ Duration::from_millis(100)
+ };
+ assert!(tokio::time::timeout(wait, launch).await.is_err());
+ // The VM is released only once the cancelled launch's own cleanup is done.
+ let _owner = tokio::time::timeout(Duration::from_secs(10), runtime.own("vm"))
+ .await
+ .expect("the VM is released");
+ let tpm = dir.join("tpm");
+ // Early cancellation can precede either stub's pid write, including when
+ // the launch shell has already backgrounded QEMU. Late cancellation must
+ // still exercise both processes after they started.
+ for file in ["fake.pid", "qemu.pid"] {
+ match std::fs::read_to_string(root.join(file)) {
+ Ok(pid) => assert!(!host::pid_alive(pid.trim().parse().unwrap()), "{file}"),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound && !late => {}
+ Err(e) => panic!("{file}: {e}"),
+ }
+ }
+ // Check even when a stub never wrote its pid. Both stand-ins retain the
+ // unique run directory in argv, including after the QEMU stub execs sleep.
+ let ps = std::process::Command::new("ps")
+ .args(["-ww", "-axo", "command="])
+ .output()
+ .unwrap();
+ assert!(ps.status.success());
+ let commands = String::from_utf8_lossy(&ps.stdout);
+ let live: Vec<_> = commands
+ .lines()
+ .filter(|line| line.contains(root.to_str().unwrap()))
+ .collect();
+ assert!(live.is_empty(), "processes survived VM release: {live:?}");
+ assert!(
+ tpm_records(&dir).unwrap().is_empty(),
+ "its record is removed"
+ );
+
+ drop(_owner);
+ // A replacement on the same directory is not touched by late cleanup.
+ let _ = std::fs::remove_file(tpm.join("swtpm.sock"));
+ let link = fake_swtpm_link(&root);
+ let mut new = spawn_fake(&link, &dir.join("swtpm.new.pid"), &tpm);
+ assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ assert!(new.try_wait().unwrap().is_none());
+ new.kill().unwrap();
+ new.wait().unwrap();
+}
+
+#[test]
+fn cancelled_launch_cleans_up_before_settle_returns() {
+ cancelled_launch(false);
+}
+
+/// Production guard ownership: cancelled after the pid is persisted.
+#[test]
+fn a_launch_cancelled_while_waiting_for_qmp_keeps_the_vm_until_cleanup() {
+ cancelled_launch(true);
+}
+
+fn cancelled_launch(late: bool) {
+ let tmp = tempfile::tempdir().unwrap();
+ let bin = tmp.path().join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let sleeper = tmp.path().join("qemu-sleep");
+ std::os::unix::fs::symlink(host::which("sleep").unwrap(), &sleeper).unwrap();
+ let exe = |name: &str, body: String| {
+ let path = bin.join(name);
+ std::fs::write(&path, body).unwrap();
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
+ };
+ exe(
+ "qemu-system-aarch64",
+ format!(
+ "#!/bin/sh\necho $$ > {}\nexec {} 30\n",
+ tmp.path().join("qemu.pid").display(),
+ sleeper.display()
+ ),
+ );
+ exe(
+ "swtpm",
+ format!(
+ "#!/bin/sh\n{nap}for a; do case \"$a\" in file=*) f=\"${{a#file=}}\";; dir=*) d=\"${{a#dir=}}\";; esac; done\n\"{link}\" --exact qemu::tpm_tests::fake_swtpm --nocapture -- --pid \"file=$f\" --tpmstate \"dir=$d\" </dev/null >/dev/null 2>&1 &\nwhile [ ! -S \"$d/swtpm.sock\" ] || [ ! -s \"$f\" ]; do sleep 0.01; done\ncp \"$f\" {pid}\n",
+ link = link.display(),
+ pid = tmp.path().join("fake.pid").display(),
+ nap = if late { "" } else { "sleep 0.5\n" }
+ ),
+ );
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "qemu::tpm_tests::cancelled_launch_child",
+ "--nocapture",
+ ])
+ .env(
+ "PATH",
+ format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()),
+ )
+ .env("CUA_CANCEL_ROOT", tmp.path())
+ .envs(late.then_some(("CUA_CANCEL_LATE", "1")))
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
+#[tokio::test]
+async fn a_guard_without_pids_touches_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let tpm = tmp.path().join("tpm");
+ let mut fake = spawn_fake(&link, &tmp.path().join("swtpm.a.pid"), &tpm);
+ for f in ["swtpm.pid", "qemu.pid"] {
+ std::fs::write(tmp.path().join(f), fake.id().to_string()).unwrap();
+ }
+ drop(LaunchGuard::new());
+ assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
+ assert!(fake.try_wait().unwrap().is_none());
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+}
+
+#[tokio::test]
+async fn abandoned_launch_stops_swtpm() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let tpm = tmp.path().join("tpm");
+ let record = tmp.path().join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ let mut guard = LaunchGuard::new();
+ guard.tpm = Some((record.clone(), tpm));
+ drop(guard);
+ assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
+ assert!(fake.wait().is_ok());
+ assert!(!record.exists());
+}
+
+#[tokio::test]
+async fn late_cleanup_leaves_the_replacement_swtpm() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let tpm = tmp.path().join("tpm");
+ let record = tmp.path().join("swtpm.old.pid");
+ let mut old = spawn_fake(&link, &record, &tpm);
+ let mut guard = LaunchGuard::new();
+ guard.tpm = Some((record.clone(), tpm.clone()));
+ drop(guard);
+ // A replacement takes over the directory under its own record.
+ std::fs::remove_file(tpm.join("swtpm.sock")).unwrap();
+ let new_record = tmp.path().join("swtpm.new.pid");
+ let mut new = spawn_fake(&link, &new_record, &tpm);
+ assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
+ old.wait().unwrap();
+ assert!(new.try_wait().unwrap().is_none(), "replacement survives");
+ assert_eq!(record_pid(&new_record).unwrap(), Some(new.id()));
+ new.kill().unwrap();
+ new.wait().unwrap();
+}
+
+#[test]
+fn text_fallback_requires_the_exact_last_directory() {
+ let (f, n) = ("file=/vm/swtpm.a.pid", "dir=/vm/tpm");
+ assert!(names_dir_text(
+ "/bin/swtpm socket --tpm2 --pid file=/vm/swtpm.a.pid --tpmstate dir=/vm/tpm",
+ f,
+ n
+ ));
+ assert!(!names_dir_text(
+ "/bin/swtpm socket --pid file=/vm/swtpm.a.pid --tpmstate dir=/vm/tpm -backup",
+ f,
+ n
+ ));
+ assert!(!names_dir_text(
+ "/bin/swtpm socket --pid file=/vm/swtpm.a.pid --tpmstate dir=/vm/tpm backup",
+ f,
+ n
+ ));
+ assert!(!names_dir_text(
+ "/bin/swtpm socket --pid file=/vm/swtpm.b.pid --tpmstate dir=/vm/tpm",
+ f,
+ n
+ ));
+}
+
+#[test]
+fn identity_survives_a_spaced_executable_and_the_legacy_pidfile() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spaced = tmp.path().join("bin dir");
+ std::fs::create_dir(&spaced).unwrap();
+ let link = fake_swtpm_link(&spaced);
+ let (run, tpm) = (tmp.path().join("run"), tmp.path().join("run/tpm"));
+ std::fs::create_dir_all(&run).unwrap();
+ let record = run.join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ assert_eq!(swtpm_state(fake.id(), &record, &tpm), Tpm::Ours);
+ // The non-Linux path: the whole identity from the `ps` text.
+ let cmd = host::pid_command(fake.id()).unwrap();
+ let (f, d) = (
+ format!("file={}", record.display()),
+ format!("dir={}", tpm.display()),
+ );
+ assert_eq!(text_identity(&cmd, &f, &d), (true, true), "{cmd}");
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+ // The previous launch script's spelling of the shared pidfile.
+ let link = fake_swtpm_link(tmp.path());
+ let (run, tpm) = (tmp.path().join("run2"), tmp.path().join("run2/tpm"));
+ std::fs::create_dir_all(&run).unwrap();
+ let old = tpm.join("../swtpm.pid");
+ let mut fake = spawn_fake(&link, &old, &tpm);
+ assert_eq!(
+ swtpm_state(fake.id(), &run.join("swtpm.pid"), &tpm),
+ Tpm::Ours
+ );
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+}
+
+#[tokio::test]
+async fn a_tpm_vm_cannot_be_claimed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(dir.join("tpm")).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ st.pid = Some(std::process::id());
+ runtime.save(&st).unwrap();
+ let id = crate::types::ClaimIdentity::default();
+ let e = runtime
+ .claim("vm", "vm2", &id)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(e.contains("cannot be claimed"), "{e}");
+ assert!(dir.join("tpm").exists() && !runtime.dir("vm2").exists());
+}
+
+/// Waits until a second caller is queued on VM `name`'s lock: the registry,
+/// the holder's guard and the waiter's clone each hold the lock.
+pub(super) async fn wait_queued(runtime: &QemuRuntime, name: &str) {
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ let n = runtime
+ .vm_locks
+ .lock()
+ .unwrap()
+ .get(name)
+ .map_or(0, Arc::strong_count);
+ if n >= 3 {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("the caller queued");
+}
+
+/// B acquires the VM after A's start succeeded: it reads A's state, returns
+/// that instance and touches neither A's TPM nor its record.
+#[tokio::test]
+async fn a_queued_start_returns_the_vm_its_predecessor_started() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = Arc::new(QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ vnc: false,
+ allow_install: false,
+ preflight_tools: false,
+ ..Default::default()
+ }));
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ runtime.save(&st).unwrap();
+ let a = runtime.own("vm").await;
+ let b = {
+ let runtime = runtime.clone();
+ tokio::spawn(async move {
+ runtime
+ .start(&StartSpec::new("vm", ImageSource::Existing))
+ .await
+ })
+ };
+ wait_queued(&runtime, "vm").await;
+ let mut sleeper = std::process::Command::new("sleep")
+ .arg("30")
+ .spawn()
+ .unwrap();
+ st.pid = Some(sleeper.id());
+ runtime.save(&st).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &dir.join("tpm"));
+ drop(a);
+ let inst = b.await.unwrap().unwrap();
+ assert_eq!(inst.status, Status::Running);
+ assert!(crate::cleanup::settle(Duration::from_secs(10)).await);
+ assert!(fake.try_wait().unwrap().is_none(), "A's TPM is alive");
+ assert!(record.exists());
+ assert_eq!(runtime.load("vm").unwrap().pid, Some(sleeper.id()));
+ assert!(!dir.join("cmdline").exists(), "nothing was launched");
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+ sleeper.kill().unwrap();
+ sleeper.wait().unwrap();
+}
+
+/// A dropped launch keeps the VM locked until its own cleanup has ended its
+/// swtpm (here one that needs KILL).
+#[tokio::test]
+async fn a_dropped_launch_keeps_the_vm_until_its_cleanup_ends() {
+ use futures::FutureExt;
+ use std::os::unix::process::ExitStatusExt;
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ let tpm = dir.join("tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake_ignoring_term(&link, &record, &tpm);
+ let owner = runtime.own("vm").await;
+ let mut guard = LaunchGuard::new();
+ guard.tpm = Some((record.clone(), tpm));
+ guard.owner = Some(owner.clone());
+ drop(guard);
+ drop(owner);
+ assert!(runtime.own("vm").now_or_never().is_none(), "still held");
+ let _again = tokio::time::timeout(Duration::from_secs(30), runtime.own("vm"))
+ .await
+ .expect("released after the cleanup");
+ assert_eq!(fake.wait().unwrap().signal(), Some(9));
+ assert!(!record.exists());
+}
+
+/// The failure handler of `start` runs under the VM lock: when a waiting
+/// caller gets the VM, the leftover only the VM-wide stop reaches is gone.
+#[test]
+fn failed_start_holds_the_vm_through_its_cleanup() {
+ if Arch::host() != Arch::Aarch64 || host::HostOs::current() == host::HostOs::Windows {
+ return;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ // One spelling for every path: scripts rebuild paths from `$PWD`.
+ let tmp_root = tmp.path().canonicalize().unwrap();
+ let tmp = tmp_root.as_path();
+ let bin = tmp.join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ let link = fake_swtpm_link(tmp);
+ let exe = |name: &str, body: String| {
+ let path = bin.join(name);
+ std::fs::write(&path, body).unwrap();
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
+ };
+ exe(
+ "swtpm",
+ format!(
+ "#!/bin/sh\nfor a; do case \"$a\" in file=*) f=\"${{a#file=}}\";; dir=*) d=\"${{a#dir=}}\";; esac; done\n\"{link}\" --exact qemu::tpm_tests::fake_swtpm --nocapture -- --pid \"file=$f\" --tpmstate \"dir=$d\" </dev/null >/dev/null 2>&1 &\nwhile [ ! -S \"$d/swtpm.sock\" ] || [ ! -s \"$f\" ]; do sleep 0.01; done\ncp \"$f\" {pid}\n",
+ link = link.display(),
+ pid = tmp.join("fake.pid").display()
+ ),
+ );
+ exe(
+ "qemu-system-aarch64",
+ format!(
+ "#!/bin/sh\nrm -f \"$PWD/tpm/swtpm.sock\"\n(trap \"\" TERM; exec \"{link}\" socket --exact qemu::tpm_tests::fake_swtpm --nocapture -- --pid \"file=$PWD/swtpm.extra.pid\" --tpmstate \"dir=$PWD/tpm\" </dev/null >/dev/null 2>&1) &\nwhile [ ! -s \"$PWD/swtpm.extra.pid\" ]; do sleep 0.01; done\ncp \"$PWD/swtpm.extra.pid\" {pid}\nexit 1\n",
+ link = link.display(),
+ pid = tmp.join("extra.pid").display()
+ ),
+ );
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "qemu::tpm_tests::failed_start_child",
+ "--nocapture",
+ ])
+ .env(
+ "PATH",
+ format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()),
+ )
+ .env("CUA_FAILED_START_ROOT", tmp)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
+#[tokio::test]
+async fn failed_start_child() {
+ let Ok(root) = std::env::var("CUA_FAILED_START_ROOT") else {
+ return;
+ };
+ let root = PathBuf::from(root);
+ let runtime = Arc::new(QemuRuntime::new(QemuConfig {
+ root: root.join("state"),
+ accel: Some("tcg".into()),
+ vnc: false,
+ allow_install: false,
+ preflight_tools: false,
+ density: crate::density::DensityConfig {
+ enabled: false,
+ ..Default::default()
+ },
+ ..Default::default()
+ }));
+ let dir = runtime.dir("vm");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ st.arch = Arch::host();
+ runtime.save(&st).unwrap();
+ let mut spec = StartSpec::new("vm", ImageSource::Existing);
+ spec.os = GuestOs::Windows;
+ spec.arch = Some(Arch::host());
+ let a = {
+ let runtime = runtime.clone();
+ tokio::spawn(async move { runtime.start(&spec).await })
+ };
+ for _ in 0..3000 {
+ if dir.join("cmdline").exists() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert!(dir.join("cmdline").exists());
+ let extra = dir.join("swtpm.extra.pid");
+ let b = {
+ let (runtime, extra) = (runtime.clone(), extra.clone());
+ tokio::spawn(async move {
+ let _owner = runtime.own("vm").await;
+ extra.exists()
+ })
+ };
+ let e = a.await.unwrap().unwrap_err();
+ assert!(
+ matches!(&e, VmmError::Command { code: None, cmd, .. } if cmd.contains("cmdline")),
+ "{e}"
+ );
+ assert!(!b.await.unwrap(), "the leftover was gone when B acquired");
+ assert_eq!(runtime.load("vm").unwrap().pid, None);
+ assert!(tpm_records(&dir).unwrap().is_empty());
+ for f in ["fake.pid", "extra.pid"] {
+ let pid: u32 = std::fs::read_to_string(root.join(f))
+ .unwrap()
+ .trim()
+ .parse()
+ .unwrap();
+ assert!(!host::pid_alive(pid), "{f}");
+ }
+}
+
+/// A run directory that cannot be listed is an error everywhere, never "no
+/// TPM": nothing is stopped, copied or removed.
+#[tokio::test]
+async fn an_unreadable_run_dir_stops_and_copies_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ let tpm = dir.join("tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ assert_eq!(
+ tpm_records(&tmp.path().join("missing")).unwrap(),
+ Vec::<PathBuf>::new()
+ );
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o300)).unwrap();
+ if std::fs::read_dir(&dir).is_ok() {
+ // Root reads anything.
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+ return;
+ }
+ let mut st = tpm_state("vm", &dir);
+ let dst = tmp.path().join("dst");
+ let denied = |e: VmmError| {
+ assert!(
+ matches!(&e, VmmError::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
+ "{e:?}"
+ )
+ };
+ denied(tpm_records(&dir).unwrap_err());
+ denied(runtime.stop_tpm(&st).await.unwrap_err());
+ st.pid = None;
+ denied(
+ runtime
+ .force_stop(&mut st, Duration::ZERO)
+ .await
+ .unwrap_err(),
+ );
+ denied(runtime.tpm_stopped(&st).unwrap_err());
+ denied(runtime.copy_tpm(&st, &dst).unwrap_err());
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
+ assert!(!dst.join("tpm").exists());
+ assert!(fake.try_wait().unwrap().is_none());
+ assert!(record.exists());
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+}
+
+#[tokio::test]
+async fn an_unreadable_or_malformed_record_stops_and_copies_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let link = fake_swtpm_link(tmp.path());
+ let runtime = QemuRuntime::new(QemuConfig {
+ root: tmp.path().join("root"),
+ ..Default::default()
+ });
+ let dir = runtime.dir("vm");
+ let tpm = dir.join("tpm");
+ std::fs::create_dir_all(&tpm).unwrap();
+ let record = dir.join("swtpm.a.pid");
+ let mut fake = spawn_fake(&link, &record, &tpm);
+ let text = std::fs::read_to_string(&record).unwrap();
+ let mut st = tpm_state("vm", &dir);
+ st.pid = None;
+ let dst = tmp.path().join("dst");
+ std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o000)).unwrap();
+ let unreadable = std::fs::read_to_string(&record).is_err();
+ for malformed in [false, true] {
+ if malformed {
+ std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o600)).unwrap();
+ std::fs::write(&record, "garbage").unwrap();
+ } else if !unreadable {
+ continue; // root reads anything
+ }
+ assert!(runtime.stop_tpm(&st).await.is_err());
+ assert!(runtime.force_stop(&mut st, Duration::ZERO).await.is_err());
+ assert!(runtime.tpm_stopped(&st).is_err());
+ assert!(runtime.copy_tpm(&st, &dst).is_err());
+ assert!(!dst.join("tpm").exists());
+ assert!(fake.try_wait().unwrap().is_none(), "swtpm survives");
+ assert!(record.exists() && tpm.exists());
+ }
+ std::fs::write(&record, text).unwrap();
+ fake.kill().unwrap();
+ fake.wait().unwrap();
+}
diff --git a/libs/cua/crates/cua-vmm/tests/argv/linux-arm.json b/libs/cua/crates/cua-vmm/tests/argv/linux-arm.json
new file mode 100644
index 0000000000..4759f75e55
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/linux-arm.json
@@ -0,0 +1,57 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "virt,memory-backend=mem0",
+ "-cpu",
+ "host",
+ "-accel",
+ "kvm",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "virtio-blk-pci,drive=disk0,bootindex=1",
+ "-drive",
+ "file=/s/vm1/seed.iso,if=none,id=cidata,format=raw,readonly=on",
+ "-device",
+ "virtio-blk-pci,drive=cidata",
+ "-drive",
+ "file=/install.iso,if=none,id=cd0,format=raw,readonly=on,media=cdrom",
+ "-device",
+ "virtio-scsi-pci,id=scsi0",
+ "-device",
+ "scsi-cd,drive=cd0,bootindex=0",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-device",
+ "virtio-rng-pci",
+ "-device",
+ "virtio-gpu-pci",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "none",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
\ No newline at end of file
diff --git a/libs/cua/crates/cua-vmm/tests/argv/linux-x86.json b/libs/cua/crates/cua-vmm/tests/argv/linux-x86.json
new file mode 100644
index 0000000000..ad530e7166
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/linux-x86.json
@@ -0,0 +1,51 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "q35,smm=off,memory-backend=mem0",
+ "-cpu",
+ "host",
+ "-accel",
+ "kvm",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "virtio-blk-pci,drive=disk0,bootindex=1",
+ "-drive",
+ "file=/s/vm1/seed.iso,if=none,id=cidata,format=raw,readonly=on",
+ "-device",
+ "virtio-blk-pci,drive=cidata",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-device",
+ "virtio-rng-pci",
+ "-vga",
+ "std",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "none",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
\ No newline at end of file
diff --git a/libs/cua/crates/cua-vmm/tests/argv/virgl-arm.json b/libs/cua/crates/cua-vmm/tests/argv/virgl-arm.json
new file mode 100644
index 0000000000..363c9f0754
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/virgl-arm.json
@@ -0,0 +1,51 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "virt,memory-backend=mem0",
+ "-cpu",
+ "host",
+ "-accel",
+ "kvm",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "virtio-blk-pci,drive=disk0,bootindex=1",
+ "-drive",
+ "file=/s/vm1/seed.iso,if=none,id=cidata,format=raw,readonly=on",
+ "-device",
+ "virtio-blk-pci,drive=cidata",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-device",
+ "virtio-rng-pci",
+ "-device",
+ "virtio-gpu-gl-pci",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "egl-headless,rendernode=/dev/dri/renderD128",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
\ No newline at end of file
diff --git a/libs/cua/crates/cua-vmm/tests/argv/virgl-x86.json b/libs/cua/crates/cua-vmm/tests/argv/virgl-x86.json
new file mode 100644
index 0000000000..0497d1357c
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/virgl-x86.json
@@ -0,0 +1,51 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "q35,smm=off,memory-backend=mem0",
+ "-cpu",
+ "host",
+ "-accel",
+ "kvm",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "virtio-blk-pci,drive=disk0,bootindex=1",
+ "-drive",
+ "file=/s/vm1/seed.iso,if=none,id=cidata,format=raw,readonly=on",
+ "-device",
+ "virtio-blk-pci,drive=cidata",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-device",
+ "virtio-rng-pci",
+ "-device",
+ "virtio-gpu-gl-pci",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "egl-headless,rendernode=/dev/dri/renderD128",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
\ No newline at end of file
diff --git a/libs/cua/crates/cua-vmm/tests/argv/windows-arm.json b/libs/cua/crates/cua-vmm/tests/argv/windows-arm.json
new file mode 100644
index 0000000000..0357b8bd7f
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/windows-arm.json
@@ -0,0 +1,49 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "virt,memory-backend=mem0",
+ "-cpu",
+ "host",
+ "-accel",
+ "hvf",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "nvme,drive=disk0,serial=cua-disk0,bootindex=1",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-drive",
+ "file=/install.iso,if=none,id=cd0,format=raw,readonly=on,media=cdrom",
+ "-device",
+ "usb-storage,drive=cd0,bus=xhci.0,bootindex=0",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-device",
+ "ramfb",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "none",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
diff --git a/libs/cua/crates/cua-vmm/tests/argv/windows-x86.json b/libs/cua/crates/cua-vmm/tests/argv/windows-x86.json
new file mode 100644
index 0000000000..a14fb84b74
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/argv/windows-x86.json
@@ -0,0 +1,55 @@
+[
+ "-name",
+ "vm1",
+ "-machine",
+ "q35,smm=off,memory-backend=mem0",
+ "-cpu",
+ "host,hv_relaxed,hv_vapic,hv_spinlocks=0x1fff,hv_time,hv_vpindex,hv_synic,hv_stimer",
+ "-accel",
+ "kvm",
+ "-smp",
+ "2",
+ "-m",
+ "2048",
+ "-object",
+ "memory-backend-ram,id=mem0,size=2048M",
+ "-drive",
+ "file=/s/vm1/disk.qcow2,if=none,id=disk0,format=qcow2,cache=writeback,discard=unmap",
+ "-device",
+ "ahci,id=ahci",
+ "-device",
+ "ide-hd,drive=disk0,bus=ahci.0,bootindex=1",
+ "-drive",
+ "file=/s/vm1/seed.iso,if=none,id=cidata,format=raw,readonly=on",
+ "-device",
+ "virtio-blk-pci,drive=cidata",
+ "-cdrom",
+ "/install.iso",
+ "-boot",
+ "d",
+ "-netdev",
+ "user,id=net0,hostfwd=tcp:127.0.0.1:40022-:22,hostfwd=tcp:127.0.0.1:40080-:8080",
+ "-device",
+ "virtio-net-pci,netdev=net0",
+ "-vga",
+ "std",
+ "-device",
+ "qemu-xhci,id=xhci",
+ "-device",
+ "usb-kbd",
+ "-device",
+ "usb-tablet",
+ "-display",
+ "none",
+ "-vnc",
+ "127.0.0.1:3",
+ "-qmp",
+ "tcp:127.0.0.1:4444,server=on,wait=off",
+ "-serial",
+ "file:/s/vm1/serial.log",
+ "-monitor",
+ "none",
+ "-pidfile",
+ "/s/vm1/qemu.pid",
+ "-daemonize"
+]
\ No newline at end of file