Skip to main content

windows_headless/
qemu.rs

1use anyhow::{Context, Result};
2use std::path::PathBuf;
3use std::process::Stdio;
4use tokio::process::{Child, Command};
5
6use crate::qmp::QmpClient;
7use crate::ssh;
8use crate::storage::DiskManager;
9use crate::timeouts;
10use crate::unattend::{Architecture, VmConfig, auto_detect_platform};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum WindowsVersion {
14    Win11,
15}
16
17/// QEMU `-display` backend: the closed set this tool supports. Anything
18/// else QEMU accepts is rejected at the CLI so a typo fails fast instead
19/// of dying deep in QEMU startup.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum Display {
22    None,
23    Cocoa,
24    Gtk,
25    Vnc(String),
26}
27
28impl Display {
29    /// Parse a `--display` value: `none`, `cocoa`, `gtk`, or `vnc=<spec>`.
30    /// Clap `value_parser` shape: `Err(String)` renders as a clean CLI error.
31    pub fn parse(s: &str) -> Result<Self, String> {
32        match s {
33            "none" => Ok(Display::None),
34            "cocoa" => Ok(Display::Cocoa),
35            "gtk" => Ok(Display::Gtk),
36            s if s.starts_with("vnc=") => Ok(Display::Vnc(s.to_string())),
37            _ => Err(format!(
38                "unsupported --display '{s}' (want none|cocoa|gtk|vnc=<spec>)"
39            )),
40        }
41    }
42
43    /// The `-display` argv value.
44    pub fn as_arg(&self) -> String {
45        match self {
46            Display::None => "none".to_string(),
47            Display::Cocoa => "cocoa".to_string(),
48            Display::Gtk => "gtk".to_string(),
49            Display::Vnc(spec) => spec.clone(),
50        }
51    }
52
53    pub fn is_vnc(&self) -> bool {
54        matches!(self, Display::Vnc(_))
55    }
56}
57
58impl std::fmt::Display for Display {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.write_str(&self.as_arg())
61    }
62}
63
64/// Proven topology: the exact QEMU configuration `install`
65/// demonstrated live (SSH banner, zero clicks). `run` boots this same
66/// configuration minus the USB installer stick. Every default below and
67/// every CLI default mirrors these — no parallel hardcodings.
68pub const PROVEN_SSH_PORT: u16 = 2232;
69/// Loopback bind for SSH forwarding and VNC. Single source of truth:
70/// every connect, message, and fallback below references this — never a
71/// literal (the VNC `-display` spec string is the one exception: QEMU
72/// syntax, kept in sync by the `vnc_display_matches_host` test).
73pub const PROVEN_SSH_HOST: &str = "127.0.0.1";
74/// Endpoint locations moved to `ipc` (per-VM-dir, never `/tmp`): file
75/// names are [`crate::ipc::MON_SOCK_NAME`] etc., resolved with
76/// [`crate::ipc::vm_endpoint`].
77// QEMU VNC `host:DISPLAY` takes a display NUMBER, not a TCP port:
78// TCP port = 5900 + display, so :10 listens on 5910 (matches vnc_url()
79// below and every netstat we ever captured).
80pub const PROVEN_VNC_DISPLAY: &str = "vnc=127.0.0.1:10,password=on";
81/// Classic VNC caps passwords at 8 chars.
82pub const PROVEN_VNC_PASSWORD: &str = "demo2026";
83
84/// Guest machine type per arch — one source of truth for install and run.
85///
86/// The machine type is part of the proven topology: OVMF's NVRAM (VARS.fd)
87/// records Boot#### device paths against the PCI layout of the machine it
88/// was written on, and those entries are *not* portable across machine
89/// types. Observed live: a q35-written VARS booted on the default `pc`
90/// (i440fx) hung OVMF before console init — "Guest has not initialized the
91/// display (yet)" forever, zero disk writes, SSH deadline — while the same
92/// disk+VARS booted fine on q35. Install writes VARS on q35, so run must
93/// boot q35. Never let the two argv builders drift apart again.
94pub fn machine_for(arch: Architecture) -> &'static str {
95    match arch {
96        Architecture::Amd64 => "q35",
97        Architecture::Arm64 => "virt",
98    }
99}
100
101/// `vnc=127.0.0.1:10,...` → `vnc://127.0.0.1:5910` (port 5900+N).
102/// Returns None for non-VNC displays. The printed URL always matches
103/// the actual display spec — never a hardcoded port.
104pub fn vnc_url(display: &str) -> Option<String> {
105    let spec = display.strip_prefix("vnc=")?;
106    let addr = spec.split(',').next()?;
107    let (host, disp) = addr.rsplit_once(':')?;
108    let n: u16 = disp.parse().ok()?;
109    let host = if host.is_empty() {
110        PROVEN_SSH_HOST
111    } else {
112        host
113    };
114    Some(format!("vnc://{host}:{}", 5900 + n))
115}
116
117#[derive(Debug, Clone)]
118pub struct HeadlessVmBuilder {
119    pub version: WindowsVersion,
120    pub config: VmConfig,
121    pub disk_size_gb: u32,
122    pub memory_mb: u32,
123    pub smp_cores: u32,
124    pub ssh_host: String,
125    pub ssh_port: u16,
126    /// `-display` backend (`none`, `cocoa`, `gtk`, or `vnc=<spec>`).
127    pub display: Display,
128    pub monitor_socket: String,
129    pub qmp_socket: String,
130    /// Guest serial log path (per-VM, next to the disk — never `/tmp`).
131    /// Re-resolved by [`HeadlessVmBuilder::workdir`]; set explicitly only
132    /// after `workdir()`.
133    pub serial_log: String,
134    pub unattend_dir: PathBuf,
135    pub workdir: PathBuf,
136    /// Portable tree root (the extracted `qemu-portable` dir holding
137    /// `bin/`). `None` = resolve `qemu-system-*` / `qemu-img` via PATH.
138    pub qemu_dir: Option<PathBuf>,
139    /// Resume migrated RAM + device state at boot (`-incoming <uri>`):
140    /// the live-snapshot fast path. `None` = normal boot. Set by the
141    /// caller after verifying the state file — the builder never guesses.
142    pub incoming: Option<String>,
143}
144
145impl HeadlessVmBuilder {
146    pub fn new(version: WindowsVersion) -> Self {
147        let (arch, _) = auto_detect_platform();
148        Self {
149            version,
150            config: VmConfig {
151                arch,
152                ..VmConfig::default()
153            },
154            disk_size_gb: 64,
155            memory_mb: 4096,
156            smp_cores: 4,
157            ssh_host: PROVEN_SSH_HOST.to_string(),
158            ssh_port: PROVEN_SSH_PORT,
159            display: Display::Vnc(PROVEN_VNC_DISPLAY.to_string()),
160            monitor_socket: crate::ipc::vm_endpoint(
161                std::path::Path::new("."),
162                crate::ipc::MON_SOCK_NAME,
163            ),
164            qmp_socket: crate::ipc::vm_endpoint(
165                std::path::Path::new("."),
166                crate::ipc::QMP_SOCK_NAME,
167            ),
168            serial_log: crate::ipc::vm_endpoint(
169                std::path::Path::new("."),
170                crate::ipc::SERIAL_LOG_NAME,
171            ),
172            unattend_dir: PathBuf::from(crate::paths::FALLBACK_UNATTEND_DIR),
173            workdir: PathBuf::from("."),
174            qemu_dir: None,
175            incoming: None,
176        }
177    }
178
179    pub fn disk_size_gb(mut self, gb: u32) -> Self {
180        self.disk_size_gb = gb;
181        self
182    }
183    pub fn memory_mb(mut self, mb: u32) -> Self {
184        self.memory_mb = mb;
185        self
186    }
187    pub fn smp_cores(mut self, n: u32) -> Self {
188        self.smp_cores = n;
189        self
190    }
191    pub fn username(mut self, u: impl Into<String>) -> Self {
192        self.config.username = u.into();
193        self
194    }
195    pub fn password(mut self, p: impl Into<String>) -> Self {
196        self.config.password = p.into();
197        self
198    }
199    pub fn locale(mut self, l: impl Into<String>) -> Self {
200        self.config.locale = l.into();
201        self
202    }
203    pub fn arch(mut self, a: Architecture) -> Self {
204        self.config.arch = a;
205        self
206    }
207    pub fn autologon(mut self, on: bool) -> Self {
208        self.config.auto_logon = on;
209        self
210    }
211    pub fn ssh_port(mut self, p: u16) -> Self {
212        self.ssh_port = p;
213        self
214    }
215    pub fn vnc(mut self, spec: impl Into<String>) -> Self {
216        self.display = Display::Vnc(format!("vnc={}", spec.into()));
217        self
218    }
219    /// Display backend directly.
220    pub fn display(mut self, d: Display) -> Self {
221        self.display = d;
222        self
223    }
224    pub fn monitor_socket(mut self, s: impl Into<String>) -> Self {
225        self.monitor_socket = s.into();
226        self
227    }
228    pub fn qmp_socket(mut self, s: impl Into<String>) -> Self {
229        self.qmp_socket = s.into();
230        self
231    }
232    pub fn unattend_dir(mut self, d: PathBuf) -> Self {
233        self.unattend_dir = d;
234        self
235    }
236    /// Use a portable QEMU tree (see `PortableQemu`); `dir` is the extracted
237    /// `qemu-portable` root containing `bin/`.
238    pub fn qemu_dir(mut self, d: PathBuf) -> Self {
239        self.qemu_dir = Some(d);
240        self
241    }
242    /// Resume migrated state at boot (`commands::migrate_read_uri` output).
243    /// The caller verifies the state file first.
244    pub fn incoming(mut self, uri: impl Into<String>) -> Self {
245        self.incoming = Some(uri.into());
246        self
247    }
248    /// Working dir anchor for per-VM state (defaults to `.`).
249    pub fn workdir(mut self, d: PathBuf) -> Self {
250        // Endpoints follow the VM dir (per-VM sockets, never /tmp):
251        // explicit socket setters apply after workdir(), not before.
252        self.monitor_socket = crate::ipc::vm_endpoint(&d, crate::ipc::MON_SOCK_NAME);
253        self.qmp_socket = crate::ipc::vm_endpoint(&d, crate::ipc::QMP_SOCK_NAME);
254        self.serial_log = crate::ipc::vm_endpoint(&d, crate::ipc::SERIAL_LOG_NAME);
255        self.workdir = d;
256        self
257    }
258
259    fn accel(&self) -> &'static str {
260        auto_detect_platform().1
261    }
262
263    /// CPU model matching the accelerator: `host` passthrough on hardware
264    /// accel (required for Windows 11 setup CPU checks to see something
265    /// modern), `max` under TCG (the `virt` default is too old for Windows
266    /// 11 ARM64, and `-cpu host` needs KVM/HVF to mean anything).
267    fn cpu_model(&self) -> &'static str {
268        if self.accel() == "tcg" { "max" } else { "host" }
269    }
270
271    /// UEFI firmware for this guest arch: read-only CODE plus a writable
272    /// VARS template, both resolved strictly inside the portable tree
273    /// (`<qemu-dir>/share/qemu`). No host paths are probed. Consumed as
274    /// two `pflash` drives (never `-bios`): the Windows bootloader writes
275    /// NVRAM boot variables, and Setup needs them to persist across its
276    /// mid-install reboots.
277    pub fn firmware(&self) -> Option<(PathBuf, PathBuf)> {
278        let (code_names, vars_names) = self.config.arch.firmware_names();
279        let q = self.qemu_dir.as_ref()?;
280        let dir = q.join("share/qemu");
281        let code = code_names
282            .iter()
283            .map(|n| dir.join(n))
284            .find(|p| p.is_file())?;
285        let vars = vars_names
286            .iter()
287            .map(|n| dir.join(n))
288            .find(|p| p.is_file())?;
289        Some((code, vars))
290    }
291
292    /// `<workdir>/VARS.fd`: the guest's private writable NVRAM copy.
293    /// Seeded once from the portable template; never shared between VMs
294    /// (locking collisions) and never written back to the template.
295    pub fn vars_file(&self) -> PathBuf {
296        self.workdir.join(crate::paths::VARS_FILE)
297    }
298
299    /// Copy the firmware VARS template into the private NVRAM file. Must
300    /// run before argv build (the pflash arg names the file).
301    ///
302    /// `refresh == true` (install / ISO-boot flows): always overwrite, so
303    /// OVMF starts with clean NVRAM — a reused VARS carries phantom boot
304    /// entries that shadow `-boot d` and prevent ISO boot
305    /// (`BlInitializeLibrary 0xc00000bb`).
306    ///
307    /// `refresh == false` (steady-state boot): seed only when absent, so
308    /// the firmware state the guest wrote last boot (BootOrder, BootNext,
309    /// policy) survives — this is the proven macOS behavior.
310    fn seed_vars(&self, refresh: bool) -> Result<PathBuf> {
311        let (_, template) = self.firmware().context("missing UEFI firmware")?;
312        let dest = self.vars_file();
313        if let Some(parent) = dest.parent()
314            && !parent.as_os_str().is_empty()
315        {
316            std::fs::create_dir_all(parent)
317                .with_context(|| format!("mkdir {}", parent.display()))?;
318        }
319        if !refresh && dest.exists() {
320            return Ok(dest);
321        }
322        std::fs::copy(&template, &dest).with_context(|| {
323            format!(
324                "copy VARS template {} -> {}",
325                template.display(),
326                dest.display()
327            )
328        })?;
329        Ok(dest)
330    }
331
332    /// Fresh NVRAM for an install or an ISO boot: overwrite every time.
333    pub fn refresh_vars(&self) -> Result<PathBuf> {
334        self.seed_vars(true)
335    }
336
337    /// Steady-state boot: overwrite only when no VARS exists yet, keeping
338    /// the guest's own firmware state across boots.
339    pub fn seed_vars_if_absent(&self) -> Result<PathBuf> {
340        self.seed_vars(false)
341    }
342
343    /// `qemu-system-*` binary: portable tree's when `qemu_dir` is set,
344    /// otherwise PATH lookup by guest arch.
345    pub fn system_bin(&self) -> String {
346        match &self.qemu_dir {
347            Some(d) => d
348                .join(crate::paths::PORTABLE_BIN_DIR)
349                .join(self.config.arch.qemu_binary())
350                .to_string_lossy()
351                .into_owned(),
352            None => self.config.arch.qemu_binary().to_string(),
353        }
354    }
355
356    /// `qemu-img` binary: portable tree's when `qemu_dir` is set, else PATH.
357    pub fn img_bin(&self) -> PathBuf {
358        match &self.qemu_dir {
359            Some(d) => d
360                .join(crate::paths::PORTABLE_BIN_DIR)
361                .join(crate::paths::QEMU_IMG_NAME),
362            None => PathBuf::from(crate::paths::QEMU_IMG_NAME),
363        }
364    }
365
366    /// User-mode NIC with host-forwarded SSH. `romfile=` (empty) drops
367    /// the NIC's PXE option ROM: QEMU ships it as an X64-only iPXE build,
368    /// which ARM64 EDK2 loudly refuses ("Image type X64 can't be loaded")
369    /// on every boot. We never PXE-boot.
370    fn net_args(&self) -> Vec<String> {
371        vec![
372            "-netdev".into(),
373            format!("user,id=n1,hostfwd=tcp::{}-:22", self.ssh_port),
374            "-device".into(),
375            "virtio-net-pci,netdev=n1,romfile=".into(),
376        ]
377    }
378
379    /// Answer-file drive args. WinPE reads `autounattend.xml` before the
380    /// VirtIO drivers in `<DriverPaths>` load, so the bus must have inbox
381    /// drivers — never `if=virtio`:
382    /// - x86_64 (`pc`): `-drive ...if=ide` (inbox ATA).
383    /// - ARM64 (`virt` has no IDE bus): USB mass storage on the shared
384    ///   xHCI bus (inbox USBSTOR — the classic answer-file-on-a-stick flow).
385    ///
386    /// An explicit `--unattend-iso` replaces either with a second CD-ROM.
387    /// (The xHCI bus itself is added by `install_argv`, which also owns the
388    /// USB keyboard — kept together so neither dangles bus-less.)
389    fn answer_drive_args(&self, unattend_iso: Option<&str>) -> Vec<String> {
390        if let Some(iso) = unattend_iso {
391            return vec![
392                "-drive".into(),
393                format!("file={iso},media=cdrom,readonly=on"),
394            ];
395        }
396        match self.config.arch {
397            Architecture::Amd64 => vec![
398                "-drive".into(),
399                format!(
400                    "file=fat:ro:{},format=raw,if=ide",
401                    self.unattend_dir.display()
402                ),
403            ],
404            Architecture::Arm64 => vec![
405                "-drive".into(),
406                format!(
407                    "file=fat:ro:{},format=raw,if=none,id=unattend-drive,readonly=on",
408                    self.unattend_dir.display()
409                ),
410                "-device".into(),
411                "usb-storage,drive=unattend-drive".into(),
412            ],
413        }
414    }
415    /// QEMU argv for the install phase (ISOs + answer drive attached).
416    pub fn install_argv(
417        &self,
418        disk: &str,
419        win_iso: &str,
420        virtio_iso: &str,
421        unattend_iso: Option<&str>,
422    ) -> Vec<String> {
423        let mut a = vec![
424            self.system_bin(),
425            "-accel".into(),
426            self.accel().into(),
427            "-m".into(),
428            self.memory_mb.to_string(),
429            "-cpu".into(),
430            self.cpu_model().into(),
431        ];
432        // Explicit machine on every arch (machine_for): the topology must
433        // be the one NVRAM was written on — see `machine_for`.
434        a.push("-M".into());
435        a.push(machine_for(self.config.arch).into());
436        a.push("-smp".into());
437        a.push(self.smp_cores.to_string());
438        // UEFI firmware as two pflash drives: read-only CODE + the VM's
439        // private writable VARS (seeded before argv build — `refresh_vars`
440        // for install/ISO boots, `seed_vars_if_absent` for plain boots).
441        // Never `-bios`: the Windows bootloader writes NVRAM boot
442        // variables and Setup needs them to persist across its reboots.
443        if let Some((fw_code, _)) = self.firmware() {
444            a.push("-drive".into());
445            a.push(format!(
446                "if=pflash,format=raw,readonly=on,file={}",
447                fw_code.display()
448            ));
449            a.push("-drive".into());
450            a.push(format!(
451                "if=pflash,format=raw,file={}",
452                self.vars_file().display()
453            ));
454        }
455        // Target disk on the SAME NVMe controller + serial boot_argv uses
456        // (inbox stornvme; part.txt/InstallTo pick Disk 0 — see the
457        // template header): identical bus topology across install and
458        // first boot means no controller change, no NIC slot shift, no
459        // minutes-long PnP re-enumeration. Never `if=virtio` here — the
460        // answer file loads no storage driver.
461        //
462        // Deliberately NO bootindex on the install NVMe (unlike
463        // boot_argv): any bootindex makes OVMF build its boot list
464        // exclusively from the fw_cfg bootorder file, and unindexed
465        // devices (the installer CD) get no boot option at all —
466        // observed live: setup drops to the UEFI shell instead of
467        // booting the ISO. Without one, OVMF enumerates every device
468        // and falls through to the installer (today's proven path, with
469        // -boot order=d below unchanged).
470        a.push("-drive".into());
471        a.push(format!("file={disk},format=qcow2,if=none,id=tgt"));
472        a.push("-device".into());
473        a.push("nvme,drive=tgt,serial=nvme1".into());
474        a.push("-drive".into());
475        a.push(format!("file={win_iso},media=cdrom,readonly=on"));
476        a.push("-drive".into());
477        a.push(format!("file={virtio_iso},media=cdrom,readonly=on"));
478        // Boot the installer CD first (the qcow2 target is empty).
479        // x86/SeaBIOS only: on ARM64 an explicit order makes EDK2 use ONLY
480        // the fw_cfg entries with no removable-media fallback, which drops
481        // to the UEFI shell; without it EDK2 boots the CD by default.
482        if self.config.arch == Architecture::Amd64 {
483            a.push("-boot".into());
484            a.push("order=d".into());
485        }
486        // ARM64 `virt` ships with NO input/display devices of its own:
487        // xHCI + USB keyboard (send-key needs it) + USB tablet (VNC
488        // pointer needs it), and ramfb as the one framebuffer (single
489        // console: VNC and screendump keep working after Windows takes
490        // over, unlike virtio-gpu). x86/pc has PS/2 + VGA by default.
491        if self.config.arch == Architecture::Arm64 {
492            a.push("-device".into());
493            a.push("qemu-xhci,id=xhci".into());
494            a.push("-device".into());
495            a.push("usb-kbd".into());
496            a.push("-device".into());
497            a.push("usb-tablet".into());
498            a.push("-device".into());
499            a.push("ramfb".into());
500        }
501        a.extend(self.answer_drive_args(unattend_iso));
502        // Guest serial log (EDK2 shouts here on `virt`): the only record
503        // when the framebuffer is dark. Same path as the proven install.
504        a.push("-serial".into());
505        a.push(format!("file:{}", self.serial_log));
506        a.extend(self.net_args());
507        a.push("-display".into());
508        a.push(self.display.as_arg());
509        a.push("-monitor".into());
510        a.push(crate::ipc::qemu_arg(&self.monitor_socket));
511        a.push("-qmp".into());
512        a.push(crate::ipc::qemu_arg(&self.qmp_socket));
513        a
514    }
515
516    /// QEMU argv for ephemeral boots (no install media, no vvfat).
517    pub fn boot_argv(&self, disk: &str) -> Vec<String> {
518        let mut a = vec![
519            self.system_bin(),
520            "-accel".into(),
521            self.accel().into(),
522            "-m".into(),
523            self.memory_mb.to_string(),
524            "-cpu".into(),
525            self.cpu_model().into(),
526        ];
527        // Explicit machine on every arch (machine_for): run must boot the
528        // exact topology install wrote NVRAM on — see `machine_for`.
529        a.push("-M".into());
530        a.push(machine_for(self.config.arch).into());
531        a.push("-smp".into());
532        a.push(self.smp_cores.to_string());
533        // Live resume: migrated state streams in over `-incoming`, so the
534        // guest continues where the save left it instead of booting. Disk
535        // and VARS are restored to the save instant by the caller — argv
536        // only carries the RAM side. Guest clock isolated from the host
537        // (`clock=vm`): with `clock=host` the RTC can wait out its whole
538        // next period after a restore and lose ticks forever (documented
539        // migration pathology); vm-clock tracking restarts cleanly.
540        if let Some(uri) = &self.incoming {
541            a.push("-incoming".into());
542            a.push(uri.clone());
543            a.push("-rtc".into());
544            a.push("base=utc,clock=vm".into());
545        }
546        if let Some((fw_code, _)) = self.firmware() {
547            a.push("-drive".into());
548            a.push(format!(
549                "if=pflash,format=raw,readonly=on,file={}",
550                fw_code.display()
551            ));
552            a.push("-drive".into());
553            a.push(format!(
554                "if=pflash,format=raw,file={}",
555                self.vars_file().display()
556            ));
557        }
558        // Ephemeral boots need input + display too (else blind post-install).
559        // (xHCI first: the USB input devices have no bus without it.)
560        if self.config.arch == Architecture::Arm64 {
561            a.push("-device".into());
562            a.push("qemu-xhci,id=xhci".into());
563            a.push("-device".into());
564            a.push("usb-kbd".into());
565            a.push("-device".into());
566            a.push("usb-tablet".into());
567            a.push("-device".into());
568            a.push("ramfb".into());
569        }
570        // The installed system lives on NVMe (the proven install topology):
571        // boot it on the identical controller + serial so Windows sees the
572        // same device it was installed on — not a controller change plus a
573        // minutes-long PnP re-enumeration. stornvme is inbox, so this also
574        // boots disks from the legacy virtio install flow.
575        a.push("-drive".into());
576        a.push(format!("file={disk},format=qcow2,if=none,id=tgt"));
577        a.push("-device".into());
578        a.push("nvme,drive=tgt,serial=nvme1,bootindex=0".into());
579        a.extend(self.net_args());
580        a.push("-display".into());
581        a.push(self.display.as_arg());
582        a.push("-serial".into());
583        a.push(format!("file:{}", self.serial_log));
584        a.push("-monitor".into());
585        a.push(crate::ipc::qemu_arg(&self.monitor_socket));
586        a.push("-qmp".into());
587        a.push(crate::ipc::qemu_arg(&self.qmp_socket));
588        a
589    }
590
591    /// Fail fast unless a portable QEMU tree with UEFI firmware is wired
592    /// up (`--qemu-dir`, i.e. `fetch-qemu` output). Portable-only by
593    /// design: no host firmware paths are probed. Both CODE and the VARS
594    /// template must be present (pflash pair; `-bios` is not used).
595    fn require_firmware(&self) -> Result<()> {
596        if self.qemu_dir.is_none() {
597            anyhow::bail!(
598                "portable QEMU is required: pass --qemu-dir <fetch-qemu tree> (run `fetch-qemu` first)"
599            );
600        }
601        if self.firmware().is_none() {
602            anyhow::bail!(
603                "portable tree lacks UEFI firmware (CODE + VARS under share/qemu); re-run `fetch-qemu`"
604            );
605        }
606        Ok(())
607    }
608
609    async fn spawn(argv: &[String]) -> Result<Child> {
610        let (bin, args) = argv.split_first().context("empty argv")?;
611        // Never orphan: if the owner drops this handle (CLI exit, panic,
612        // task cancel), the guest dies with it. There is no detach path.
613        let mut cmd = Command::new(bin);
614        cmd.args(args).stdin(Stdio::null()).kill_on_drop(true);
615        // Own process group (Unix): a tty Ctrl-C broadcasts SIGINT to the
616        // whole foreground group. Without this, QEMU dies by signal on
617        // every Ctrl-C — bypassing graceful shutdown and risking dirty
618        // NTFS (observed live: "terminating on signal 2", then QMP gone).
619        // Only the CLI receives the keystroke; the guest exits via ACPI.
620        #[cfg(unix)]
621        {
622            cmd.process_group(0);
623        }
624        // Same isolation on Windows: console Ctrl-C reaches every process
625        // attached to the console. CREATE_NEW_PROCESS_GROUP detaches QEMU
626        // (Ctrl-Break still would, which nobody sends by accident).
627        #[cfg(windows)]
628        {
629            /// Win32 `CREATE_NEW_PROCESS_GROUP` (no winapi dep for one flag;
630            /// tokio's `Command` carries `creation_flags` itself).
631            const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
632            cmd.creation_flags(CREATE_NEW_PROCESS_GROUP);
633        }
634        cmd.spawn().with_context(|| format!("spawn {bin}"))
635    }
636
637    /// Give QEMU a few seconds to reject bad argv, then fail fast instead
638    /// of polling SSH for 15 minutes against a dead process. A healthy
639    /// boot is still starting at this point, so a live child means success.
640    async fn spawn_guarded(argv: &[String]) -> Result<Child> {
641        let mut child = Self::spawn(argv).await?;
642        eprintln!(
643            "QEMU spawned (pid {:?}); waiting {} s ...",
644            child.id(),
645            timeouts::SPAWN_GUARD.as_secs()
646        );
647        tokio::time::sleep(timeouts::SPAWN_GUARD).await;
648        match child.try_wait().context("poll qemu process")? {
649            Some(status) => anyhow::bail!(
650                "QEMU (pid {:?}) exited immediately (status {status}); check its stderr above for the rejected flag",
651                child.id(),
652            ),
653            None => Ok(child),
654        }
655    }
656
657    /// `<workdir>/qemu.pid` — written on launch, removed by `stop`.
658    /// Lets the CLI refuse double-starts and shut down cleanly instead of
659    /// orphaning QEMU when the operator's shell exits.
660    pub fn pidfile(&self) -> std::path::PathBuf {
661        self.workdir.join(crate::paths::QEMU_PIDFILE)
662    }
663
664    fn write_pidfile(&self, child: &Child) -> Result<()> {
665        if let Some(id) = child.id() {
666            std::fs::write(self.pidfile(), id.to_string())
667                .with_context(|| format!("write {}", self.pidfile().display()))?;
668        }
669        Ok(())
670    }
671
672    /// Remove stale monitor/QMP socket files left by a previous run.
673    /// Only unlinks when nothing is listening (live VM → keep, caller
674    /// preflights that case separately). Without this QEMU's bind fails
675    /// on the leftover file even though no process holds the port.
676    async fn clear_stale_sockets(&self) {
677        for sock in [&self.monitor_socket, &self.qmp_socket] {
678            // Never unlink a live endpoint (a running VM's socket): only
679            // stale files go. Named pipes aren't fs entries (no-op there).
680            if !crate::ipc::endpoint_alive(sock).await {
681                crate::ipc::stale_remove(sock);
682            }
683        }
684    }
685
686    /// Full install flow: render XML → stage vvfat → refresh VARS → create
687    /// base → launch. Uses the portable `qemu-img` when `qemu_dir` is set.
688    pub async fn build_and_start(
689        self,
690        disk: &str,
691        win_iso: &str,
692        virtio_iso: &str,
693    ) -> Result<HeadlessVm> {
694        self.require_firmware()?;
695        let xml = self.config.generate_unattend_xml();
696        DiskManager::ensure_unattend_dir(&self.unattend_dir, &xml)?;
697        // Clean NVRAM: stale boot entries would shadow `-boot d`.
698        self.refresh_vars()?;
699        DiskManager::create_base(
700            &self.img_bin(),
701            std::path::Path::new(disk),
702            self.disk_size_gb,
703        )
704        .await?;
705        self.clear_stale_sockets().await;
706        let argv = self.install_argv(disk, win_iso, virtio_iso, None);
707        let child = Self::spawn_guarded(&argv).await?;
708        self.write_pidfile(&child)?;
709        Ok(HeadlessVm {
710            builder: self,
711            child,
712            disk: disk.to_string(),
713        })
714    }
715
716    /// Boot an existing (overlay) disk without install media.
717    pub async fn boot_existing(self, disk: &str) -> Result<HeadlessVm> {
718        self.require_firmware()?;
719        // Keep the guest's NVRAM across boots (seed only when absent):
720        // nothing here shadows a boot device, and the guest's own
721        // BootOrder/BootNext must survive (proven macOS behavior).
722        self.seed_vars_if_absent()?;
723        self.clear_stale_sockets().await;
724        let argv = self.boot_argv(disk);
725        let mut child = Self::spawn_guarded(&argv).await?;
726        // Same slow-start race as the install path (hvf startup >3 s): poll
727        // for the monitor socket FILE (bind = starting), bail only on death
728        // or timeout — never on a live child, or kill_on_drop destroys the
729        // evidence. Deliberately no connect-probe here: QEMU's listen
730        // backlog is a single slot and a probe occupies it, refusing the
731        // real VNC handshake that follows (observed ECONNREFUSED on live
732        // QEMU). The handshake itself retries (see install path).
733        // Total wait = the declared budget, split into polls of
734        // MONITOR_SOCKET_POLL_SECS (so changing either const keeps the
735        // message and the loop in agreement).
736        let polls = timeouts::MONITOR_SOCKET_WAIT_SECS / timeouts::MONITOR_SOCKET_POLL_SECS.max(1);
737        for _ in 0..polls {
738            if std::path::Path::new(&self.monitor_socket).exists() {
739                break;
740            }
741            if let Some(status) = child.try_wait().context("poll qemu process")? {
742                anyhow::bail!(
743                    "QEMU (pid {:?}) exited during startup (status {status}); check its stderr above for the rejected flag",
744                    child.id(),
745                );
746            }
747            tokio::time::sleep(std::time::Duration::from_secs(
748                timeouts::MONITOR_SOCKET_POLL_SECS,
749            ))
750            .await;
751        }
752        if !std::path::Path::new(&self.monitor_socket).exists() {
753            let _ = child.kill().await;
754            anyhow::bail!(
755                "QEMU (pid {:?}) alive but no monitor socket at {} after {} s; killed it",
756                child.id(),
757                self.monitor_socket,
758                timeouts::MONITOR_SOCKET_WAIT_SECS
759            );
760        }
761        self.write_pidfile(&child)?;
762        Ok(HeadlessVm {
763            builder: self,
764            child,
765            disk: disk.to_string(),
766        })
767    }
768}
769
770/// Re-exported transport check (lives in `ipc`; kept here so existing
771/// `qemu::qmp_alive` import paths don't churn).
772pub use crate::ipc::qmp_alive;
773
774pub struct HeadlessVm {
775    pub builder: HeadlessVmBuilder,
776    pub child: Child,
777    pub disk: String,
778}
779
780impl HeadlessVm {
781    pub async fn wait_for_ssh(&self, timeout: std::time::Duration) -> Result<()> {
782        ssh::wait_for_ssh(&self.builder.ssh_host, self.builder.ssh_port, timeout).await
783    }
784
785    pub async fn qmp(&self) -> Result<QmpClient> {
786        QmpClient::connect(&self.builder.qmp_socket).await
787    }
788
789    pub async fn snapshot_live(&self, overlay: &str) -> Result<()> {
790        let mut q = self.qmp().await?;
791        q.live_overlay("drive0", overlay).await
792    }
793
794    /// Tap guest keys via QMP (e.g. `&["ret"]` for the ISO boot prompt).
795    pub async fn send_keys(&self, keys: &[&str]) -> Result<()> {
796        let mut q = self.qmp().await?;
797        q.send_keys(keys).await
798    }
799
800    /// Graceful shutdown over SSH (`Stop-Computer -Force`), required before
801    /// offline `create_overlay` to avoid a dirty-NTFS `chkdsk` on next boot.
802    pub async fn shutdown_cleanly(&self) -> Result<()> {
803        let status = Command::new("ssh")
804            .arg("-o")
805            .arg("StrictHostKeyChecking=no")
806            .arg("-p")
807            .arg(self.builder.ssh_port.to_string())
808            .arg(format!(
809                "{}@{}",
810                self.builder.config.username, self.builder.ssh_host
811            ))
812            .arg("powershell.exe -NoProfile -Command \"Stop-Computer -Force\"")
813            .status()
814            .await
815            .context("ssh shutdown")?;
816        if !status.success() {
817            anyhow::bail!("remote shutdown command failed");
818        }
819        Ok(())
820    }
821
822    /// Graceful teardown for the supervisor path: ACPI powerdown (clean
823    /// Windows shutdown, no dirty NTFS bit), wait up to `timeout` for the
824    /// process to exit, SIGKILL fallback with a warning. Dropping the VM
825    /// without this still kills QEMU via `kill_on_drop` — just dirtier.
826    pub async fn shutdown_graceful(&mut self, timeout: std::time::Duration) -> Result<()> {
827        // Powerdown errors are LOUD, never swallowed: a guest that never
828        // got the message makes the whole timeout expire feeling hung
829        // (observed live). Failure here still falls through to the wait
830        // (the guest may already be exiting) but the log says so.
831        match self.qmp().await {
832            Ok(mut q) => match q.powerdown().await {
833                Ok(_) => eprintln!("ACPI powerdown sent; waiting for guest exit ..."),
834                Err(e) => eprintln!("warning: powerdown send failed ({e:#}); waiting anyway ..."),
835            },
836            Err(e) => eprintln!("warning: no QMP for powerdown ({e:#}); waiting anyway ..."),
837        }
838        match tokio::time::timeout(timeout, self.child.wait()).await {
839            Ok(_) => Ok(()),
840            Err(_) => {
841                tracing::warn!("guest did not exit in time; SIGKILL (next boot may chkdsk)");
842                self.child.kill().await.context("kill qemu")?;
843                let _ = self.child.wait().await;
844                Ok(())
845            }
846        }
847    }
848
849    pub async fn kill(mut self) -> Result<()> {
850        self.child.kill().await.context("kill qemu")?;
851        let _ = self.child.wait().await;
852        Ok(())
853    }
854}
855
856#[cfg(test)]
857mod tests {
858    use super::*;
859
860    #[test]
861    fn builder_sizing_reaches_boot_argv() {
862        // Same flags-through-argv proof for the boot path: what the
863        // builder holds is what QEMU gets, no VM needed.
864        let b = HeadlessVmBuilder::new(WindowsVersion::Win11)
865            .memory_mb(8192)
866            .smp_cores(8);
867        let argv = b.boot_argv("d.qcow2");
868        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
869        assert_eq!(at("-m"), "8192");
870        assert_eq!(at("-smp"), "8");
871    }
872
873    #[test]
874    fn builder_incoming_reaches_boot_argv() {
875        // Live resume: -incoming streams the migrated state file, no boot.
876        let b = HeadlessVmBuilder::new(WindowsVersion::Win11).incoming("exec:cat '/tmp/state'");
877        let argv = b.boot_argv("d.qcow2");
878        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
879        assert_eq!(at("-incoming"), "exec:cat '/tmp/state'");
880        // Restore carries isolated guest time (documented RTC-stop
881        // workaround); plain boots set no -rtc.
882        assert_eq!(at("-rtc"), "base=utc,clock=vm");
883        // Default boot carries no -incoming.
884        let plain = HeadlessVmBuilder::new(WindowsVersion::Win11).boot_argv("d.qcow2");
885        assert!(!plain.iter().any(|a| a == "-incoming"));
886        assert!(!plain.iter().any(|a| a == "-rtc"));
887    }
888
889    #[test]
890    fn display_parse_rejects_typos() {
891        assert_eq!(Display::parse("cocoa").unwrap(), Display::Cocoa);
892        assert_eq!(Display::parse("none").unwrap(), Display::None);
893        assert_eq!(
894            Display::parse("vnc=127.0.0.1:10,password=on")
895                .unwrap()
896                .as_arg(),
897            "vnc=127.0.0.1:10,password=on"
898        );
899        assert!(Display::parse("x11").is_err());
900        assert!(Display::parse("vnc").is_err());
901        assert!(!Display::Cocoa.is_vnc());
902        assert!(Display::parse("vnc=127.0.0.1:0").unwrap().is_vnc());
903    }
904
905    #[test]
906    fn vnc_display_matches_host() {
907        // PROVEN_VNC_DISPLAY is QEMU syntax (can't concat! a const into
908        // it), so this test keeps its bind address glued to PROVEN_SSH_HOST.
909        let spec = PROVEN_VNC_DISPLAY.strip_prefix("vnc=").unwrap();
910        let addr = spec.split(',').next().unwrap();
911        let (host, _) = addr.rsplit_once(':').unwrap();
912        assert_eq!(host, PROVEN_SSH_HOST);
913    }
914
915    #[test]
916    fn vvfat_never_virtio() {
917        // x86_64/pc: inbox IDE.
918        let x86 = HeadlessVmBuilder::new(WindowsVersion::Win11).arch(Architecture::Amd64);
919        let argv = x86.install_argv("d.qcow2", "w.iso", "v.iso", None);
920        let vvfat = argv.iter().find(|a| a.starts_with("file=fat:")).unwrap();
921        assert!(
922            vvfat.contains("if=ide"),
923            "vvfat must be if=ide, got {vvfat}"
924        );
925        // ARM64/virt has no IDE bus: USB mass storage (inbox USBSTOR).
926        let arm = HeadlessVmBuilder::new(WindowsVersion::Win11).arch(Architecture::Arm64);
927        let argv = arm.install_argv("d.qcow2", "w.iso", "v.iso", None);
928        let vvfat = argv.iter().find(|a| a.starts_with("file=fat:")).unwrap();
929        assert!(vvfat.contains("if=none"), "got {vvfat}");
930        assert!(argv.iter().any(|a| a == "qemu-xhci,id=xhci"));
931        assert!(argv.iter().any(|a| a == "usb-storage,drive=unattend-drive"));
932        // ARM64/virt has no keyboard either: send-key needs usb-kbd or the
933        // taps are accepted by QMP but never reach the guest.
934        assert!(argv.iter().any(|a| a == "usb-kbd"));
935        assert!(argv.iter().any(|a| a == "usb-tablet"));
936        // ...and the keyboard bus must exist even with --unattend-iso.
937        let argv_iso = arm.install_argv("d.qcow2", "w.iso", "v.iso", Some("u.iso"));
938        assert!(argv_iso.iter().any(|a| a == "qemu-xhci,id=xhci"));
939        assert!(argv_iso.iter().any(|a| a == "usb-kbd"));
940        // ARM needs a real framebuffer (ramfb: single console, observable
941        // under Windows) and input devices for VNC/send-key.
942        assert!(argv.iter().any(|a| a == "ramfb"));
943        assert!(!argv.iter().any(|a| a == "virtio-gpu-pci"));
944        assert!(arm.boot_argv("d.qcow2").iter().any(|a| a == "ramfb"));
945        // Guest serial log for dark-framebuffer forensics, install + boot.
946        assert!(argv.iter().any(|a| a.ends_with("serial.log")));
947        assert!(
948            arm.boot_argv("d.qcow2")
949                .iter()
950                .any(|a| a.ends_with("serial.log"))
951        );
952        for argv in [x86.install_argv("d.qcow2", "w.iso", "v.iso", None), argv] {
953            assert!(
954                !argv
955                    .iter()
956                    .any(|a| a.contains("if=virtio") && a.starts_with("file=fat:"))
957            );
958            // Install target: NVMe (same controller as boot_argv, never
959            // virtio-blk) but WITHOUT bootindex — any bootindex starves
960            // the unindexed installer CD of a boot option in OVMF
961            // (observed: setup drops to the UEFI shell instead).
962            let os = argv.iter().find(|a| a.contains(".qcow2")).unwrap();
963            assert!(os.contains("if=none,id=tgt"), "got {os}");
964            assert!(argv.iter().any(|a| a == "nvme,drive=tgt,serial=nvme1"));
965            assert!(!argv.iter().any(|a| a.contains("bootindex")));
966        }
967    }
968
969    #[test]
970    fn install_and_boot_share_the_nvme_controller() {
971        // One controller identity across install and first boot: same
972        // device string (bus topology + serial), differing only by
973        // boot_argv's bootindex (firmware boot priority only — invisible
974        // to Windows PnP, so it never perturbs device enumeration).
975        let b = HeadlessVmBuilder::new(WindowsVersion::Win11);
976        let install = b.install_argv("d.qcow2", "w.iso", "v.iso", None);
977        let boot = b.boot_argv("d.qcow2");
978        let dev = |argv: &[String]| {
979            argv.iter()
980                .find(|a| a.starts_with("nvme,drive=tgt"))
981                .expect("NVMe target device present")
982                .clone()
983        };
984        assert_eq!(dev(&install), "nvme,drive=tgt,serial=nvme1");
985        assert_eq!(dev(&boot), "nvme,drive=tgt,serial=nvme1,bootindex=0");
986    }
987
988    #[test]
989    fn unattend_iso_replaces_vvfat() {
990        let b = HeadlessVmBuilder::new(WindowsVersion::Win11);
991        let argv = b.install_argv("d.qcow2", "w.iso", "v.iso", Some("u.iso"));
992        assert!(
993            argv.iter()
994                .any(|a| a.contains("u.iso") && a.contains("media=cdrom"))
995        );
996        assert!(!argv.iter().any(|a| a.starts_with("file=fat:")));
997    }
998
999    #[test]
1000    fn ephemeral_boot_has_no_install_media() {
1001        let b = HeadlessVmBuilder::new(WindowsVersion::Win11);
1002        let argv = b.boot_argv("overlay.qcow2");
1003        assert!(!argv.iter().any(|a| a.starts_with("file=fat:")));
1004        assert!(!argv.iter().any(|a| a.contains("media=cdrom")));
1005        // Installed on NVMe, booted on NVMe: same controller + serial as
1006        // the proven install, never a virtio-blk surprise.
1007        assert!(
1008            argv.iter()
1009                .any(|a| a == "nvme,drive=tgt,serial=nvme1,bootindex=0")
1010        );
1011        assert!(
1012            !argv
1013                .iter()
1014                .any(|a| a.contains(".qcow2") && a.contains("if=virtio"))
1015        );
1016    }
1017
1018    #[test]
1019    fn portable_dir_overrides_path_lookup() {
1020        let b = HeadlessVmBuilder::new(WindowsVersion::Win11);
1021        assert_eq!(b.system_bin(), b.config.arch.qemu_binary());
1022        assert_eq!(b.img_bin(), PathBuf::from("qemu-img"));
1023
1024        let p = b.qemu_dir(PathBuf::from("/cache/qemu-portable/11.1.1/qemu-portable"));
1025        let sys = p.system_bin();
1026        assert!(
1027            sys.starts_with("/cache/qemu-portable/11.1.1/qemu-portable/bin/qemu-system-"),
1028            "got {sys}"
1029        );
1030        assert_eq!(
1031            p.img_bin(),
1032            PathBuf::from("/cache/qemu-portable/11.1.1/qemu-portable/bin/qemu-img")
1033        );
1034        // argv[0] is the resolved binary.
1035        assert_eq!(p.install_argv("d.qcow2", "w.iso", "v.iso", None)[0], sys);
1036    }
1037
1038    #[test]
1039    fn machine_type_is_pinned_on_both_arches() {
1040        // Shared NIC shape (incl. romfile= PXE-ROM suppression) on both.
1041        for b in [
1042            HeadlessVmBuilder::new(WindowsVersion::Win11),
1043            HeadlessVmBuilder::new(WindowsVersion::Win11).arch(Architecture::Arm64),
1044        ] {
1045            let argv = b.install_argv("d.qcow2", "w.iso", "v.iso", None);
1046            assert!(
1047                argv.iter()
1048                    .any(|a| a == "virtio-net-pci,netdev=n1,romfile=")
1049            );
1050        } // qemu-system-aarch64 has no default machine: -M virt is required.
1051        let arm = HeadlessVmBuilder::new(WindowsVersion::Win11).arch(Architecture::Arm64);
1052        for argv in [
1053            arm.install_argv("d.qcow2", "w.iso", "v.iso", None),
1054            arm.boot_argv("d.qcow2"),
1055        ] {
1056            let pos = argv.iter().position(|a| a == "-M").expect("-M present");
1057            assert_eq!(argv[pos + 1], "virt");
1058        }
1059        // x86 pins q35 — the exact topology install wrote NVRAM on
1060        // (default `pc` + q35-written VARS hangs OVMF, machine_for).
1061        let x86 = HeadlessVmBuilder::new(WindowsVersion::Win11).arch(Architecture::Amd64);
1062        for argv in [
1063            x86.install_argv("d.qcow2", "w.iso", "v.iso", None),
1064            x86.boot_argv("d.qcow2"),
1065        ] {
1066            let pos = argv.iter().position(|a| a == "-M").expect("-M present");
1067            assert_eq!(argv[pos + 1], "q35");
1068        }
1069    }
1070
1071    #[test]
1072    fn firmware_is_portable_tree_only() {
1073        // No --qemu-dir: no firmware, never host paths.
1074        let b = HeadlessVmBuilder::new(WindowsVersion::Win11);
1075        assert_eq!(b.qemu_dir, None);
1076        assert!(b.firmware().is_none());
1077        assert!(b.require_firmware().is_err());
1078
1079        // Portable tree with CODE + VARS: resolves both inside the tree.
1080        let tmp = tempfile::tempdir().unwrap();
1081        let fw_dir = tmp.path().join("qemu-portable/share/qemu");
1082        std::fs::create_dir_all(&fw_dir).unwrap();
1083        std::fs::write(fw_dir.join("edk2-aarch64-code.fd"), b"fake-code").unwrap();
1084        std::fs::write(fw_dir.join("edk2-arm-vars.fd"), b"fake-vars").unwrap();
1085        let p = HeadlessVmBuilder::new(WindowsVersion::Win11)
1086            .arch(Architecture::Arm64)
1087            .qemu_dir(tmp.path().join("qemu-portable"))
1088            .workdir(tmp.path().join("vm"));
1089        let (code, vars) = p.firmware().unwrap();
1090        assert_eq!(code, fw_dir.join("edk2-aarch64-code.fd"));
1091        assert_eq!(vars, fw_dir.join("edk2-arm-vars.fd"));
1092        assert!(p.require_firmware().is_ok());
1093
1094        // VARS seeding: steady-state keeps guest NVRAM, install refreshes.
1095        let seeded = p.seed_vars_if_absent().unwrap();
1096        assert_eq!(seeded, tmp.path().join("vm/VARS.fd"));
1097        assert_eq!(std::fs::read(&seeded).unwrap(), b"fake-vars");
1098        std::fs::write(&seeded, b"guest-modified").unwrap();
1099        // Seed-once: a second call leaves the guest's firmware state alone.
1100        assert_eq!(p.seed_vars_if_absent().unwrap(), seeded);
1101        assert_eq!(std::fs::read(&seeded).unwrap(), b"guest-modified");
1102        // Install / ISO boot: fresh template every time (stale boot entries
1103        // would shadow `-boot d`).
1104        assert_eq!(p.refresh_vars().unwrap(), seeded);
1105        assert_eq!(std::fs::read(&seeded).unwrap(), b"fake-vars");
1106
1107        // pflash pair in argv, no -bios anywhere.
1108        let argv = p.install_argv("d.qcow2", "w.iso", "v.iso", None);
1109        assert!(!argv.iter().any(|a| a == "-bios"));
1110        let pf: Vec<_> = argv.iter().filter(|a| a.starts_with("if=pflash")).collect();
1111        assert_eq!(pf.len(), 2);
1112        assert!(pf[0].contains("readonly=on"));
1113        assert!(pf[0].contains("edk2-aarch64-code.fd"));
1114        assert!(pf[1].contains("vm/VARS.fd"));
1115        assert!(!pf[1].contains("readonly"));
1116    }
1117}