Skip to main content

openvmm_entry/
cli_args.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! CLI argument parsing.
5//!
6//! Code in this module must not instantiate any complex VM objects!
7//!
8//! In other words, this module is only responsible for marshalling raw CLI
9//! strings into typed Rust structs/enums, and should consist of entirely _pure
10//! functions_.
11//!
12//! e.g: instead of opening a `File` directly, parse the specified file path
13//! into a `PathBuf`, and allow later parts of the init flow to handle opening
14//! the file.
15
16// NOTE: This module itself is not pub, but the Options struct below is
17//       re-exported as pub in main to make this lint fire. It won't fire on
18//       anything else on this file though.
19#![warn(missing_docs)]
20
21use crate::usb::UsbBackend;
22use anyhow::Context;
23use clap::Parser;
24use clap::ValueEnum;
25use cxl_spec::CfmwsWindowRestrictions;
26use guid::Guid;
27use net_backend_resources::mac_address::MacAddress;
28use openvmm_defs::config::DEFAULT_PCAT_BOOT_ORDER;
29use openvmm_defs::config::DeviceVtl;
30use openvmm_defs::config::PcatBootDevice;
31use openvmm_defs::config::Vtl2BaseAddressType;
32use openvmm_defs::config::X2ApicConfig;
33use std::ffi::OsString;
34use std::net::SocketAddr;
35use std::path::PathBuf;
36use std::str::FromStr;
37use thiserror::Error;
38
39/// Parse CLI options, using a thread with a larger stack on Windows to avoid
40/// stack overflow in debug builds due to clap's deep stack usage.
41/// See <https://github.com/clap-rs/clap/issues/5134>.
42pub(crate) fn parse_options() -> Options {
43    // In non-optimized builds, clap uses an embarrassing amount of stack space
44    // to construct the `Command` instance for `Options`, more than the Windows
45    // default of 1MB. This has been known since 2023:
46    // <https://github.com/clap-rs/clap/issues/5134>, but no one has stepped up
47    // to fix it.
48    //
49    // Work around this by running the code on a thread with lots of stack
50    // space. This is easier and more reliable than configuring the PE binary to
51    // have a larger stack.
52    fn on_big_stack<R: Send>(f: impl Send + FnOnce() -> R) -> R {
53        cfg_select! {
54            windows => std::thread::scope(|s| {
55                std::thread::Builder::new()
56                    .stack_size(0x400000)
57                    .spawn_scoped(s, f)
58                    .unwrap()
59                    .join()
60                    .unwrap()
61            }),
62            _ => f(),
63        }
64    }
65
66    on_big_stack(Options::parse)
67}
68
69const DEFAULT_MEMORY_SIZE: u64 = 1024 * 1024 * 1024;
70
71/// Guest memory configuration parsed from `--memory` (and, flattened, from
72/// `--numa`).
73///
74/// Fields are the raw parsed options; callers apply the defaults (`size`
75/// defaults to [`DEFAULT_MEMORY_SIZE`]; `transparent_hugepages` defaults to
76/// `!hugepages`). Cross-field validation lives in [`MemoryCli::validate`].
77#[derive(Debug, Clone, Default, PartialEq, Eq, vmm_cli::KeyValueArgs)]
78pub struct MemoryCli {
79    /// Guest RAM size. Defaults to [`DEFAULT_MEMORY_SIZE`] when unset.
80    pub size: Option<vmm_cli::MemorySize>,
81    /// Whether shared file-backed memory was explicitly requested (tri-state:
82    /// unset / `on` / `off`).
83    #[kv(flag)]
84    pub shared: Option<bool>,
85    /// Whether to prefetch guest RAM.
86    #[kv(flag)]
87    pub prefetch: bool,
88    /// Whether to use transparent huge pages. When unset, defaults to enabled
89    /// unless `hugepages` is set.
90    #[kv(flag, key = "thp")]
91    pub transparent_hugepages: Option<bool>,
92    /// Whether to use explicit hugetlb memfd backing for guest RAM.
93    #[kv(flag)]
94    pub hugepages: bool,
95    /// Explicit hugetlb page size.
96    pub hugepage_size: Option<vmm_cli::MemorySize>,
97    /// File used to back guest RAM.
98    pub file: Option<PathBuf>,
99}
100
101impl MemoryCli {
102    /// Validate cross-field constraints shared by `--memory` and `--numa`.
103    pub fn validate(&self) -> anyhow::Result<()> {
104        if self.hugepage_size.is_some() && !self.hugepages {
105            anyhow::bail!("hugepage_size requires hugepages=on");
106        }
107        if self.hugepages {
108            if self.shared == Some(false) {
109                anyhow::bail!("hugepages=on conflicts with shared=off");
110            }
111            if self.file.is_some() {
112                anyhow::bail!("hugepages=on conflicts with file=...");
113            }
114        }
115        Ok(())
116    }
117}
118
119/// NUMA node configuration parsed from `--numa`.
120#[derive(Debug, Clone, PartialEq, Eq, vmm_cli::KeyValueArgs)]
121pub struct NumaNodeCli {
122    /// Memory configuration (size, shared, prefetch, hugepages, etc.).
123    #[kv(flatten)]
124    pub memory: MemoryCli,
125    /// Host NUMA node to bind memory allocation to.
126    pub host_numa_node: Option<u32>,
127    /// Explicit VP indices for this node.
128    pub vps: Option<vmm_cli::BracketRangeList>,
129}
130
131/// NUMA distance parsed from `--numa-distance`.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct NumaDistanceCli {
134    /// Source node index.
135    pub src: u32,
136    /// Destination node index.
137    pub dst: u32,
138    /// Distance value (10-255, 255 = unreachable).
139    pub distance: u8,
140}
141
142/// OpenVMM virtual machine monitor.
143///
144/// This is not yet a stable interface and may change radically between
145/// versions.
146#[derive(Parser)]
147#[command(
148    name = "openvmm",
149    version = openvmm_build_info::get().version(),
150    long_version = openvmm_build_info::get().long_version(),
151)]
152pub struct Options {
153    /// Disable persistent guest-RAM locking while keeping CPU copies available.
154    ///
155    /// Unsupported export operations fail when requested.
156    /// VMBus rings and synthetic-page loans may be unavailable. Host-owned
157    /// I/O buffers are not restricted. MSHV SNP uses non-lockable backing
158    /// automatically, without this option.
159    #[clap(long)]
160    pub force_guest_memory_bounce: bool,
161
162    /// processor count
163    #[clap(short = 'p', long, value_name = "COUNT", default_value = "1")]
164    pub processors: u32,
165
166    /// guest RAM configuration (`SIZE` or `key=value[,key=value...]`)
167    #[clap(
168        short = 'm',
169        long,
170        value_name = "PARAMS",
171        default_value = "1GB",
172        value_parser = parse_memory_config,
173        conflicts_with = "numa",
174        long_help = r#"Configure guest RAM.
175
176Syntax: SIZE | key=value[,key=value...]
177
178Size suffixes accept K, M, G, and T, optionally followed by B.
179
180Options:
181    size=<SIZE>              guest RAM size, default 1GB
182    shared[=on|off]          use shared file-backed RAM, default on
183    prefetch[=on|off]        pre-populate guest RAM mappings
184    thp[=on|off]             mark guest RAM as THP-eligible (Linux), default on
185    hugepages[=on|off]       allocate RAM from hugetlb/large pages (Linux, Windows)
186    hugepage_size=<SIZE>     hugepage size, default 2MB; requires hugepages=on
187    file=<PATH>              use an existing file as guest RAM backing
188
189Examples:
190    --memory 4G
191    --memory size=64GB,hugepages=on,hugepage_size=2MB
192    --memory size=4G,file=path/to/memory.bin
193    --memory size=4G,thp=off"#
194    )]
195    pub memory: MemoryCli,
196
197    /// NUMA node configuration (repeatable, one per node).
198    ///
199    /// Each --numa specifies one guest NUMA node. Mutually exclusive with
200    /// --memory.
201    #[clap(
202        long,
203        value_name = "PARAMS",
204        value_parser = parse_numa_node,
205        conflicts_with = "memory",
206        long_help = r#"Configure a guest NUMA node (repeatable, one per node).
207
208Syntax: key=value[,key=value...]
209
210Options:
211    size=<SIZE>              RAM for this node (required)
212    shared[=on|off]          use shared file-backed RAM, default on
213    prefetch[=on|off]        pre-populate guest RAM mappings
214    thp[=on|off]             mark node RAM as THP-eligible (Linux), default on
215    hugepages[=on|off]       allocate RAM from hugetlb/large pages (Linux, Windows)
216    hugepage_size=<SIZE>     hugepage size, default 2MB; requires hugepages=on
217    host_numa_node=<N>       bind allocation to host NUMA node N
218    vps=<LIST>               explicit VP indices (e.g. "[0,1,2,3]")
219
220  VP lists use bracket syntax with comma-separated indices and dash
221  ranges: vps=[0,1] or vps=[0-3] or vps=[0,1,4-5]. An empty list, vps=[],
222  declares a CPU-less node (e.g. a generic-initiator target); unlike a
223  non-empty list, it may be combined with nodes that omit vps.
224
225Examples:
226    --numa size=2G --numa size=2G
227    --numa size=2G,host_numa_node=0 --numa size=2G,host_numa_node=1
228    --numa size=2G,hugepages=on,vps=[0,1] --numa size=2G,vps=[2,3]
229    --numa size=2G,vps=[0-3] --numa size=2G,vps=[4-7]
230    --numa size=2G --numa size=0,vps=[]"#
231    )]
232    pub numa: Option<Vec<NumaNodeCli>>,
233
234    /// NUMA distance (repeatable). Format: SRC:DST:DISTANCE.
235    ///
236    /// SRC and DST are 0-based node indices. DISTANCE is 10-255 (10 = local, 255 = unreachable).
237    /// Specify each direction explicitly (not auto-symmetric).
238    #[clap(long, value_name = "SRC:DST:DIST", value_parser = parse_numa_distance, conflicts_with = "memory", requires = "numa")]
239    pub numa_distance: Option<Vec<NumaDistanceCli>>,
240
241    /// use shared memory segment
242    #[clap(short = 'M', long, hide = true)]
243    pub shared_memory: bool,
244
245    /// prefetch guest RAM
246    #[clap(long = "prefetch", hide = true, conflicts_with = "numa")]
247    pub deprecated_prefetch: bool,
248
249    /// back guest RAM with a file instead of anonymous memory.
250    /// The file is created/opened and sized to the guest RAM size.
251    /// Enables snapshot save (fsync) and restore (open + mmap).
252    #[clap(
253        long = "memory-backing-file",
254        value_name = "FILE",
255        hide = true,
256        conflicts_with_all = ["deprecated_private_memory", "numa"]
257    )]
258    pub deprecated_memory_backing_file: Option<PathBuf>,
259
260    /// Restore VM from a snapshot directory (implies file-backed memory from
261    /// the snapshot's memory.bin). Cannot be used with --memory-backing-file.
262    /// The same boot and device flags used at save time must also be supplied.
263    #[clap(
264        long,
265        value_name = "DIR",
266        conflicts_with_all = ["deprecated_memory_backing_file", "numa"]
267    )]
268    pub restore_snapshot: Option<PathBuf>,
269
270    /// use private anonymous memory for guest RAM
271    #[clap(long = "private-memory", hide = true, conflicts_with_all = ["deprecated_memory_backing_file", "restore_snapshot", "numa"])]
272    pub deprecated_private_memory: bool,
273
274    /// enable transparent huge pages for guest RAM (Linux only; deprecated, THP is on by default)
275    #[clap(long = "thp", hide = true, conflicts_with = "numa")]
276    pub deprecated_thp: bool,
277
278    /// start in paused state
279    #[clap(short = 'P', long)]
280    pub paused: bool,
281
282    /// kernel image (when using linux direct boot)
283    #[clap(short = 'k', long, value_name = "FILE", default_value = default_value_from_arch_env("OPENVMM_LINUX_DIRECT_KERNEL"))]
284    pub kernel: OptionalPathBuf,
285
286    /// initrd image (when using linux direct boot)
287    #[clap(short = 'r', long, value_name = "FILE", default_value = default_value_from_arch_env("OPENVMM_LINUX_DIRECT_INITRD"))]
288    pub initrd: OptionalPathBuf,
289
290    /// extra kernel command line args
291    #[clap(short = 'c', long, value_name = "STRING")]
292    pub cmdline: Vec<String>,
293
294    /// enable HV#1 capabilities
295    #[clap(long)]
296    pub hv: bool,
297
298    /// Boot UEFI without exposing hypervisor (HV#1) enlightenments. Requires
299    /// `--no-vmbus` since VMBus depends on the hypervisor.
300    #[clap(
301        long,
302        requires_all = ["uefi", "no_vmbus"],
303        conflicts_with_all = ["hv", "vtl2", "get", "pcat", "igvm"]
304    )]
305    pub no_hv: bool,
306
307    /// Use a full device tree instead of ACPI tables for ARM64 Linux direct
308    /// boot. By default, ARM64 uses ACPI mode (stub DT + EFI + ACPI tables).
309    /// This flag selects the legacy DT-only path. Rejected on x86.
310    #[clap(long, conflicts_with_all = ["uefi", "pcat", "igvm", "smbios"])]
311    pub device_tree: bool,
312
313    /// SMBIOS (DMI) identity overrides (repeatable).
314    #[clap(
315        long,
316        value_name = "PARAMS",
317        value_parser = parse_smbios,
318        long_help = r#"Override the guest's SMBIOS (DMI) identity.
319
320Syntax: type=N,key=value[,key=value...]
321
322`type` selects the SMBIOS structure and is required; there is no default.
323Unset keys use the loader's built-in default identity. Repeat --smbios to set
324fields across multiple structure types.
325
326OpenVMM Linux direct boot supports all listed fields. OpenHCL Linux direct
327boot and UEFI boot support Type 1 fields only. PCAT boot supports only Type 1
328`serial` and `uuid`. Unsupported fields are rejected with an error.
329
330Type 0 (BIOS Information):
331    vendor=<STRING>          BIOS vendor
332    version=<STRING>         BIOS version
333    date=<STRING>            BIOS release date
334    release=<MAJOR.MINOR>    System BIOS Major/Minor Release (e.g. 4.1)
335
336Type 1 (System Information):
337    manufacturer=<STRING>    system manufacturer (sys_vendor)
338    product=<STRING>         product name (product_name)
339    version=<STRING>         product version (product_version)
340    serial=<STRING>          serial number (product_serial)
341    uuid=<GUID|random>       system UUID (product_uuid); `random` generates a
342                             fresh per-VM GUID. Unset => all-zero GUID.
343    sku=<STRING>             SKU number (product_sku)
344    family=<STRING>          product family (product_family)
345
346Examples:
347    --smbios type=1,manufacturer=Contoso,product="Virtual Machine"
348    --smbios type=1,uuid=12345678-9abc-def0-1234-56789abcdef0
349    --smbios type=1,uuid=random
350    --smbios type=0,vendor=Contoso,version=1.0"#
351    )]
352    pub smbios: Vec<SmbiosCli>,
353
354    /// enable vtl2 - only supported in WHP and simulated without hypervisor support currently
355    ///
356    /// Currently implies --get.
357    #[clap(long, requires("hv"))]
358    pub vtl2: bool,
359
360    /// Add GET and related devices for using the OpenHCL paravisor to the
361    /// highest enabled VTL.
362    #[clap(long, requires("hv"))]
363    pub get: bool,
364
365    /// Disable GET and related devices for using the OpenHCL paravisor, even
366    /// when --vtl2 is passed.
367    #[clap(long, conflicts_with("get"))]
368    pub no_get: bool,
369
370    /// Run without VMBus, even if --hv or --uefi are specified.
371    #[clap(
372        long,
373        conflicts_with_all = [
374            "vmbus_vsock_path",
375            "vmbus_vtl2_vsock_path",
376            "vmbus_redirect",
377            "vmbus_max_version",
378            "vmbus_com1_serial",
379            "vmbus_com2_serial",
380            "vtl2",
381            "get",
382            "pcat",
383        ],
384    )]
385    pub no_vmbus: bool,
386
387    /// disable the VTL0 alias map presented to VTL2 by default
388    #[clap(long, requires("vtl2"))]
389    pub no_alias_map: bool,
390
391    /// enable isolation
392    #[clap(long)]
393    pub isolation: Option<IsolationCli>,
394
395    /// enable restricted interrupt injection for SNP Linux direct boot
396    #[clap(long)]
397    pub snp_restricted_injection: bool,
398
399    /// the hybrid vsock listener path
400    #[clap(long, value_name = "PATH", alias = "vsock-path")]
401    pub vmbus_vsock_path: Option<String>,
402
403    /// the VTL2 hybrid vsock listener path
404    #[clap(long, value_name = "PATH", requires("vtl2"), alias = "vtl2-vsock-path")]
405    pub vmbus_vtl2_vsock_path: Option<String>,
406
407    /// the late map vtl0 ram access policy when vtl2 is enabled
408    #[clap(long, requires("vtl2"), default_value = "halt")]
409    pub late_map_vtl0_policy: Vtl0LateMapPolicyCli,
410
411    /// attach a disk (can be passed multiple times)
412    #[clap(long_help = r#"
413e.g: --disk memdiff:file:/path/to/disk.vhd
414
415syntax: <path> | kind:<arg>[,flag,opt=arg,...]
416
417valid disk kinds:
418    `mem:<len>`                    memory backed disk
419        <len>: length of ramdisk, e.g.: `1G`
420    `memdiff:<disk>`               memory backed diff disk
421        <disk>: lower disk, e.g.: `file:base.img`
422    `file:<path>[;direct][;create=<len>]`   file-backed disk
423        <path>: path to file
424        `;direct`: bypass the OS page cache
425    `sql:<path>[;create=<len>]`    SQLite-backed disk (dev/test)
426    `sqldiff:<path>[;create]:<disk>` SQLite diff layer on a backing disk
427    `autocache:<key>:<disk>`       auto-cached SQLite layer (use `autocache::<disk>` to omit key; needs OPENVMM_AUTO_CACHE_PATH)
428    `blob:<type>:<url>`            HTTP blob (read-only)
429        <type>: `flat` or `vhd1`
430    `crypt:<cipher>:<key_file>:<disk>` encrypted disk wrapper
431        <cipher>: `xts-aes-256`
432    `prwrap:<disk>`                persistent reservations wrapper
433
434flags:
435    `ro`                           open disk as read-only
436    `dvd`                          specifies that device is cd/dvd and it is read_only
437    `vtl2`                         assign this disk to VTL2
438    `uh`                           relay this disk to VTL0 through SCSI-to-OpenHCL (show to VTL0 as SCSI)
439    `uh-nvme`                      relay this disk to VTL0 through NVMe-to-OpenHCL (show to VTL0 as SCSI)
440
441options:
442    `pcie_port=<name>`             present the disk using pcie under the specified port, incompatible with `dvd`, `vtl2`, `uh`, and `uh-nvme`
443    `on=<name>`                    attach to a named controller (NVMe or SCSI), incompatible with `pcie_port` and `vtl2`
444    `nsid=<N>`                     NVMe namespace ID (1-based), requires `on`; auto-assigned if omitted
445    `lun=<N>`                      SCSI LUN (0-based), requires `on`; auto-assigned if omitted
446    `relay=<ctrl>[:<loc>]`         relay through OpenHCL to the named OpenHCL controller, with optional location (LUN or NSID)
447"#)]
448    #[clap(long, value_name = "FILE")]
449    pub disk: Vec<DiskCli>,
450
451    /// \[deprecated\] attach a disk via an NVMe controller
452    ///
453    /// Use --nvme-pci and --disk on=\<name\> instead.
454    #[clap(long_help = r#"
455e.g: --nvme memdiff:file:/path/to/disk.vhd
456
457syntax: <path> | kind:<arg>[,flag,opt=arg,...]
458
459valid disk kinds:
460    `mem:<len>`                    memory backed disk
461        <len>: length of ramdisk, e.g.: `1G`
462    `memdiff:<disk>`               memory backed diff disk
463        <disk>: lower disk, e.g.: `file:base.img`
464    `file:<path>[;direct][;create=<len>]`   file-backed disk
465        <path>: path to file
466        `;direct`: bypass the OS page cache
467    `sql:<path>[;create=<len>]`    SQLite-backed disk (dev/test)
468    `sqldiff:<path>[;create]:<disk>` SQLite diff layer on a backing disk
469    `autocache:<key>:<disk>`       auto-cached SQLite layer (use `autocache::<disk>` to omit key; needs OPENVMM_AUTO_CACHE_PATH)
470    `blob:<type>:<url>`            HTTP blob (read-only)
471        <type>: `flat` or `vhd1`
472    `crypt:<cipher>:<key_file>:<disk>` encrypted disk wrapper
473        <cipher>: `xts-aes-256`
474    `prwrap:<disk>`                persistent reservations wrapper
475
476flags:
477    `ro`                           open disk as read-only
478    `vtl2`                         assign this disk to VTL2
479    `uh`                           relay this disk to VTL0 through SCSI-to-OpenHCL (show to VTL0 as NVMe)
480    `uh-nvme`                      relay this disk to VTL0 through NVMe-to-OpenHCL (show to VTL0 as NVMe)
481
482options:
483    `pcie_port=<name>`             present the disk using pcie under the specified port, incompatible with `vtl2`, `uh`, and `uh-nvme`
484"#)]
485    #[clap(long)]
486    pub nvme: Vec<DiskCli>,
487
488    /// create a named NVMe controller
489    #[clap(long_help = r#"
490Create a named NVMe controller with an explicit transport.
491
492syntax: id=<name>,pcie_port=<port> | id=<name>,vpci[=<guid>]
493
494The controller name can be referenced by `--disk` with the `on=<name>`
495option to attach namespaces to this controller.
496
497options:
498    `id=<name>`                    controller name (required)
499    `pcie_port=<port>`             present on PCIe under the specified port
500    `vpci[=<guid>]`                present via VPCI; optional instance GUID
501    `vtl2`                         assign to VTL2 (default VTL0)
502
503Exactly one of `pcie_port` or `vpci` must be specified.
504
505Examples:
506    --nvme-pci id=nvme0,pcie_port=p0
507    --nvme-pci id=nvme1,vpci
508    --nvme-pci id=nvme2,vpci=008091f6-9688-497d-9091-af347dc9173c
509"#)]
510    #[clap(long = "nvme-pci")]
511    pub nvme_pci: Vec<NvmeControllerCli>,
512
513    /// create a named VMBus SCSI controller
514    #[clap(long_help = r#"
515Create a named VMBus SCSI controller.
516
517syntax: id=<name>[,sub_channels=<N>][,vtl2]
518
519The controller name can be referenced by `--disk` with the `on=<name>`
520option to attach disks to this controller.
521
522options:
523    `id=<name>`                    controller name (required)
524    `sub_channels=<N>`             number of sub-channels (default 0)
525    `vtl2`                         assign to VTL2 (default VTL0)
526
527Examples:
528    --vmbus-scsi id=scsi0
529    --vmbus-scsi id=scsi1,sub_channels=4
530"#)]
531    #[clap(long = "vmbus-scsi")]
532    pub vmbus_scsi: Vec<ScsiControllerCli>,
533
534    /// register an OpenHCL-managed storage controller (relay target)
535    #[clap(long_help = r#"
536Register an OpenHCL-managed storage controller that can be used as a
537relay target with `--disk ... relay=<name>`.
538
539syntax: id=<name>,type=scsi|nvme[,guid=<guid>]
540
541options:
542    `id=<name>`                    controller name (required)
543    `type=scsi|nvme`               controller protocol (required)
544    `guid=<guid>`                  instance GUID (auto-derived from name if omitted)
545
546Examples:
547    --openhcl-controller id=vtl0-scsi,type=scsi
548    --openhcl-controller id=vtl0-nvme,type=nvme,guid=09a59b81-...
549"#)]
550    #[clap(long = "openhcl-controller")]
551    pub openhcl_controller: Vec<OpenhclControllerCli>,
552
553    /// attach a CXL Type-3 test endpoint on a PCIe root port
554    #[clap(long = "cxl-test", value_name = "mem:<len>,pcie_port=<name>")]
555    pub cxl_test: Vec<CxlTestDeviceCli>,
556
557    /// attach a disk via a virtio-blk controller
558    #[clap(long_help = r#"
559e.g: --virtio-blk memdiff:file:/path/to/disk.vhd
560
561syntax: <path> | kind:<arg>[,flag,opt=arg,...]
562
563valid disk kinds:
564    `mem:<len>`                    memory backed disk
565        <len>: length of ramdisk, e.g.: `1G`
566    `memdiff:<disk>`               memory backed diff disk
567        <disk>: lower disk, e.g.: `file:base.img`
568    `file:<path>[;direct]`                  file-backed disk
569        <path>: path to file
570        `;direct`: bypass the OS page cache
571
572flags:
573    `ro`                           open disk as read-only
574
575options:
576    `pcie_port=<name>`             present the disk using pcie under the specified port
577    `serial=<value>`               1-20 printable ASCII bytes except comma and brackets
578    `num_queues=<count>`           request queues (1-256); overrides --virtio-blk-queues
579"#)]
580    #[clap(long = "virtio-blk")]
581    pub virtio_blk: Vec<DiskCli>,
582
583    /// Default request queues and dedicated workers per native virtio-blk disk (1-256).
584    #[clap(long, default_value_t = 1, value_parser = clap::value_parser!(u16).range(1..=256))]
585    pub virtio_blk_queues: u16,
586
587    /// Maximum in-flight requests per native virtio-blk queue.
588    #[clap(long, default_value_t = 64, value_parser = clap::value_parser!(u16).range(1..))]
589    pub virtio_blk_io_depth: u16,
590
591    /// Attach a vhost-user device via a Unix socket.
592    ///
593    /// The first positional argument is the socket path. Options:
594    ///
595    /// ```text
596    ///   type=blk|fs                        — device type (shorthand)
597    ///   device_id=N                        — numeric virtio device ID
598    ///   tag=NAME                           — mount tag (required for type=fs)
599    ///   num_queues=N                       — queue count (type=blk/fs only)
600    ///   queue_size=N                       — per-queue size (type=blk/fs only)
601    ///   queue_sizes=[N,N,N]                — per-queue sizes (device_id= only)
602    ///   pcie_port=NAME                     — present on PCIe under the specified port
603    /// ```
604    ///
605    /// Examples:
606    ///
607    /// ```text
608    ///   --vhost-user /tmp/vhost.sock,type=blk
609    ///   --vhost-user /tmp/vhost.sock,type=blk,num_queues=4,queue_size=512
610    ///   --vhost-user /tmp/vhost.sock,device_id=2,queue_sizes=[128,128]
611    ///   --vhost-user /tmp/vhost.sock,type=blk,pcie_port=port0
612    ///   --vhost-user /tmp/virtiofsd.sock,type=fs,tag=myfs
613    ///   --vhost-user /tmp/virtiofsd.sock,type=fs,tag=myfs,num_queues=2,queue_size=1024
614    /// ```
615    #[cfg(target_os = "linux")]
616    #[clap(long = "vhost-user")]
617    pub vhost_user: Vec<VhostUserCli>,
618
619    /// number of sub-channels for the SCSI controller
620    #[clap(long, value_name = "COUNT", default_value = "0")]
621    pub scsi_sub_channels: u16,
622
623    /// expose a virtual NIC
624    #[clap(long)]
625    pub nic: bool,
626
627    /// expose a virtual NIC with the given backend (consomme | dio | tap | none)
628    ///
629    /// Prefix with `uh:` to add this NIC via Mana emulation through OpenHCL,
630    /// `vtl2:` to assign this NIC to VTL2, or `pcie_port=<port_name>:` to
631    /// expose the NIC over emulated PCIe at the specified port.
632    /// Prefix with `mac=<XX-XX-XX-XX-XX-XX>:` to set the guest MAC address.
633    /// Prefix a virtio NIC with `rx_gso:` to advertise guest TCP segmentation
634    /// offload. This is disabled by default until mergeable receive buffers are
635    /// supported.
636    ///
637    /// For consomme, forward host ports into the guest with `hostfwd=`:
638    ///   --net consomme:hostfwd=tcp::3389-:3389
639    ///   --net consomme:hostfwd=tcp:127.0.0.1:8080-:80
640    ///   --net consomme:hostfwd=tcp:\[::1\]:8080-:80
641    ///   --net consomme:10.0.0.0/24,hostfwd=tcp::22-:22,hostfwd=udp::5000-:5000
642    #[clap(long)]
643    pub net: Vec<NicConfigCli>,
644
645    /// expose a virtual NIC using the Windows kernel-mode vmswitch.
646    ///
647    /// Specify the switch ID or "default" for the default switch.
648    #[clap(long, value_name = "SWITCH_ID")]
649    pub kernel_vmnic: Vec<String>,
650
651    /// expose a graphics device
652    #[clap(long)]
653    pub gfx: bool,
654
655    /// support a graphics device in vtl2
656    #[clap(long, requires("vtl2"), conflicts_with("gfx"))]
657    pub vtl2_gfx: bool,
658
659    /// VNC server configuration (listen address, port, client limit, etc.).
660    #[clap(flatten)]
661    pub vnc: VncCli,
662
663    /// set the APIC ID offset, for testing APIC IDs that don't match VP index
664    #[cfg(guest_arch = "x86_64")]
665    #[clap(long, default_value_t)]
666    pub apic_id_offset: u32,
667
668    /// the maximum number of VPs per socket
669    #[clap(long)]
670    pub vps_per_socket: Option<u32>,
671
672    /// enable or disable SMT (hyperthreading) (auto | force | off)
673    #[clap(long, default_value = "auto")]
674    pub smt: SmtConfigCli,
675
676    /// configure x2apic (auto | supported | off | on)
677    #[cfg(guest_arch = "x86_64")]
678    #[clap(long, default_value = "auto", value_parser = parse_x2apic)]
679    pub x2apic: X2ApicConfig,
680
681    /// configure PCIe MSI controller for aarch64 (auto | its | v2m)
682    #[cfg(guest_arch = "aarch64")]
683    #[clap(long, default_value = "auto")]
684    pub gic_msi: GicMsiCli,
685
686    /// configure SMMUv3 IOMMU for an aarch64 PCIe root complex (repeatable).
687    ///
688    /// Syntax: `rc=<name>[,accel][,oas=auto|N][,ssidsize=auto|N]`.
689    #[cfg(guest_arch = "aarch64")]
690    #[clap(long, value_name = "SMMU_CONFIG")]
691    pub smmu: Vec<SmmuCli>,
692
693    /// COM1 binding, optionally prefixed with `debugger-mode:` (see below)
694    /// (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
695    ///
696    /// Prefix the binding with `debugger-mode:` to run this COM port in
697    /// debugger mode for WinDbg kernel debugging over serial (KD), e.g.
698    /// `--com1 debugger-mode:listen=<path>` or
699    /// `--com1 debugger-mode:listen=tcp:<ip>:<port>`. In debugger mode OpenVMM
700    /// keeps this port's backend drained and may drop bytes instead of applying
701    /// backpressure, so the KD transport does not deadlock across guest
702    /// resets/reboots (KD recovers dropped bytes via its own retransmission).
703    /// Debugger mode is independent per COM port.
704    #[clap(long, value_name = "SERIAL")]
705    pub com1: Option<ComSerialConfigCli>,
706
707    /// COM2 binding, optionally prefixed with `debugger-mode:` (see --com1)
708    /// (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
709    #[clap(long, value_name = "SERIAL")]
710    pub com2: Option<ComSerialConfigCli>,
711
712    /// COM3 binding, optionally prefixed with `debugger-mode:` (see --com1)
713    /// (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
714    #[clap(long, value_name = "SERIAL")]
715    pub com3: Option<ComSerialConfigCli>,
716
717    /// COM4 binding, optionally prefixed with `debugger-mode:` (see --com1)
718    /// (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
719    #[clap(long, value_name = "SERIAL")]
720    pub com4: Option<ComSerialConfigCli>,
721
722    /// vmbus com1 serial binding (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
723    #[structopt(long, value_name = "SERIAL")]
724    pub vmbus_com1_serial: Option<SerialConfigCli>,
725
726    /// vmbus com2 serial binding (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
727    #[structopt(long, value_name = "SERIAL")]
728    pub vmbus_com2_serial: Option<SerialConfigCli>,
729
730    /// Only allow guest to host serial traffic
731    #[clap(long)]
732    pub serial_tx_only: bool,
733
734    /// debugcon binding (port:serial, where port is a u16, and serial is (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none))
735    #[clap(long, value_name = "SERIAL")]
736    pub debugcon: Option<DebugconSerialConfigCli>,
737
738    /// boot UEFI firmware, optionally configured with comma-separated options
739    #[clap(
740        long,
741        short = 'e',
742        value_name = "OPTIONS",
743        num_args = 0..=1,
744        default_missing_value = ""
745    )]
746    pub uefi: Option<UefiCli>,
747
748    /// UEFI firmware file (deprecated; use --uefi firmware=FILE)
749    #[clap(
750        long = "uefi-firmware",
751        hide = true,
752        requires("uefi"),
753        conflicts_with("igvm"),
754        value_name = "FILE"
755    )]
756    pub deprecated_uefi_firmware: Option<PathBuf>,
757
758    /// enable UEFI debugging on COM1 (deprecated; use --uefi debug)
759    #[clap(long = "uefi-debug", hide = true, requires("uefi"))]
760    pub deprecated_uefi_debug: bool,
761
762    /// enable memory protections in UEFI (deprecated; use --uefi enable_memory_protections)
763    #[clap(long = "uefi-enable-memory-protections", hide = true, requires("uefi"))]
764    pub deprecated_uefi_enable_memory_protections: bool,
765
766    /// force UEFI to bounce-buffer all DMA traffic (deprecated; use --uefi force_dma_bounce)
767    #[clap(long = "uefi-force-dma-bounce", hide = true, requires("uefi"))]
768    pub deprecated_uefi_force_dma_bounce: bool,
769
770    /// continue with invalid UEFI firmware version information (deprecated; use --uefi force_firmware_version)
771    #[clap(long = "uefi-force-firmware-version", hide = true, requires("uefi"))]
772    pub deprecated_uefi_force_firmware_version: bool,
773
774    /// set PCAT boot order as comma-separated string of boot device types
775    /// (e.g: floppy,hdd,optical,net).
776    ///
777    /// If less than 4 entries are added, entries are added according to their
778    /// default boot order (optical,hdd,net,floppy)
779    ///
780    /// e.g: passing "floppy,optical" will result in a boot order equivalent to
781    /// "floppy,optical,hdd,net".
782    ///
783    /// Passing duplicate types is an error.
784    #[clap(long, requires("pcat"))]
785    pub pcat_boot_order: Option<PcatBootOrderCli>,
786
787    /// Boot with PCAT BIOS firmware and piix4 devices
788    #[clap(long, conflicts_with("uefi"))]
789    pub pcat: bool,
790
791    /// PCAT firmware file
792    #[clap(long, requires("pcat"), value_name = "FILE")]
793    pub pcat_firmware: Option<PathBuf>,
794
795    /// boot an IGVM with required firmware and personality options
796    #[clap(
797        long,
798        conflicts_with_all = ["kernel", "pcat"],
799        value_name = "OPTIONS",
800        long_help = r#"Boot an IGVM file.
801
802Syntax: --igvm firmware=<FILE>,personality=<openhcl|uefi|linux-direct>
803
804Both firmware and personality are required; neither has a default.
805The openhcl personality requires explicit --hv --vtl2."#
806    )]
807    pub igvm: Option<IgvmCli>,
808
809    /// specify igvm vtl2 relocation type
810    /// (absolute=\<addr\>, disable, auto=\<filesize,or memory size\>, vtl2=\<filesize,or memory size\>,)
811    #[clap(long, requires("igvm"), default_value = "auto=filesize", value_parser = parse_vtl2_relocation)]
812    pub igvm_vtl2_relocation_type: Vtl2BaseAddressType,
813
814    /// add a virtio_9p device (e.g. myfs,C:\)
815    ///
816    /// Prefix with `pcie_port=<port_name>:` to expose the device over
817    /// emulated PCIe at the specified port.
818    #[clap(long, value_name = "[pcie_port=PORT:]tag,root_path")]
819    pub virtio_9p: Vec<FsArgs>,
820
821    /// output debug info from the 9p server
822    #[clap(long)]
823    pub virtio_9p_debug: bool,
824
825    /// add a virtio_fs device (e.g. myfs,C:\,uid=1000,gid=2000)
826    ///
827    /// Prefix with `pcie_port=<port_name>:` to expose the device over
828    /// emulated PCIe at the specified port.
829    #[clap(long, value_name = "[pcie_port=PORT:]tag,root_path,[options]")]
830    pub virtio_fs: Vec<FsArgsWithOptions>,
831
832    /// add a virtio_fs device for sharing memory (e.g. myfs,\SectionDirectoryPath)
833    ///
834    /// Prefix with `pcie_port=<port_name>:` to expose the device over
835    /// emulated PCIe at the specified port.
836    #[clap(long, value_name = "[pcie_port=PORT:]tag,root_path")]
837    pub virtio_fs_shmem: Vec<FsArgs>,
838
839    /// add a virtio_fs device under the selected bus (auto | mmio | pci | pcie:port | vpci)
840    #[clap(long, value_name = "BUS", default_value = "auto")]
841    pub virtio_fs_bus: VirtioBusCli,
842
843    /// virtio PMEM device
844    ///
845    /// Prefix with `pcie_port=<port_name>:` to expose the device over
846    /// emulated PCIe at the specified port.
847    #[clap(long, value_name = "[pcie_port=PORT:]PATH")]
848    pub virtio_pmem: Option<VirtioPmemArgs>,
849
850    /// add a virtio entropy (RNG) device
851    #[clap(long)]
852    pub virtio_rng: bool,
853
854    /// add a virtio-rng device under the selected bus (auto | mmio | pci | pcie:port | vpci)
855    #[clap(long, value_name = "BUS", default_value = "auto")]
856    pub virtio_rng_bus: VirtioBusCli,
857
858    /// attach the virtio-rng device to the specified PCIe port (overrides --virtio-rng-bus)
859    #[clap(long, value_name = "PORT", requires("virtio_rng"))]
860    pub virtio_rng_pcie_port: Option<String>,
861
862    /// add a virtio real-time clock device, optionally configured with
863    /// comma-separated options (bus=auto|mmio|pci|pcie:PORT|vpci)
864    #[clap(
865        long,
866        value_name = "OPTIONS",
867        num_args = 0..=1,
868        default_missing_value = ""
869    )]
870    pub virtio_rtc: Option<VirtioRtcCli>,
871
872    /// virtio console device backed by a serial backend (/dev/hvc0 in guest)
873    ///
874    /// Accepts serial config (console | stderr | listen=\<path\> |
875    /// file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> |
876    /// term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
877    #[clap(long)]
878    pub virtio_console: Option<SerialConfigCli>,
879
880    /// attach the virtio-console device to the specified PCIe port
881    #[clap(long, value_name = "PORT", requires("virtio_console"))]
882    pub virtio_console_pcie_port: Option<String>,
883
884    /// select the bus for virtio vsock devices (pci | pcie\[:port\] | mmio)
885    #[clap(long, value_name = "BUS", value_parser = parse_virtio_vsock_bus)]
886    pub virtio_vsock_bus: Option<VirtioBusCli>,
887
888    /// add a virtio vsock device with the given Unix socket base path
889    #[clap(long, value_name = "PATH")]
890    pub virtio_vsock_path: Option<String>,
891
892    /// expose the guest in the host AF_VSOCK namespace using the Linux
893    /// vhost_vsock kernel backend
894    #[cfg(target_os = "linux")]
895    #[clap(
896        long,
897        value_name = "CID",
898        conflicts_with = "virtio_vsock_path",
899        value_parser = parse_vhost_vsock_cid
900    )]
901    pub virtio_vsock_vhost_cid: Option<u32>,
902
903    /// expose a virtio network with the given backend (dio | vmnic | tap |
904    /// none)
905    ///
906    /// Prefix with `uh:` to add this NIC via Mana emulation through OpenHCL,
907    /// `vtl2:` to assign this NIC to VTL2, or `pcie_port=<port_name>:` to
908    /// expose the NIC over emulated PCIe at the specified port.
909    /// Prefix with `mac=<XX-XX-XX-XX-XX-XX>:` to set the guest MAC address.
910    #[clap(long)]
911    pub virtio_net: Vec<NicConfigCli>,
912
913    /// send log output from the worker process to a file instead of stderr. the file will be overwritten.
914    #[clap(long, value_name = "PATH")]
915    pub log_file: Option<PathBuf>,
916
917    /// write the process ID to the specified file on startup, and remove it on
918    /// exit. the file is not removed if the process is killed with SIGKILL or
919    /// crashes. no file locking is performed.
920    #[clap(long, value_name = "PATH")]
921    pub pidfile: Option<PathBuf>,
922
923    /// \[deprecated\] run as a ttrpc server on the specified Unix socket
924    ///
925    /// Use `--rpc path=<PATH>,transport=ttrpc` instead.
926    #[clap(long, value_name = "SOCKETPATH")]
927    pub ttrpc: Option<PathBuf>,
928
929    /// \[deprecated\] run as a grpc server on the specified Unix socket
930    ///
931    /// Use `--rpc path=<PATH>,transport=grpc` instead.
932    #[clap(long, value_name = "SOCKETPATH", conflicts_with("ttrpc"))]
933    pub grpc: Option<PathBuf>,
934
935    /// run as an RPC server on the specified Unix socket
936    #[clap(long_help = r#"
937Run as an RPC server on the specified Unix socket.
938
939syntax: path=<PATH>[,transport=<TRANSPORT>]
940
941options:
942    `path=<PATH>`                  Unix socket path to listen on (required)
943    `transport=<TRANSPORT>`        wire transport to accept (default: auto)
944
945valid transports:
946    `auto`                         auto-detect ttrpc vs. gRPC per connection
947    `ttrpc`                        accept ttrpc clients only
948    `grpc`                         accept gRPC clients only
949
950Examples:
951    --rpc path=/tmp/openvmm.sock
952    --rpc path=/tmp/openvmm.sock,transport=ttrpc
953"#)]
954    #[clap(
955        long,
956        value_name = "path=PATH[,transport=TRANSPORT]",
957        conflicts_with("ttrpc"),
958        conflicts_with("grpc")
959    )]
960    pub rpc: Option<RpcCli>,
961
962    /// do not launch child processes
963    #[clap(long)]
964    pub single_process: bool,
965
966    /// device to assign (can be passed multiple times)
967    #[cfg(windows)]
968    #[clap(long, value_name = "PATH")]
969    pub device: Vec<String>,
970
971    /// instead of showing the frontpage the VM will shutdown instead (deprecated; use --uefi disable_frontpage)
972    #[clap(long = "disable-frontpage", hide = true, requires("uefi"))]
973    pub deprecated_disable_frontpage: bool,
974
975    /// add a vtpm device, optionally selecting version 138 or 185 (default: 185)
976    #[clap(
977        long,
978        value_name = "VERSION",
979        num_args = 0..=1,
980        default_missing_value = "185"
981    )]
982    pub tpm: Option<TpmVersionCli>,
983
984    /// the mesh worker host name.
985    ///
986    /// Used internally for debugging and diagnostics.
987    #[clap(long, default_value = "control", hide(true))]
988    #[expect(clippy::option_option)]
989    pub internal_worker: Option<Option<String>>,
990
991    /// redirect the VTL 0 vmbus control plane to a proxy in VTL 2.
992    #[clap(long, requires("vtl2"))]
993    pub vmbus_redirect: bool,
994
995    /// limit the maximum protocol version allowed by vmbus; used for testing purposes
996    #[clap(long, value_parser = vmbus_core::parse_vmbus_version)]
997    pub vmbus_max_version: Option<u32>,
998
999    /// The disk to use for the VMGS.
1000    ///
1001    /// If this is not provided, guest state will be stored in memory.
1002    #[clap(long_help = r#"
1003e.g: --vmgs memdiff:file:/path/to/file.vmgs
1004
1005syntax: <path> | kind:<arg>[,flag]
1006
1007valid disk kinds:
1008    `mem:<len>`                     memory backed disk
1009        <len>: length of ramdisk, e.g.: `1G` or `VMGS_DEFAULT`
1010    `memdiff:<disk>[;create=<len>]` memory backed diff disk
1011        <disk>: lower disk, e.g.: `file:base.img`
1012    `file:<path>`                   file-backed disk
1013        <path>: path to file
1014
1015flags:
1016    `fmt`                           reprovision the VMGS before boot
1017    `fmt-on-fail`                   reprovision the VMGS before boot if it is corrupted
1018"#)]
1019    #[clap(long)]
1020    pub vmgs: Option<VmgsCli>,
1021
1022    /// Use GspById guest state encryption policy with a test seed
1023    #[clap(long, requires("vmgs"))]
1024    pub test_gsp_by_id: bool,
1025
1026    /// VGA firmware file
1027    #[clap(long, requires("pcat"), value_name = "FILE")]
1028    pub vga_firmware: Option<PathBuf>,
1029
1030    /// enable secure boot
1031    #[clap(long)]
1032    pub secure_boot: bool,
1033
1034    /// use secure boot template
1035    #[clap(long)]
1036    pub secure_boot_template: Option<SecureBootTemplateCli>,
1037
1038    /// custom uefi nvram json file
1039    #[clap(long, value_name = "PATH")]
1040    pub custom_uefi_json: Option<PathBuf>,
1041
1042    /// the path to a named pipe (Windows) or Unix socket (Linux) to relay to the connected
1043    /// tty.
1044    ///
1045    /// This is a hidden argument used internally.
1046    #[clap(long, hide(true))]
1047    pub relay_console_path: Option<PathBuf>,
1048
1049    /// the title of the console window spawned from the relay console.
1050    ///
1051    /// This is a hidden argument used internally.
1052    #[clap(long, hide(true))]
1053    pub relay_console_title: Option<String>,
1054
1055    /// enable in-hypervisor gdb debugger
1056    #[clap(long, value_name = "PORT")]
1057    pub gdb: Option<u16>,
1058
1059    /// enable emulated MANA devices with the given network backend (see --net)
1060    ///
1061    /// Prefix with `pcie_port=<port_name>:` to expose the nic over emulated PCIe
1062    /// at the specified port.
1063    /// Prefix with `mac=<XX-XX-XX-XX-XX-XX>:` to set the guest MAC address.
1064    #[clap(long)]
1065    pub mana: Vec<NicConfigCli>,
1066
1067    /// use a specific hypervisor interface, with optional backend-specific
1068    /// parameters.
1069    ///
1070    /// Format: `name` or `name:key=val,key,...`
1071    ///
1072    /// WHP parameters (x86_64 guests only):
1073    ///   user_mode_apic       - use user-mode APIC emulator
1074    ///   no_enlightenments    - disable in-hypervisor enlightenments
1075    ///
1076    /// Examples:
1077    ///   --hypervisor whp
1078    ///   --hypervisor whp:user_mode_apic
1079    ///   --hypervisor whp:user_mode_apic,no_enlightenments
1080    ///   --hypervisor kvm
1081    #[clap(long)]
1082    pub hypervisor: Option<String>,
1083
1084    /// expose hardware virtualization (VMX/SVM) to the guest so it can run its
1085    /// own hypervisor.
1086    ///
1087    /// Only supported on x86_64, and only by backends that support nested
1088    /// virtualization (currently WHP, KVM, and MSHV). Requires host support.
1089    #[clap(long)]
1090    pub nested_virt: bool,
1091
1092    /// attach an ide drive (can be passed multiple times)
1093    ///
1094    /// Each ide controller has two channels. Each channel can have up to two
1095    /// attachments.
1096    ///
1097    /// If the `s` flag is not passed then the drive will we be attached to the
1098    /// primary ide channel if space is available. If two attachments have already
1099    /// been added to the primary channel then the drive will be attached to the
1100    /// secondary channel.
1101    #[clap(long_help = r#"
1102e.g: --ide memdiff:file:/path/to/disk.vhd
1103
1104syntax: <path> | kind:<arg>[,flag,opt=arg,...]
1105
1106valid disk kinds:
1107    `mem:<len>`                    memory backed disk
1108        <len>: length of ramdisk, e.g.: `1G`
1109    `memdiff:<disk>`               memory backed diff disk
1110        <disk>: lower disk, e.g.: `file:base.img`
1111    `file:<path>[;create=<len>]`   file-backed disk
1112        <path>: path to file
1113    `sql:<path>[;create=<len>]`    SQLite-backed disk (dev/test)
1114    `sqldiff:<path>[;create]:<disk>` SQLite diff layer on a backing disk
1115    `blob:<type>:<url>`            HTTP blob (read-only)
1116        <type>: `flat` or `vhd1`
1117    `crypt:<cipher>:<key_file>:<disk>` encrypted disk wrapper
1118        <cipher>: `xts-aes-256`
1119
1120additional wrapper kinds (e.g., `autocache`, `prwrap`) are also supported;
1121this list is not exhaustive.
1122
1123flags:
1124    `ro`                           open disk as read-only
1125    `s`                            attach drive to secondary ide channel
1126    `dvd`                          specifies that device is cd/dvd and it is read_only
1127"#)]
1128    #[clap(long, value_name = "FILE", requires("pcat"))]
1129    pub ide: Vec<IdeDiskCli>,
1130
1131    /// attach a floppy drive (should be able to be passed multiple times). VM must be generation 1 (no UEFI)
1132    ///
1133    #[clap(long_help = r#"
1134e.g: --floppy memdiff:file:/path/to/disk.vfd,ro
1135
1136syntax: <path> | kind:<arg>[,flag,opt=arg,...]
1137
1138valid disk kinds:
1139    `mem:<len>`                    memory backed disk
1140        <len>: length of ramdisk, e.g.: `1G`
1141    `memdiff:<disk>`               memory backed diff disk
1142        <disk>: lower disk, e.g.: `file:base.img`
1143    `file:<path>[;create=<len>]`   file-backed disk
1144        <path>: path to file
1145    `sql:<path>[;create=<len>]`    SQLite-backed disk (dev/test)
1146    `sqldiff:<path>[;create]:<disk>` SQLite diff layer on a backing disk
1147    `blob:<type>:<url>`            HTTP blob (read-only)
1148        <type>: `flat` or `vhd1`
1149    `crypt:<cipher>:<key_file>:<disk>` encrypted disk wrapper
1150        <cipher>: `xts-aes-256`
1151
1152flags:
1153    `ro`                           open disk as read-only
1154"#)]
1155    #[clap(long, value_name = "FILE", requires("pcat"))]
1156    pub floppy: Vec<FloppyDiskCli>,
1157
1158    /// enable guest watchdog device
1159    #[clap(long)]
1160    pub guest_watchdog: bool,
1161
1162    /// Enable OpenHCL's crash dump device, writing ELF core dumps of
1163    /// VTL2 user-mode components of OpenHCL in the given directory.
1164    #[clap(long)]
1165    pub openhcl_dump_path: Option<PathBuf>,
1166
1167    /// what to do when the guest requests a reset: reset it (default), halt the
1168    /// VM for inspection, or exit the VMM process (use `exit:<code>` to set the
1169    /// exit status)
1170    #[clap(long, value_name = "ACTION", default_value = "reset", value_parser = parse_guest_power_action)]
1171    pub guest_reset_action: GuestPowerAction,
1172
1173    /// what to do when the guest powers off or hibernates: halt the VM for
1174    /// inspection (default), reset it, or exit the VMM process (use
1175    /// `exit:<code>` to set the exit status)
1176    #[clap(long, value_name = "ACTION", default_value = "halt", value_parser = parse_guest_power_action)]
1177    pub guest_shutdown_action: GuestPowerAction,
1178
1179    /// what to do when the guest triple-faults: halt the VM for inspection
1180    /// (default), reset it, or exit the VMM process (use `exit:<code>` to set
1181    /// the exit status)
1182    #[clap(long, value_name = "ACTION", default_value = "halt", value_parser = parse_guest_power_action)]
1183    pub guest_crash_action: GuestPowerAction,
1184
1185    /// when the guest triple-faults, write a WinDbg-compatible `.vmrs` dump of
1186    /// the whole VM's VP state and guest memory to the specified path before
1187    /// applying the crash action
1188    ///
1189    /// This is a host-side, whole-VM dump triggered by a triple fault, distinct
1190    /// from `--openhcl-dump-path` (which captures an ELF core dump of user-mode
1191    /// components in OpenHCL).
1192    #[clap(long, value_name = "PATH")]
1193    pub crash_dump_path: Option<PathBuf>,
1194
1195    /// what to do when the guest watchdog fires (the guest stopped petting it):
1196    /// reset the VM (default), halt it for inspection, or exit the VMM process
1197    /// (use `exit:<code>` to set the exit status). Requires `--guest-watchdog`.
1198    #[clap(long, value_name = "ACTION", default_value = "reset", value_parser = parse_guest_power_action, requires = "guest_watchdog")]
1199    pub guest_watchdog_action: GuestPowerAction,
1200
1201    /// write saved state .proto files to the specified path
1202    #[clap(long)]
1203    pub write_saved_state_proto: Option<PathBuf>,
1204
1205    /// specify the IMC hive file for booting Windows
1206    #[clap(long)]
1207    pub imc: Option<PathBuf>,
1208
1209    /// expose a battery device
1210    #[clap(long)]
1211    pub battery: bool,
1212
1213    /// enable guest hibernation
1214    #[clap(long)]
1215    pub hibernation: bool,
1216
1217    /// set the UEFI console mode (deprecated; use --uefi console=MODE)
1218    #[clap(long = "uefi-console-mode", hide = true, requires("uefi"))]
1219    pub deprecated_uefi_console_mode: Option<UefiConsoleModeCli>,
1220
1221    /// set the EFI diagnostics log level
1222    #[clap(long_help = r#"
1223Set the EFI diagnostics log level.
1224
1225options:
1226    default                        default (ERROR and WARN only)
1227    info                           info (ERROR, WARN, and INFO)
1228    full                           full (all log levels)
1229"#)]
1230    #[clap(long = "efi-diagnostics-log-level", hide = true, requires("uefi"))]
1231    pub deprecated_efi_diagnostics_log_level: Option<EfiDiagnosticsLogLevelCli>,
1232
1233    /// Perform a default boot even if boot entries exist and fail (deprecated; use --uefi default_boot_always_attempt)
1234    #[clap(long = "default-boot-always-attempt", hide = true)]
1235    pub deprecated_default_boot_always_attempt: bool,
1236
1237    /// Enable AMD IOMMU (AMD-Vi) emulation on specified root complexes.
1238    /// Repeat for each root complex that should have an IOMMU, e.g.:
1239    ///   --amd-iommu rc0 --amd-iommu rc1
1240    /// The IOMMU appears at device 0 function 0 on each specified root
1241    /// complex. Requires --pcie-root-complex.
1242    #[cfg(guest_arch = "x86_64")]
1243    #[clap(long)]
1244    pub amd_iommu: Vec<String>,
1245
1246    /// Enable Intel VT-d IOMMU emulation on specified root complexes.
1247    /// Repeat for each root complex that should have an IOMMU, e.g.:
1248    ///   --intel-vtd rc0 --intel-vtd rc1
1249    /// Mutually exclusive with --amd-iommu within the same VM.
1250    /// Requires --pcie-root-complex.
1251    #[cfg(guest_arch = "x86_64")]
1252    #[clap(long)]
1253    pub intel_vtd: Vec<String>,
1254
1255    /// Attach a PCI Express root complex to the VM
1256    #[clap(long_help = r#"
1257Attach root complexes to the VM.
1258
1259Examples:
1260    # Attach root complex rc0 on segment 0 with bus and MMIO ranges
1261    --pcie-root-complex rc0,segment=0,start_bus=0,end_bus=255,low_mmio=4M,high_mmio=1G
1262
1263    # Configure HDM window size and restrictions (bitmask)
1264    --pcie-root-complex rc1,hdm=2G,hdm_window_restrictions=0x21
1265
1266Syntax: <name>[,opt=arg,...]
1267
1268Options:
1269    `segment=<value>`              configures the PCI Express segment, default 0
1270    `start_bus=<value>`            lowest valid bus number, default 0
1271    `end_bus=<value>`              highest valid bus number, default 255
1272    `low_mmio=<size>`              low MMIO window size, default 64M
1273    `high_mmio=<size>`             high MMIO window size, default 1G
1274    `low_mmio_base=<addr>`         pin low MMIO window base address (0x-prefixed hex)
1275    `high_mmio_base=<addr>`        pin high MMIO window base address (0x-prefixed hex)
1276    `hdm=<size>`                   HDM decoder MMIO window size (CFMWS window), default 1G
1277    `hdm_window_restrictions=<m>`  CFMWS window restriction bitmask (u16, decimal or 0x-prefixed hex),
1278                                   default DEVICE_COHERENT (bit 0, value 0x1)
1279    `preserve_bars`                keep pinned BARs at their assigned addresses
1280    `node=<value>`                 NUMA node the root complex is associated with
1281"#)]
1282    #[clap(long, conflicts_with("pcat"))]
1283    pub pcie_root_complex: Vec<PcieRootComplexCli>,
1284
1285    /// Place PCIe ECAM below 4 GiB for guest kernels that cannot discover high ECAM
1286    #[clap(long, requires("pcie_root_complex"), conflicts_with("pcat"))]
1287    pub pcie_ecam_below_4gb: bool,
1288
1289    /// Attach a PCI Express root port to the VM
1290    #[clap(long_help = r#"
1291Attach root ports to root complexes.
1292
1293Examples:
1294    # Attach root port rc0rp0 to root complex rc0
1295    --pcie-root-port rc0:rc0rp0
1296
1297    # Attach root port rc0rp1 to root complex rc0 with hotplug support
1298    --pcie-root-port rc0:rc0rp1,hotplug
1299
1300    # Attach root port rc0rp2 at device 5, function 0
1301    --pcie-root-port rc0:rc0rp2,addr=5
1302
1303    # Attach root port rc0rp3 at device 5, function 1
1304    --pcie-root-port rc0:rc0rp3,addr=5.1
1305
1306Syntax: <root_complex_name>:<name>[,opt,opt=arg,...]
1307
1308Options:
1309    `addr=<dev>[.<fn>]`            device/function to place this port at (default:
1310                                   lowest available); dev 0-31, fn 0-7
1311    `hotplug`                      enable hotplug support for this root port
1312    `acs=<mask>`                   ACS capability bitmask (u16, decimal or 0x-prefixed hex)
1313    `cxl`                          configure this root port as CXL-capable
1314    `pasid`                        configure this port to support PASID for downstream devices
1315"#)]
1316    #[clap(long, conflicts_with("pcat"))]
1317    pub pcie_root_port: Vec<PcieRootPortCli>,
1318
1319    /// Attach a PCI Express switch to the VM
1320    #[clap(long_help = r#"
1321Attach switches to root ports or downstream switch ports to create PCIe hierarchies.
1322
1323Examples:
1324    # Connect switch0 (with 4 downstream switch ports) directly to root port rp0
1325    --pcie-switch rp0:switch0,num_downstream_ports=4
1326
1327    # Connect switch1 (with 2 downstream switch ports) to downstream port 0 of switch0
1328    --pcie-switch switch0-downstream-0:switch1,num_downstream_ports=2
1329
1330    # Create a 3-level hierarchy: rp0 -> switch0 -> switch1 -> switch2
1331    --pcie-switch rp0:switch0
1332    --pcie-switch switch0-downstream-0:switch1
1333    --pcie-switch switch1-downstream-1:switch2
1334
1335    # Enable hotplug on all downstream switch ports of switch0
1336    --pcie-switch rp0:switch0,hotplug
1337
1338    # Enable PASID on all downstream switch ports of switch0
1339    --pcie-switch rp0:switch0,pasid
1340
1341Syntax: <port_name>:<name>[,opt,opt=arg,...]
1342
1343    port_name can be:
1344        - Root port name (e.g., "rp0") to connect directly to a root port
1345        - Downstream port name (e.g., "switch0-downstream-1") to connect to another switch
1346
1347Options:
1348    `hotplug`                       enable hotplug support for all downstream switch ports
1349    `num_downstream_ports=<value>`  number of downstream ports, default 4
1350    `acs=<mask>`                    ACS capability bitmask for downstream switch ports
1351    `pasid`                         configure this port to support PASID for downstream devices
1352"#)]
1353    #[clap(long, conflicts_with("pcat"))]
1354    pub pcie_switch: Vec<GenericPcieSwitchCli>,
1355
1356    /// Declare the device behind a PCIe port as an SRAT generic initiator
1357    #[clap(long_help = r#"
1358Declare that the device directly behind a PCIe port is a generic initiator
1359(GI) for a NUMA node, generating an SRAT Generic Initiator Affinity structure.
1360
1361The port may be a root port or a switch downstream port, so this works for
1362devices that sit behind a switch (e.g. a GPU placed under a switch shared
1363with a NIC for peer-to-peer DMA). The port is resolved by name against the
1364live topology after switch downstream ports are enumerated.
1365
1366Examples:
1367    # The device behind switch downstream port sw1-downstream-0 is a generic
1368    # initiator for NUMA node 1
1369    --pcie-generic-initiator port=sw1-downstream-0,node=1
1370
1371    # Also works for a root port name
1372    --pcie-generic-initiator port=rp0,node=2
1373
1374Syntax: port=<port_name>,node=<node>
1375"#)]
1376    #[clap(
1377        long = "pcie-generic-initiator",
1378        value_name = "port=<name>,node=<node>",
1379        conflicts_with("pcat")
1380    )]
1381    pub pcie_generic_initiator: Vec<PcieGenericInitiatorCli>,
1382
1383    /// Attach a PCIe remote device to a downstream port
1384    #[clap(long_help = r#"
1385Attach PCIe devices to root ports or downstream switch ports
1386which are implemented in a simulator running in a remote process.
1387
1388Examples:
1389    # Attach to root port rc0rp0 with default socket
1390    --pcie-remote rc0rp0
1391
1392    # Attach with custom socket address
1393    --pcie-remote rc0rp0,socket=0.0.0.0:48914
1394
1395    # Specify HU and controller identifiers
1396    --pcie-remote rc0rp0,hu=1,controller=0
1397
1398    # Multiple devices on different ports
1399    --pcie-remote rc0rp0,socket=0.0.0.0:48914
1400    --pcie-remote rc0rp1,socket=0.0.0.0:48915
1401
1402Syntax: <port_name>[,opt=arg,...]
1403
1404Options:
1405    `socket=<address>`              TCP socket (default: localhost:48914)
1406    `hu=<value>`                    Hardware unit identifier (default: 0)
1407    `controller=<value>`            Controller identifier (default: 0)
1408"#)]
1409    #[clap(long, conflicts_with("pcat"))]
1410    pub pcie_remote: Vec<PcieRemoteCli>,
1411
1412    // TODO: Unhide both USB options once USB emulation is ready for use.
1413    /// Attach an emulated xHCI USB controller to a PCIe port (repeatable).
1414    #[clap(long, hide = true, value_name = "PORT_NAME", conflicts_with("pcat"))]
1415    pub usb_xhci: Vec<UsbXhciCli>,
1416
1417    /// Attach a device backend to an xHCI USB controller (repeatable).
1418    #[clap(
1419        long,
1420        hide = true,
1421        value_name = "SPEC",
1422        requires("usb_xhci"),
1423        long_help = r#"Attach an initial USB device to a controller declared with --usb-xhci.
1424
1425Syntax: KIND[,on=PCIE_PORT][,connector=N][,OPTION=VALUE,...]
1426
1427With one controller, on defaults to its PCIe port; otherwise on is required.
1428Connectors are one-based and optional. Explicit numbers are reserved first;
1429omitted connectors use the first free number in command-line order.
1430An empty controller needs no --usb-device options.
1431
1432Kinds: mock-loopback, mock-hid, mock-storage, mock-mutt, mock-supermutt,
1433       winusb, winusb-all.
1434
1435The first four mocks accept vid=ID,pid=ID,serial=STRING overrides.
1436IDs accept decimal or 0x-prefixed hexadecimal values.
1437mock-storage also accepts blocks=N in 512-byte logical blocks.
1438mock-supermutt accepts no device-specific options.
1439winusb requires instance_id=ID, a Windows PnP instance ID.
1440winusb-all selects eligible present devices at startup and assigns free
1441connectors. It accepts optional on=PCIE_PORT, but no connector.
1442
1443Examples:
1444    --usb-xhci rc0rp0 --usb-device mock-hid --usb-device mock-storage
1445    --usb-device mock-storage,on=rc0rp0,connector=2,blocks=65536
1446    --usb-device 'winusb,instance_id=USB\DEVICE\INSTANCE'
1447    --usb-device winusb-all"#
1448    )]
1449    pub usb_device: Vec<UsbDeviceCli>,
1450
1451    /// Assign a host PCI device to the guest via VFIO (Linux only)
1452    #[clap(long_help = r#"
1453Assign a host PCI device to the guest via Linux VFIO.
1454
1455The device must be bound to vfio-pci on the host before starting the VM.
1456
1457Examples:
1458    --vfio host=0000:01:00.0,port=rp0
1459    --vfio host=0000:01:00.0,port=rp0,iommu=iommu0
1460
1461Keys:
1462    host=<pci_bdf>    (required) PCI address on the host
1463    port=<name>       (required) Root port or downstream switch port name
1464    iommu=<id>        (optional) Reference to an --iommu object. When present,
1465                      uses VFIO cdev + iommufd instead of the legacy group path.
1466"#)]
1467    #[cfg(target_os = "linux")]
1468    #[clap(long, conflicts_with("pcat"))]
1469    pub vfio: Vec<VfioDeviceCli>,
1470
1471    /// Create an iommufd context for VFIO cdev device assignment
1472    #[clap(long_help = r#"
1473Declare an iommufd context. Opens /dev/iommu so it can be referenced by
1474--vfio devices via the iommu=<id> key. The associated IOAS is allocated
1475the first time a --vfio device referring to this id is opened.
1476
1477Requires Linux kernel >= 6.6 with iommufd support.
1478
1479Examples:
1480    --iommu id=iommu0 --vfio host=0000:01:00.0,port=rp0,iommu=iommu0
1481
1482Syntax: id=<name>
1483"#)]
1484    #[cfg(target_os = "linux")]
1485    #[clap(long, conflicts_with("pcat"))]
1486    pub iommu: Vec<IommuCli>,
1487}
1488
1489impl Options {
1490    /// Returns the structured UEFI configuration with deprecated options merged in.
1491    pub fn effective_uefi(&self) -> anyhow::Result<Option<UefiCli>> {
1492        let mut uefi = match &self.uefi {
1493            Some(uefi) => uefi.clone(),
1494            None => return Ok(None),
1495        };
1496
1497        if let Some(firmware) = &self.deprecated_uefi_firmware {
1498            if uefi.firmware.is_some() {
1499                anyhow::bail!("--uefi firmware=... conflicts with --uefi-firmware");
1500            }
1501            uefi.firmware = Some(firmware.clone());
1502        }
1503        if let Some(console) = self.deprecated_uefi_console_mode {
1504            if uefi.console.is_some() {
1505                anyhow::bail!("--uefi console=... conflicts with --uefi-console-mode");
1506            }
1507            uefi.console = Some(console);
1508        }
1509        if let Some(diagnostics) = self.deprecated_efi_diagnostics_log_level {
1510            if uefi.diagnostics.is_some() {
1511                anyhow::bail!("--uefi diagnostics=... conflicts with --efi-diagnostics-log-level");
1512            }
1513            uefi.diagnostics = Some(diagnostics);
1514        }
1515
1516        uefi.debug |= self.deprecated_uefi_debug;
1517        uefi.enable_memory_protections |= self.deprecated_uefi_enable_memory_protections;
1518        uefi.force_dma_bounce |= self.deprecated_uefi_force_dma_bounce;
1519        uefi.force_firmware_version |= self.deprecated_uefi_force_firmware_version;
1520        uefi.disable_frontpage |= self.deprecated_disable_frontpage;
1521        uefi.default_boot_always_attempt |= self.deprecated_default_boot_always_attempt;
1522        Ok(Some(uefi))
1523    }
1524
1525    /// Returns the effective guest RAM size.
1526    pub fn memory_size(&self) -> u64 {
1527        self.memory.size.map(|m| m.0).unwrap_or(DEFAULT_MEMORY_SIZE)
1528    }
1529
1530    /// Returns whether guest RAM should be prefetched.
1531    pub fn prefetch_memory(&self) -> bool {
1532        self.memory.prefetch || self.deprecated_prefetch
1533    }
1534
1535    /// Returns whether guest RAM should use private anonymous backing.
1536    pub fn private_memory(&self) -> bool {
1537        self.memory.shared == Some(false) || self.deprecated_private_memory
1538    }
1539
1540    /// Returns whether guest RAM should be marked THP-eligible.
1541    pub fn transparent_hugepages(&self) -> bool {
1542        self.memory
1543            .transparent_hugepages
1544            .unwrap_or(!self.memory.hugepages)
1545            || self.deprecated_thp
1546    }
1547
1548    /// Returns the effective file backing path for guest RAM.
1549    pub fn memory_backing_file(&self) -> Option<&PathBuf> {
1550        self.memory
1551            .file
1552            .as_ref()
1553            .or(self.deprecated_memory_backing_file.as_ref())
1554    }
1555
1556    /// Validates combinations that span the new `--memory` parser and legacy aliases.
1557    ///
1558    /// Only checks that cannot be expressed elsewhere live here. Conflicts
1559    /// within a single `--memory` string are enforced by the parser, and
1560    /// semantic constraints (platform support, private-vs-shared, huge pages
1561    /// vs. legacy RAM, etc.) are enforced by the membacking builder at VM
1562    /// build time; those are not duplicated here.
1563    pub fn validate_memory_options(&self) -> anyhow::Result<()> {
1564        if self.memory.file.is_some() && self.deprecated_memory_backing_file.is_some() {
1565            anyhow::bail!("--memory file=... conflicts with --memory-backing-file");
1566        }
1567        if self.memory.file.is_some() && self.restore_snapshot.is_some() {
1568            anyhow::bail!("--memory file=... conflicts with --restore-snapshot");
1569        }
1570        if self.memory.shared == Some(true) && self.deprecated_private_memory {
1571            anyhow::bail!("--memory shared=on conflicts with --private-memory");
1572        }
1573        Ok(())
1574    }
1575
1576    /// Validates isolation-specific command-line option combinations.
1577    pub fn validate_isolation_options(&self) -> anyhow::Result<()> {
1578        if self.snp_restricted_injection && !matches!(self.isolation, Some(IsolationCli::Snp)) {
1579            anyhow::bail!("--snp-restricted-injection requires --isolation snp");
1580        }
1581        if self.snp_restricted_injection
1582            && self
1583                .hypervisor
1584                .as_deref()
1585                .and_then(|value| value.split(':').next())
1586                != Some("mshv")
1587        {
1588            anyhow::bail!("--snp-restricted-injection requires --hypervisor mshv");
1589        }
1590        if self.snp_restricted_injection
1591            && (self.uefi.is_some()
1592                || self.pcat
1593                || self.igvm.is_some()
1594                || self.restore_snapshot.is_some())
1595        {
1596            anyhow::bail!("--snp-restricted-injection requires Linux direct boot");
1597        }
1598        if matches!(self.isolation, Some(IsolationCli::Snp)) {
1599            if self.uefi.is_some() {
1600                anyhow::bail!("SNP isolation currently only supports Linux direct boot");
1601            }
1602            if self.memory.hugepages
1603                || self
1604                    .numa
1605                    .as_ref()
1606                    .is_some_and(|nodes| nodes.iter().any(|node| node.memory.hugepages))
1607            {
1608                anyhow::bail!("SNP isolation currently does not support hugetlb memory");
1609            }
1610        }
1611        Ok(())
1612    }
1613
1614    /// Validates VM options before resource construction or other side effects.
1615    pub fn validate_vm_options(&self) -> anyhow::Result<()> {
1616        self.validate_isolation_options()?;
1617        self.validate_igvm_options()?;
1618        Ok(())
1619    }
1620
1621    /// Validates IGVM personality selection.
1622    pub fn validate_igvm_options(&self) -> anyhow::Result<()> {
1623        let Some(igvm) = &self.igvm else {
1624            return Ok(());
1625        };
1626        match igvm.personality {
1627            IgvmPersonalityCli::Openhcl => {
1628                anyhow::ensure!(
1629                    self.hv && self.vtl2,
1630                    "--igvm personality=openhcl requires --hv --vtl2"
1631                );
1632            }
1633            IgvmPersonalityCli::Uefi | IgvmPersonalityCli::LinuxDirect => {
1634                anyhow::ensure!(
1635                    !self.vtl2,
1636                    "--vtl2 requires --igvm personality=openhcl for IGVM boots"
1637                );
1638                anyhow::ensure!(
1639                    self.uefi.is_none(),
1640                    "--uefi is only supported with --igvm personality=openhcl"
1641                );
1642            }
1643        }
1644        Ok(())
1645    }
1646}
1647
1648#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueArgs)]
1649pub struct IgvmCli {
1650    pub firmware: PathBuf,
1651    pub personality: IgvmPersonalityCli,
1652}
1653
1654#[derive(Clone, Debug, Default, vmm_cli::KeyValueArgs)]
1655pub struct UefiCli {
1656    pub firmware: Option<PathBuf>,
1657    #[kv(flag)]
1658    pub debug: bool,
1659    #[kv(flag)]
1660    pub enable_memory_protections: bool,
1661    #[kv(flag)]
1662    pub force_dma_bounce: bool,
1663    #[kv(flag)]
1664    pub force_firmware_version: bool,
1665    #[kv(flag)]
1666    pub disable_frontpage: bool,
1667    pub console: Option<UefiConsoleModeCli>,
1668    pub diagnostics: Option<EfiDiagnosticsLogLevelCli>,
1669    #[kv(flag)]
1670    pub default_boot_always_attempt: bool,
1671}
1672
1673/// Options for `--virtio-rtc`.
1674#[derive(Clone, Debug, PartialEq, Eq, vmm_cli::KeyValueArgs)]
1675pub struct VirtioRtcCli {
1676    /// Bus to attach the device to (auto | mmio | pci | pcie:PORT | vpci).
1677    #[kv(default = VirtioBusCli::Auto)]
1678    pub bus: VirtioBusCli,
1679}
1680
1681#[derive(Clone, Debug, PartialEq)]
1682pub struct FsArgs {
1683    pub tag: String,
1684    pub path: String,
1685    pub pcie_port: Option<String>,
1686}
1687
1688impl FromStr for FsArgs {
1689    type Err = anyhow::Error;
1690
1691    fn from_str(s: &str) -> Result<Self, Self::Err> {
1692        let (pcie_port, s) = parse_pcie_port_prefix(s);
1693        let mut s = s.split(',');
1694        let (Some(tag), Some(path), None) = (s.next(), s.next(), s.next()) else {
1695            anyhow::bail!("expected [pcie_port=<port>:]<tag>,<path>");
1696        };
1697        Ok(Self {
1698            tag: tag.to_owned(),
1699            path: path.to_owned(),
1700            pcie_port,
1701        })
1702    }
1703}
1704
1705#[derive(Clone, Debug, PartialEq)]
1706pub struct FsArgsWithOptions {
1707    /// The file system tag.
1708    pub tag: String,
1709    /// The root path.
1710    pub path: String,
1711    /// The extra options, joined with ';'.
1712    pub options: String,
1713    /// Optional PCIe port name.
1714    pub pcie_port: Option<String>,
1715}
1716
1717impl FromStr for FsArgsWithOptions {
1718    type Err = anyhow::Error;
1719
1720    fn from_str(s: &str) -> Result<Self, Self::Err> {
1721        let (pcie_port, s) = parse_pcie_port_prefix(s);
1722        let mut s = s.split(',');
1723        let (Some(tag), Some(path)) = (s.next(), s.next()) else {
1724            anyhow::bail!("expected [pcie_port=<port>:]<tag>,<path>[,<options>]");
1725        };
1726        let options = s.collect::<Vec<_>>().join(";");
1727        Ok(Self {
1728            tag: tag.to_owned(),
1729            path: path.to_owned(),
1730            options,
1731            pcie_port,
1732        })
1733    }
1734}
1735
1736/// What the VMM does on a guest power event (reset, power-off/hibernate,
1737/// triple-fault, or watchdog timeout). Parsed from `reset`, `halt`, `exit`, or
1738/// `exit:<code>`; a bare `exit` uses status 0.
1739#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1740pub enum GuestPowerAction {
1741    /// Restart the guest.
1742    Reset,
1743    /// Stop the VM but keep the VMM process, so it can be inspected or
1744    /// restarted from the REPL.
1745    Halt,
1746    /// Exit the VMM process with this status code.
1747    Exit(u8),
1748}
1749
1750/// Parse a [`GuestPowerAction`] from `reset`, `halt`, `exit`, or `exit:<code>`.
1751/// A bare `exit` exits with status 0; `exit:<code>` exits with `<code>` (0-255).
1752fn parse_guest_power_action(s: &str) -> Result<GuestPowerAction, String> {
1753    match s {
1754        "reset" => Ok(GuestPowerAction::Reset),
1755        "halt" => Ok(GuestPowerAction::Halt),
1756        "exit" => Ok(GuestPowerAction::Exit(0)),
1757        _ => match s.strip_prefix("exit:") {
1758            Some(code) => code
1759                .parse::<u8>()
1760                .map(GuestPowerAction::Exit)
1761                .map_err(|err| format!("invalid exit code '{code}' (expected 0-255): {err}")),
1762            None => Err(format!(
1763                "expected reset, halt, exit, or exit:<code>, got '{s}'"
1764            )),
1765        },
1766    }
1767}
1768
1769#[derive(Clone, Debug, PartialEq, Eq)]
1770pub enum VirtioBusCli {
1771    Auto,
1772    Mmio,
1773    Pci,
1774    Pcie(String),
1775    Vpci,
1776}
1777
1778impl FromStr for VirtioBusCli {
1779    type Err = String;
1780
1781    fn from_str(value: &str) -> Result<Self, Self::Err> {
1782        parse_virtio_bus(value, false)
1783    }
1784}
1785
1786fn parse_virtio_bus(value: &str, ignore_case: bool) -> Result<VirtioBusCli, String> {
1787    let eq = |value: &str, expected: &str| {
1788        if ignore_case {
1789            value.eq_ignore_ascii_case(expected)
1790        } else {
1791            value == expected
1792        }
1793    };
1794
1795    match value.split_once(':') {
1796        None if eq(value, "auto") => Ok(VirtioBusCli::Auto),
1797        None if eq(value, "mmio") => Ok(VirtioBusCli::Mmio),
1798        None if eq(value, "pci") => Ok(VirtioBusCli::Pci),
1799        None if eq(value, "vpci") => Ok(VirtioBusCli::Vpci),
1800        Some((bus, port)) if eq(bus, "pcie") && !port.is_empty() && !port.contains(':') => {
1801            Ok(VirtioBusCli::Pcie(port.to_string()))
1802        }
1803        _ => Err("expected auto, mmio, pci, pcie:<port>, or vpci".to_string()),
1804    }
1805}
1806
1807fn parse_virtio_vsock_bus(value: &str) -> Result<VirtioBusCli, String> {
1808    if value.eq_ignore_ascii_case("pcie") {
1809        return Ok(VirtioBusCli::Pcie("vsock".to_string()));
1810    }
1811
1812    match parse_virtio_bus(value, true) {
1813        Ok(bus @ (VirtioBusCli::Mmio | VirtioBusCli::Pci | VirtioBusCli::Pcie(_))) => Ok(bus),
1814        _ => Err("expected mmio, pci, pcie, or pcie:<port>".to_string()),
1815    }
1816}
1817
1818#[cfg(target_os = "linux")]
1819fn parse_vhost_vsock_cid(value: &str) -> Result<u32, String> {
1820    let cid = value
1821        .parse::<u32>()
1822        .map_err(|error| format!("invalid CID '{value}': {error}"))?;
1823    if !(3..u32::MAX).contains(&cid) {
1824        return Err(format!("CID must be between 3 and {}", u32::MAX - 1));
1825    }
1826    Ok(cid)
1827}
1828
1829/// Parse an optional `pcie_port=<name>:` prefix from a CLI argument string.
1830///
1831/// Returns `(Some(port_name), rest)` if the prefix is present, or
1832/// `(None, original)` if not.
1833fn parse_pcie_port_prefix(s: &str) -> (Option<String>, &str) {
1834    if let Some(rest) = s.strip_prefix("pcie_port=") {
1835        if let Some((port, rest)) = rest.split_once(':') {
1836            if !port.is_empty() {
1837                return (Some(port.to_string()), rest);
1838            }
1839        }
1840    }
1841    (None, s)
1842}
1843
1844#[derive(Clone, Debug, PartialEq)]
1845pub struct VirtioPmemArgs {
1846    pub path: String,
1847    pub pcie_port: Option<String>,
1848}
1849
1850impl FromStr for VirtioPmemArgs {
1851    type Err = anyhow::Error;
1852
1853    fn from_str(s: &str) -> Result<Self, Self::Err> {
1854        let (pcie_port, s) = parse_pcie_port_prefix(s);
1855        if s.is_empty() {
1856            anyhow::bail!("expected [pcie_port=<port>:]<path>");
1857        }
1858        Ok(Self {
1859            path: s.to_owned(),
1860            pcie_port,
1861        })
1862    }
1863}
1864
1865#[derive(clap::ValueEnum, Clone, Copy)]
1866pub enum SecureBootTemplateCli {
1867    Windows,
1868    UefiCa,
1869}
1870
1871/// TPM reference implementation version selected by `--tpm`.
1872#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
1873pub enum TpmVersionCli {
1874    /// TPM reference implementation version 1.38.
1875    #[value(name = "138", alias = "1.38")]
1876    V138,
1877    /// TPM reference implementation version 1.85.
1878    #[value(name = "185", alias = "1.85")]
1879    V185,
1880}
1881
1882fn parse_memory(s: &str) -> anyhow::Result<u64> {
1883    if s == "VMGS_DEFAULT" {
1884        Ok(vmgs_format::VMGS_DEFAULT_CAPACITY)
1885    } else {
1886        || -> Option<u64> {
1887            let mut b = s.as_bytes();
1888            if s.ends_with('B') {
1889                b = &b[..b.len() - 1]
1890            }
1891            if b.is_empty() {
1892                return None;
1893            }
1894            let multi = match b[b.len() - 1] as char {
1895                'T' => Some(1024 * 1024 * 1024 * 1024),
1896                'G' => Some(1024 * 1024 * 1024),
1897                'M' => Some(1024 * 1024),
1898                'K' => Some(1024),
1899                _ => None,
1900            };
1901            if multi.is_some() {
1902                b = &b[..b.len() - 1]
1903            }
1904            let n: u64 = std::str::from_utf8(b).ok()?.parse().ok()?;
1905            n.checked_mul(multi.unwrap_or(1))
1906        }()
1907        .with_context(|| format!("invalid memory size '{0}'", s))
1908    }
1909}
1910
1911/// Parses an address, which must be a `0x`-prefixed hexadecimal value.
1912fn parse_address(s: &str) -> anyhow::Result<u64> {
1913    let hex = s
1914        .strip_prefix("0x")
1915        .or_else(|| s.strip_prefix("0X"))
1916        .with_context(|| format!("invalid address '{s}', expected a 0x-prefixed hex value"))?;
1917    u64::from_str_radix(hex, 16).with_context(|| format!("invalid address '{s}'"))
1918}
1919
1920fn parse_acs_capability_mask(value: &str) -> anyhow::Result<u16> {
1921    if let Some(hex) = value
1922        .strip_prefix("0x")
1923        .or_else(|| value.strip_prefix("0X"))
1924    {
1925        u16::from_str_radix(hex, 16).context("invalid ACS capability mask")
1926    } else {
1927        value.parse::<u16>().context("invalid ACS capability mask")
1928    }
1929}
1930
1931/// A parsed SMBIOS `release=MAJOR.MINOR` value: exactly two `u8` components
1932/// separated by a dot.
1933#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1934pub struct SmbiosRelease(pub u8, pub u8);
1935
1936impl FromStr for SmbiosRelease {
1937    type Err = anyhow::Error;
1938
1939    fn from_str(value: &str) -> anyhow::Result<Self> {
1940        let (major, minor) = value
1941            .split_once('.')
1942            .with_context(|| format!("invalid smbios release '{value}', expected MAJOR.MINOR"))?;
1943        let major = major
1944            .parse::<u8>()
1945            .with_context(|| format!("invalid smbios release major '{major}'"))?;
1946        let minor = minor
1947            .parse::<u8>()
1948            .with_context(|| format!("invalid smbios release minor '{minor}'"))?;
1949        Ok(SmbiosRelease(major, minor))
1950    }
1951}
1952
1953/// A parsed SMBIOS `uuid=` value: either an explicit GUID or the literal
1954/// `random`, which requests a freshly generated per-VM GUID.
1955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1956pub enum SmbiosUuid {
1957    /// Generate a fresh random GUID when the VM is created.
1958    Random,
1959    /// Use this fixed GUID.
1960    Fixed(Guid),
1961}
1962
1963impl FromStr for SmbiosUuid {
1964    type Err = anyhow::Error;
1965
1966    fn from_str(value: &str) -> anyhow::Result<Self> {
1967        if value == "random" {
1968            Ok(SmbiosUuid::Random)
1969        } else {
1970            let guid = value
1971                .parse::<Guid>()
1972                .with_context(|| format!("invalid smbios uuid '{value}'"))?;
1973            Ok(SmbiosUuid::Fixed(guid))
1974        }
1975    }
1976}
1977
1978/// SMBIOS Type 0 (BIOS Information) overrides parsed from a `--smbios type=0,…`
1979/// argument. Field names mirror `SmbiosBiosOverrides`.
1980#[derive(Debug, Clone, Default, PartialEq, Eq, vmm_cli::KeyValueArgs)]
1981pub struct SmbiosBiosCli {
1982    /// BIOS vendor (`vendor`).
1983    pub vendor: Option<String>,
1984    /// BIOS version (`version`).
1985    pub version: Option<String>,
1986    /// BIOS release date (`date`).
1987    #[kv(key = "date")]
1988    pub release_date: Option<String>,
1989    /// System BIOS Major/Minor Release (`release=MAJOR.MINOR`).
1990    pub release: Option<SmbiosRelease>,
1991}
1992
1993/// SMBIOS Type 1 (System Information) overrides parsed from a `--smbios type=1,…`
1994/// argument. Field names mirror `SmbiosSystemOverrides`.
1995#[derive(Debug, Clone, Default, PartialEq, Eq, vmm_cli::KeyValueArgs)]
1996pub struct SmbiosSystemCli {
1997    /// System manufacturer (`manufacturer`).
1998    pub manufacturer: Option<String>,
1999    /// System product name (`product`).
2000    #[kv(key = "product")]
2001    pub product_name: Option<String>,
2002    /// System version (`version`).
2003    pub version: Option<String>,
2004    /// System serial number (`serial`).
2005    #[kv(key = "serial")]
2006    pub serial_number: Option<String>,
2007    /// System SKU number (`sku`).
2008    #[kv(key = "sku")]
2009    pub sku_number: Option<String>,
2010    /// System family (`family`).
2011    pub family: Option<String>,
2012    /// System UUID (`uuid=GUID` or `uuid=random`).
2013    pub uuid: Option<SmbiosUuid>,
2014}
2015
2016/// SMBIOS (DMI) identity overrides parsed from `--smbios` arguments, grouped by
2017/// SMBIOS structure type to mirror the required `type=N` CLI prefix and the
2018/// loader's `SmbiosConfig` layout.
2019///
2020/// Each `--smbios` argument targets exactly one type; multiple arguments are
2021/// merged with [`SmbiosCli::merge`].
2022#[derive(Debug, Clone, Default, PartialEq, Eq)]
2023pub struct SmbiosCli {
2024    /// Type 0 (BIOS Information) overrides.
2025    pub bios: SmbiosBiosCli,
2026    /// Type 1 (System Information) overrides.
2027    pub system: SmbiosSystemCli,
2028}
2029
2030/// Set an override slot, erroring if it is already set.
2031fn smbios_set_once<T>(slot: &mut Option<T>, key: &str, value: T) -> anyhow::Result<()> {
2032    anyhow::ensure!(slot.is_none(), "duplicate smbios option '{key}'");
2033    *slot = Some(value);
2034    Ok(())
2035}
2036
2037impl SmbiosCli {
2038    /// Merge another parsed `--smbios` argument into this one, erroring if any
2039    /// field is set by both.
2040    pub fn merge(&mut self, other: SmbiosCli) -> anyhow::Result<()> {
2041        let SmbiosCli {
2042            bios:
2043                SmbiosBiosCli {
2044                    vendor,
2045                    version: bios_version,
2046                    release_date,
2047                    release,
2048                },
2049            system:
2050                SmbiosSystemCli {
2051                    manufacturer,
2052                    product_name,
2053                    version: system_version,
2054                    serial_number,
2055                    sku_number,
2056                    family,
2057                    uuid,
2058                },
2059        } = other;
2060        merge_smbios_field(&mut self.bios.vendor, vendor, 0, "vendor")?;
2061        merge_smbios_field(&mut self.bios.version, bios_version, 0, "version")?;
2062        merge_smbios_field(&mut self.bios.release_date, release_date, 0, "date")?;
2063        merge_smbios_field(&mut self.bios.release, release, 0, "release")?;
2064        merge_smbios_field(
2065            &mut self.system.manufacturer,
2066            manufacturer,
2067            1,
2068            "manufacturer",
2069        )?;
2070        merge_smbios_field(&mut self.system.product_name, product_name, 1, "product")?;
2071        merge_smbios_field(&mut self.system.version, system_version, 1, "version")?;
2072        merge_smbios_field(&mut self.system.serial_number, serial_number, 1, "serial")?;
2073        merge_smbios_field(&mut self.system.sku_number, sku_number, 1, "sku")?;
2074        merge_smbios_field(&mut self.system.family, family, 1, "family")?;
2075        merge_smbios_field(&mut self.system.uuid, uuid, 1, "uuid")?;
2076        Ok(())
2077    }
2078}
2079
2080/// Merge a single override field, erroring if both sides are set. `typ` is the
2081/// SMBIOS structure type the field belongs to, included in the error message.
2082fn merge_smbios_field<T>(
2083    dst: &mut Option<T>,
2084    src: Option<T>,
2085    typ: u8,
2086    key: &str,
2087) -> anyhow::Result<()> {
2088    if let Some(value) = src {
2089        smbios_set_once(dst, &format!("type={typ} {key}"), value)?;
2090    }
2091    Ok(())
2092}
2093
2094/// Parse a single `--smbios` argument: `type=N,key=value[,key=value...]`.
2095///
2096/// `type=N` is required (there is no default) and selects the key namespace;
2097/// the remaining `key=value` pairs are parsed by the matching per-type
2098/// `KeyValueArgs` struct. Unknown types and unknown keys are hard errors (no
2099/// silent drop).
2100fn parse_smbios(s: &str) -> anyhow::Result<SmbiosCli> {
2101    let mut typ: Option<u8> = None;
2102    let mut rest = Vec::new();
2103    for part in s.split(',') {
2104        let (key, value) = part
2105            .split_once('=')
2106            .with_context(|| format!("invalid smbios option '{part}', expected key=value"))?;
2107        if key.is_empty() || value.is_empty() {
2108            anyhow::bail!("invalid smbios option '{part}', expected key=value");
2109        }
2110        if key == "type" {
2111            anyhow::ensure!(typ.is_none(), "duplicate smbios option 'type'");
2112            typ = Some(
2113                value
2114                    .parse::<u8>()
2115                    .with_context(|| format!("invalid smbios type '{value}'"))?,
2116            );
2117        } else {
2118            rest.push(part);
2119        }
2120    }
2121
2122    let typ = typ.context("smbios option requires 'type=N' (e.g. 'type=1')")?;
2123    let rest = rest.join(",");
2124    Ok(match typ {
2125        0 => SmbiosCli {
2126            bios: rest.parse()?,
2127            ..Default::default()
2128        },
2129        1 => SmbiosCli {
2130            system: rest.parse()?,
2131            ..Default::default()
2132        },
2133        other => anyhow::bail!("unsupported smbios type '{other}' (expected 0 or 1)"),
2134    })
2135}
2136
2137fn parse_memory_config(s: &str) -> anyhow::Result<MemoryCli> {
2138    // Bare shortcut: `--memory 64G` sets only the size.
2139    let memory = if !s.contains('=') && !s.contains(',') {
2140        MemoryCli {
2141            size: Some(s.parse::<vmm_cli::MemorySize>()?),
2142            ..Default::default()
2143        }
2144    } else {
2145        s.parse::<MemoryCli>()?
2146    };
2147    memory.validate()?;
2148    Ok(memory)
2149}
2150
2151fn parse_numa_node(s: &str) -> anyhow::Result<NumaNodeCli> {
2152    let node: NumaNodeCli = s.parse()?;
2153    anyhow::ensure!(
2154        node.memory.size.is_some(),
2155        "numa node requires 'size' option"
2156    );
2157    anyhow::ensure!(
2158        node.memory.file.is_none(),
2159        "'file' is not supported in --numa"
2160    );
2161    node.memory.validate()?;
2162    Ok(node)
2163}
2164
2165fn parse_numa_distance(s: &str) -> anyhow::Result<NumaDistanceCli> {
2166    let parts: Vec<&str> = s.split(':').collect();
2167    anyhow::ensure!(
2168        parts.len() == 3,
2169        "expected SRC:DST:DISTANCE format, got '{s}'"
2170    );
2171    let src = parts[0].parse::<u32>().context("invalid source node")?;
2172    let dst = parts[1]
2173        .parse::<u32>()
2174        .context("invalid destination node")?;
2175    let distance = parts[2].parse::<u8>().context("invalid distance")?;
2176    anyhow::ensure!(
2177        distance >= 10,
2178        "distance must be >= 10 (10 = local), got {distance}"
2179    );
2180    Ok(NumaDistanceCli { src, dst, distance })
2181}
2182
2183/// Parse a number from a string that could be prefixed with 0x to indicate hex.
2184fn parse_number(s: &str) -> Result<u64, std::num::ParseIntError> {
2185    match s.strip_prefix("0x") {
2186        Some(rest) => u64::from_str_radix(rest, 16),
2187        None => s.parse::<u64>(),
2188    }
2189}
2190
2191#[derive(Clone, Debug, PartialEq)]
2192pub enum DiskCliKind {
2193    // mem:<len>
2194    Memory(u64),
2195    // memdiff:<kind>
2196    MemoryDiff(Box<DiskCliKind>),
2197    // sql:<path>[;create=<len>]
2198    Sqlite {
2199        path: PathBuf,
2200        create_with_len: Option<u64>,
2201    },
2202    // sqldiff:<path>[;create]:<kind>
2203    SqliteDiff {
2204        path: PathBuf,
2205        create: bool,
2206        disk: Box<DiskCliKind>,
2207    },
2208    // autocache:[key]:<kind>
2209    AutoCacheSqlite {
2210        cache_path: String,
2211        key: Option<String>,
2212        disk: Box<DiskCliKind>,
2213    },
2214    // prwrap:<kind>
2215    PersistentReservationsWrapper(Box<DiskCliKind>),
2216    // file:<path>[;direct][;create=<len>]
2217    File {
2218        path: PathBuf,
2219        create_with_len: Option<u64>,
2220        direct: bool,
2221    },
2222    // blob:<type>:<url>
2223    Blob {
2224        kind: BlobKind,
2225        url: String,
2226    },
2227    // crypt:<cipher>:<key_file>:<kind>
2228    Crypt {
2229        cipher: DiskCipher,
2230        key_file: PathBuf,
2231        disk: Box<DiskCliKind>,
2232    },
2233    // delay:<delay_ms>:<kind>
2234    DelayDiskWrapper {
2235        delay_ms: u64,
2236        disk: Box<DiskCliKind>,
2237    },
2238}
2239
2240#[derive(ValueEnum, Clone, Copy, Debug, PartialEq)]
2241pub enum DiskCipher {
2242    #[clap(name = "xts-aes-256")]
2243    XtsAes256,
2244}
2245
2246#[derive(Copy, Clone, Debug, PartialEq)]
2247pub enum BlobKind {
2248    Flat,
2249    Vhd1,
2250}
2251
2252struct FileOpts {
2253    path: PathBuf,
2254    create_with_len: Option<u64>,
2255    direct: bool,
2256}
2257
2258fn parse_file_opts(arg: &str) -> anyhow::Result<FileOpts> {
2259    let mut path = arg;
2260    let mut create_with_len = None;
2261    let mut direct = false;
2262
2263    // Parse semicolon-delimited options after the path.
2264    if let Some((p, rest)) = arg.split_once(';') {
2265        path = p;
2266        for opt in rest.split(';') {
2267            if let Some(len) = opt.strip_prefix("create=") {
2268                create_with_len = Some(parse_memory(len)?);
2269            } else if opt == "direct" {
2270                direct = true;
2271            } else {
2272                anyhow::bail!("invalid file option '{opt}', expected 'create=<len>' or 'direct'");
2273            }
2274        }
2275    }
2276
2277    Ok(FileOpts {
2278        path: path.into(),
2279        create_with_len,
2280        direct,
2281    })
2282}
2283
2284impl DiskCliKind {
2285    /// Parse an `autocache:[key]:<kind>` disk spec, given the cache path
2286    /// (normally read from `OPENVMM_AUTO_CACHE_PATH`).
2287    fn parse_autocache(
2288        arg: &str,
2289        cache_path: Result<String, std::env::VarError>,
2290    ) -> anyhow::Result<Self> {
2291        let (key, kind) = arg.split_once(':').context("expected [key]:kind")?;
2292        let cache_path = cache_path.context("must set cache path via OPENVMM_AUTO_CACHE_PATH")?;
2293        Ok(DiskCliKind::AutoCacheSqlite {
2294            cache_path,
2295            key: (!key.is_empty()).then(|| key.to_string()),
2296            disk: Box::new(kind.parse()?),
2297        })
2298    }
2299}
2300
2301impl FromStr for DiskCliKind {
2302    type Err = anyhow::Error;
2303
2304    fn from_str(s: &str) -> anyhow::Result<Self> {
2305        let disk = match s.split_once(':') {
2306            // convenience support for passing bare paths as file disks
2307            None => {
2308                let FileOpts {
2309                    path,
2310                    create_with_len,
2311                    direct,
2312                } = parse_file_opts(s)?;
2313                DiskCliKind::File {
2314                    path,
2315                    create_with_len,
2316                    direct,
2317                }
2318            }
2319            Some((kind, arg)) => match kind {
2320                "mem" => DiskCliKind::Memory(parse_memory(arg)?),
2321                "memdiff" => DiskCliKind::MemoryDiff(Box::new(arg.parse()?)),
2322                "sql" => {
2323                    let FileOpts {
2324                        path,
2325                        create_with_len,
2326                        direct,
2327                    } = parse_file_opts(arg)?;
2328                    if direct {
2329                        anyhow::bail!("'direct' is not supported for 'sql' disks");
2330                    }
2331                    DiskCliKind::Sqlite {
2332                        path,
2333                        create_with_len,
2334                    }
2335                }
2336                "sqldiff" => {
2337                    let (path_and_opts, kind) =
2338                        arg.split_once(':').context("expected path[;opts]:kind")?;
2339                    let disk = Box::new(kind.parse()?);
2340                    match path_and_opts.split_once(';') {
2341                        Some((path, create)) => {
2342                            if create != "create" {
2343                                anyhow::bail!("invalid syntax after ';', expected 'create'")
2344                            }
2345                            DiskCliKind::SqliteDiff {
2346                                path: path.into(),
2347                                create: true,
2348                                disk,
2349                            }
2350                        }
2351                        None => DiskCliKind::SqliteDiff {
2352                            path: path_and_opts.into(),
2353                            create: false,
2354                            disk,
2355                        },
2356                    }
2357                }
2358                "autocache" => {
2359                    Self::parse_autocache(arg, std::env::var("OPENVMM_AUTO_CACHE_PATH"))?
2360                }
2361                "prwrap" => DiskCliKind::PersistentReservationsWrapper(Box::new(arg.parse()?)),
2362                "delay" => {
2363                    let (delay_ms, kind) = arg.split_once(':').context("expected delay_ms:kind")?;
2364                    DiskCliKind::DelayDiskWrapper {
2365                        delay_ms: delay_ms.parse().context("invalid disk delay")?,
2366                        disk: Box::new(kind.parse()?),
2367                    }
2368                }
2369                "file" => {
2370                    let FileOpts {
2371                        path,
2372                        create_with_len,
2373                        direct,
2374                    } = parse_file_opts(arg)?;
2375                    DiskCliKind::File {
2376                        path,
2377                        create_with_len,
2378                        direct,
2379                    }
2380                }
2381                "blob" => {
2382                    let (blob_kind, url) = arg.split_once(':').context("expected kind:url")?;
2383                    let blob_kind = match blob_kind {
2384                        "flat" => BlobKind::Flat,
2385                        "vhd1" => BlobKind::Vhd1,
2386                        _ => anyhow::bail!("unknown blob kind {blob_kind}"),
2387                    };
2388                    DiskCliKind::Blob {
2389                        kind: blob_kind,
2390                        url: url.to_string(),
2391                    }
2392                }
2393                "crypt" => {
2394                    let (cipher, (key, kind)) = arg
2395                        .split_once(':')
2396                        .and_then(|(cipher, arg)| Some((cipher, arg.split_once(':')?)))
2397                        .context("expected cipher:key_file:kind")?;
2398                    DiskCliKind::Crypt {
2399                        cipher: ValueEnum::from_str(cipher, false)
2400                            .map_err(|err| anyhow::anyhow!("invalid cipher: {err}"))?,
2401                        key_file: PathBuf::from(key),
2402                        disk: Box::new(kind.parse()?),
2403                    }
2404                }
2405                kind => {
2406                    // here's a fun edge case: what if the user passes `--disk d:\path\to\disk.img`?
2407                    //
2408                    // in this case, we actually want to treat that leading `d:` as part of the
2409                    // path, rather than as a disk with `kind == 'd'`
2410                    let FileOpts {
2411                        path,
2412                        create_with_len,
2413                        direct,
2414                    } = parse_file_opts(s)?;
2415                    if path.has_root() {
2416                        DiskCliKind::File {
2417                            path,
2418                            create_with_len,
2419                            direct,
2420                        }
2421                    } else {
2422                        anyhow::bail!("invalid disk kind {kind}");
2423                    }
2424                }
2425            },
2426        };
2427        Ok(disk)
2428    }
2429}
2430
2431/// Wire transport selection for `--rpc`.
2432#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2433pub enum RpcTransportCli {
2434    /// Auto-detect ttrpc vs. gRPC per connection, based on the first byte of
2435    /// the stream.
2436    #[default]
2437    Auto,
2438    /// Accept ttrpc clients only.
2439    Ttrpc,
2440    /// Accept gRPC clients only.
2441    Grpc,
2442}
2443
2444/// RPC server configuration parsed from `--rpc`.
2445#[derive(Clone, Debug, PartialEq, Eq)]
2446pub struct RpcCli {
2447    /// Unix socket path to listen on.
2448    pub path: PathBuf,
2449    /// Wire transport to accept.
2450    pub transport: RpcTransportCli,
2451}
2452
2453impl FromStr for RpcCli {
2454    type Err = anyhow::Error;
2455
2456    fn from_str(s: &str) -> anyhow::Result<Self> {
2457        let mut path = None;
2458        let mut transport = None;
2459        for part in s.split(',') {
2460            let (key, value) = part
2461                .split_once('=')
2462                .with_context(|| format!("invalid rpc option '{part}', expected key=value"))?;
2463            match key {
2464                "path" => {
2465                    anyhow::ensure!(path.is_none(), "duplicate option 'path'");
2466                    anyhow::ensure!(!value.is_empty(), "'path' requires a value");
2467                    path = Some(PathBuf::from(value));
2468                }
2469                "transport" => {
2470                    anyhow::ensure!(transport.is_none(), "duplicate option 'transport'");
2471                    transport = Some(match value {
2472                        "auto" => RpcTransportCli::Auto,
2473                        "ttrpc" => RpcTransportCli::Ttrpc,
2474                        "grpc" => RpcTransportCli::Grpc,
2475                        _ => anyhow::bail!(
2476                            "invalid transport '{value}', expected auto, ttrpc, or grpc"
2477                        ),
2478                    });
2479                }
2480                _ => anyhow::bail!("unknown rpc option '{key}'"),
2481            }
2482        }
2483
2484        Ok(RpcCli {
2485            path: path.context("'path' is required")?,
2486            transport: transport.unwrap_or_default(),
2487        })
2488    }
2489}
2490
2491#[derive(Clone)]
2492pub struct VmgsCli {
2493    pub kind: DiskCliKind,
2494    pub provision: ProvisionCondition,
2495}
2496
2497#[derive(Copy, Clone)]
2498pub enum ProvisionCondition {
2499    OnEmpty,
2500    OnFailure,
2501    Single,
2502}
2503
2504impl FromStr for VmgsCli {
2505    type Err = anyhow::Error;
2506
2507    fn from_str(s: &str) -> anyhow::Result<Self> {
2508        let (kind, opt) = s
2509            .split_once(',')
2510            .map(|(k, o)| (k, Some(o)))
2511            .unwrap_or((s, None));
2512        let kind = kind.parse()?;
2513
2514        let provision = match opt {
2515            None => ProvisionCondition::OnEmpty,
2516            Some("fmt-on-fail") => ProvisionCondition::OnFailure,
2517            Some("fmt") => ProvisionCondition::Single,
2518            Some(opt) => anyhow::bail!("unknown option: '{opt}'"),
2519        };
2520
2521        Ok(VmgsCli { kind, provision })
2522    }
2523}
2524
2525/// VNC server configuration options.
2526#[derive(clap::Args)]
2527pub struct VncCli {
2528    /// Listen for VNC connections. Implied by --gfx.
2529    #[clap(long)]
2530    pub vnc: bool,
2531
2532    /// VNC port number
2533    #[clap(long, value_name = "PORT", default_value = "5900")]
2534    pub vnc_port: u16,
2535
2536    /// VNC listen address (use 0.0.0.0 for all IPv4, :: for dual-stack IPv4+IPv6).
2537    /// Accepts a bare IP address (combined with --vnc-port) or a full socket
2538    /// address like [::1]:5900 (overrides --vnc-port).
2539    #[clap(long, value_name = "ADDRESS", default_value = "127.0.0.1")]
2540    pub vnc_listen: String,
2541
2542    /// Maximum concurrent VNC clients (~8MB memory per client for framebuffer buffers)
2543    #[clap(long, value_name = "COUNT", default_value = "16")]
2544    pub vnc_max_clients: usize,
2545
2546    /// When the client limit is reached, disconnect the oldest client
2547    /// instead of rejecting the new connection
2548    #[clap(long)]
2549    pub vnc_evict_oldest: bool,
2550}
2551
2552// <kind>[,ro]
2553#[derive(Clone)]
2554pub struct DiskCli {
2555    pub vtl: DeviceVtl,
2556    pub kind: DiskCliKind,
2557    pub read_only: bool,
2558    pub is_dvd: bool,
2559    pub underhill: Option<UnderhillDiskSource>,
2560    pub pcie_port: Option<String>,
2561    pub serial: Option<String>,
2562    pub num_queues: Option<u16>,
2563    pub controller: Option<String>,
2564    pub nsid: Option<u32>,
2565    pub lun: Option<u8>,
2566    pub relay: Option<(String, Option<u32>)>,
2567}
2568
2569#[derive(Copy, Clone)]
2570pub enum UnderhillDiskSource {
2571    Scsi,
2572    Nvme,
2573}
2574
2575/// A `relay=<name>[:<location>]` target for an OpenHCL-managed controller.
2576struct RelayTarget {
2577    name: String,
2578    location: Option<u32>,
2579}
2580
2581impl FromStr for RelayTarget {
2582    type Err = anyhow::Error;
2583
2584    fn from_str(s: &str) -> anyhow::Result<Self> {
2585        Ok(if let Some((name, loc)) = s.split_once(':') {
2586            RelayTarget {
2587                name: name.to_string(),
2588                location: Some(loc.parse::<u32>().context("invalid relay location")?),
2589            }
2590        } else {
2591            RelayTarget {
2592                name: s.to_string(),
2593                location: None,
2594            }
2595        })
2596    }
2597}
2598
2599/// Raw `--disk`/`--nvme`/`--virtio-blk` options, resolved and validated into a
2600/// [`DiskCli`] by its `FromStr`.
2601#[derive(vmm_cli::KeyValueArgs)]
2602struct DiskArgs {
2603    #[kv(positional)]
2604    kind: DiskCliKind,
2605    #[kv(flag)]
2606    ro: bool,
2607    #[kv(flag)]
2608    dvd: bool,
2609    #[kv(flag, key = "vtl2", present = DeviceVtl::Vtl2, absent = DeviceVtl::Vtl0)]
2610    vtl: DeviceVtl,
2611    #[kv(flag)]
2612    uh: bool,
2613    #[kv(flag, key = "uh-nvme")]
2614    uh_nvme: bool,
2615    pcie_port: Option<String>,
2616    serial: Option<String>,
2617    num_queues: Option<u16>,
2618    #[kv(key = "on")]
2619    controller: Option<String>,
2620    nsid: Option<u32>,
2621    lun: Option<u8>,
2622    relay: Option<RelayTarget>,
2623}
2624
2625impl FromStr for DiskCli {
2626    type Err = anyhow::Error;
2627
2628    fn from_str(s: &str) -> anyhow::Result<Self> {
2629        let args: DiskArgs = s.parse()?;
2630
2631        let underhill = match (args.uh, args.uh_nvme) {
2632            (false, false) => None,
2633            (true, false) => Some(UnderhillDiskSource::Scsi),
2634            (false, true) => Some(UnderhillDiskSource::Nvme),
2635            (true, true) => anyhow::bail!("`uh` and `uh-nvme` are mutually exclusive"),
2636        };
2637        let read_only = args.ro || args.dvd;
2638        let is_dvd = args.dvd;
2639        let vtl = args.vtl;
2640        let pcie_port = args.pcie_port;
2641        let serial = args.serial;
2642        let num_queues = args.num_queues;
2643        let controller = args.controller;
2644        let nsid = args.nsid;
2645        let lun = args.lun;
2646        let relay = args.relay.map(|r| (r.name, r.location));
2647
2648        if num_queues.is_some_and(|count| !(1..=256).contains(&count)) {
2649            anyhow::bail!("`num_queues` must be between 1 and 256");
2650        }
2651
2652        if serial.as_ref().is_some_and(|serial| {
2653            serial.bytes().any(|byte| {
2654                !(byte.is_ascii_graphic() || byte == b' ') || matches!(byte, b'[' | b']')
2655            })
2656        }) {
2657            anyhow::bail!("`serial` must contain only printable ASCII characters and no brackets");
2658        }
2659
2660        if underhill.is_some() && vtl != DeviceVtl::Vtl0 {
2661            anyhow::bail!("`uh` or `uh-nvme` is incompatible with `vtl2`");
2662        }
2663
2664        if pcie_port.is_some() && (underhill.is_some() || vtl != DeviceVtl::Vtl0 || is_dvd) {
2665            anyhow::bail!("`pcie_port` is incompatible with `uh`, `uh-nvme`, `vtl2`, and `dvd`");
2666        }
2667
2668        if controller.is_some() && pcie_port.is_some() {
2669            anyhow::bail!("`on` is incompatible with `pcie_port`");
2670        }
2671
2672        if controller.is_some() && vtl != DeviceVtl::Vtl0 {
2673            anyhow::bail!(
2674                "`vtl2` is incompatible with `on`; the controller's VTL determines placement"
2675            );
2676        }
2677
2678        if controller.is_some() && underhill.is_some() {
2679            anyhow::bail!("`on` is incompatible with `uh` and `uh-nvme`; use `relay` instead");
2680        }
2681
2682        if nsid.is_some() && controller.is_none() {
2683            anyhow::bail!("`nsid` requires `on`");
2684        }
2685
2686        if lun.is_some() && controller.is_none() {
2687            anyhow::bail!("`lun` requires `on`");
2688        }
2689
2690        if nsid.is_some() && lun.is_some() {
2691            anyhow::bail!("`nsid` and `lun` are mutually exclusive");
2692        }
2693
2694        if relay.is_some() && controller.is_none() {
2695            anyhow::bail!("`relay` requires `on`");
2696        }
2697
2698        if relay.is_some() && underhill.is_some() {
2699            anyhow::bail!("`relay` is incompatible with `uh` and `uh-nvme`");
2700        }
2701
2702        Ok(DiskCli {
2703            vtl,
2704            kind: args.kind,
2705            read_only,
2706            is_dvd,
2707            underhill,
2708            pcie_port,
2709            serial,
2710            num_queues,
2711            controller,
2712            nsid,
2713            lun,
2714            relay,
2715        })
2716    }
2717}
2718
2719/// The transport for a named NVMe controller.
2720#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueGroup)]
2721pub enum NvmeControllerTransport {
2722    /// Present via PCIe on the specified root port.
2723    #[kv(key = "pcie_port")]
2724    Pcie(String),
2725    /// Present via VPCI with an optional instance GUID.
2726    #[kv(key = "vpci")]
2727    Vpci(Option<Guid>),
2728}
2729
2730/// CLI arguments for a named NVMe controller.
2731#[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
2732pub struct NvmeControllerCli {
2733    /// Controller name, referenced by `--disk on=<name>`.
2734    pub id: String,
2735    /// Transport configuration.
2736    #[kv(flatten)]
2737    pub transport: NvmeControllerTransport,
2738    /// VTL assignment (default VTL0).
2739    #[kv(flag, key = "vtl2", present = DeviceVtl::Vtl2, absent = DeviceVtl::Vtl0)]
2740    pub vtl: DeviceVtl,
2741}
2742
2743/// CLI arguments for a named VMBus SCSI controller.
2744#[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
2745pub struct ScsiControllerCli {
2746    /// Controller name, referenced by `--disk on=<name>`.
2747    pub id: String,
2748    /// Number of sub-channels.
2749    #[kv(default)]
2750    pub sub_channels: u16,
2751    /// VTL assignment (default VTL0).
2752    #[kv(flag, key = "vtl2", present = DeviceVtl::Vtl2, absent = DeviceVtl::Vtl0)]
2753    pub vtl: DeviceVtl,
2754}
2755
2756/// Protocol type for an OpenHCL-managed controller.
2757#[derive(Copy, Clone, Debug, PartialEq)]
2758pub enum OpenhclControllerType {
2759    Scsi,
2760    Nvme,
2761}
2762
2763/// CLI arguments for an OpenHCL-managed storage controller (relay target).
2764#[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
2765pub struct OpenhclControllerCli {
2766    /// Controller name, referenced by `--disk ... relay=<name>`.
2767    pub id: String,
2768    /// Controller protocol.
2769    #[kv(key = "type")]
2770    pub controller_type: OpenhclControllerType,
2771    /// Instance GUID (auto-derived from name if omitted).
2772    pub guid: Option<Guid>,
2773}
2774
2775impl FromStr for OpenhclControllerType {
2776    type Err = anyhow::Error;
2777
2778    fn from_str(s: &str) -> anyhow::Result<Self> {
2779        Ok(match s {
2780            "scsi" => OpenhclControllerType::Scsi,
2781            "nvme" => OpenhclControllerType::Nvme,
2782            other => anyhow::bail!("unknown controller type: '{other}'"),
2783        })
2784    }
2785}
2786
2787/// CLI arguments for a CXL Type-3 test endpoint.
2788#[derive(Clone, Debug, PartialEq)]
2789pub struct CxlTestDeviceCli {
2790    /// Size of HDM memory the test device should expose and back.
2791    pub hdm_size: u64,
2792    /// PCIe root port name where the device is attached.
2793    pub pcie_port: String,
2794}
2795
2796impl FromStr for CxlTestDeviceCli {
2797    type Err = anyhow::Error;
2798
2799    fn from_str(s: &str) -> anyhow::Result<Self> {
2800        let mut opts = s.split(',');
2801        let first = opts.next().context("expected CXL test device config")?;
2802        let (kind, arg) = first
2803            .split_once(':')
2804            .context("expected CXL test syntax: mem:<len>")?;
2805
2806        if kind != "mem" {
2807            anyhow::bail!("unsupported CXL test backing kind '{kind}', expected 'mem'");
2808        }
2809
2810        let hdm_size = parse_memory(arg).context("failed to parse CXL test HDM size")?;
2811        let mut pcie_port = None;
2812
2813        for opt in opts {
2814            let mut kv = opt.split('=');
2815            let key = kv.next().unwrap_or_default();
2816            match key {
2817                "pcie_port" => {
2818                    let val = kv.next();
2819                    if val.is_none_or(|v| v.is_empty()) {
2820                        anyhow::bail!("`pcie_port` requires a port name");
2821                    }
2822                    pcie_port = Some(val.unwrap().to_string());
2823                }
2824                _ => anyhow::bail!("unknown option: '{opt}'"),
2825            }
2826        }
2827
2828        let Some(pcie_port) = pcie_port else {
2829            anyhow::bail!("`pcie_port=<name>` is required for `--cxl-test`");
2830        };
2831
2832        Ok(Self {
2833            hdm_size,
2834            pcie_port,
2835        })
2836    }
2837}
2838
2839// <kind>[,ro,s]
2840#[derive(Clone)]
2841pub struct IdeDiskCli {
2842    pub kind: DiskCliKind,
2843    pub read_only: bool,
2844    pub channel: Option<u8>,
2845    pub device: Option<u8>,
2846    pub is_dvd: bool,
2847}
2848
2849impl FromStr for IdeDiskCli {
2850    type Err = anyhow::Error;
2851
2852    fn from_str(s: &str) -> anyhow::Result<Self> {
2853        let mut opts = s.split(',');
2854        let kind = opts.next().unwrap().parse()?;
2855
2856        let mut read_only = false;
2857        let mut channel = None;
2858        let mut device = None;
2859        let mut is_dvd = false;
2860        for opt in opts {
2861            let mut s = opt.split('=');
2862            let opt = s.next().unwrap();
2863            match opt {
2864                "ro" => read_only = true,
2865                "p" => channel = Some(0),
2866                "s" => channel = Some(1),
2867                "0" => device = Some(0),
2868                "1" => device = Some(1),
2869                "dvd" => {
2870                    is_dvd = true;
2871                    read_only = true;
2872                }
2873                _ => anyhow::bail!("unknown option: '{opt}'"),
2874            }
2875        }
2876
2877        Ok(IdeDiskCli {
2878            kind,
2879            read_only,
2880            channel,
2881            device,
2882            is_dvd,
2883        })
2884    }
2885}
2886
2887// <kind>[,ro]
2888#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueArgs)]
2889pub struct FloppyDiskCli {
2890    #[kv(positional)]
2891    pub kind: DiskCliKind,
2892    #[kv(flag, key = "ro")]
2893    pub read_only: bool,
2894}
2895
2896#[derive(Clone)]
2897pub struct DebugconSerialConfigCli {
2898    pub port: u16,
2899    pub serial: SerialConfigCli,
2900}
2901
2902impl FromStr for DebugconSerialConfigCli {
2903    type Err = String;
2904
2905    fn from_str(s: &str) -> Result<Self, Self::Err> {
2906        let Some((port, serial)) = s.split_once(',') else {
2907            return Err("invalid format (missing comma between port and serial)".into());
2908        };
2909
2910        let port: u16 = parse_number(port)
2911            .map_err(|_| "could not parse port".to_owned())?
2912            .try_into()
2913            .map_err(|_| "port must be 16-bit")?;
2914        let serial: SerialConfigCli = serial.parse()?;
2915
2916        Ok(Self { port, serial })
2917    }
2918}
2919
2920/// A COM port binding, optionally prefixed with `debugger-mode:` to run the
2921/// port in debugger mode for WinDbg / KD-over-serial.
2922#[derive(Clone, Debug, PartialEq)]
2923pub struct ComSerialConfigCli {
2924    /// Whether this COM port runs in debugger mode (for WinDbg / KD-over-serial).
2925    pub debugger_mode: bool,
2926    /// The serial backend for this COM port.
2927    pub backend: SerialConfigCli,
2928}
2929
2930impl FromStr for ComSerialConfigCli {
2931    type Err = String;
2932
2933    fn from_str(s: &str) -> Result<Self, Self::Err> {
2934        match s.strip_prefix("debugger-mode:") {
2935            Some(rest) => Ok(Self {
2936                debugger_mode: true,
2937                backend: rest.parse()?,
2938            }),
2939            None => Ok(Self {
2940                debugger_mode: false,
2941                backend: s.parse()?,
2942            }),
2943        }
2944    }
2945}
2946
2947/// (console | stderr | listen=\<path\> | file=\<path\> (overwrites) | listen=tcp:\<ip\>:\<port\> | term[=\<program\>]\[,name=\<windowtitle\>\] | null | none)
2948#[derive(Clone, Debug, PartialEq)]
2949pub enum SerialConfigCli {
2950    None,
2951    Null,
2952    Console,
2953    NewConsole(Option<PathBuf>, Option<String>),
2954    Stderr,
2955    Pipe(PathBuf),
2956    Tcp(SocketAddr),
2957    File(PathBuf),
2958}
2959
2960impl FromStr for SerialConfigCli {
2961    type Err = String;
2962
2963    fn from_str(s: &str) -> Result<Self, Self::Err> {
2964        let keyvalues = SerialConfigCli::parse_keyvalues(s)?;
2965
2966        let first_key = match keyvalues.first() {
2967            Some(first_pair) => first_pair.0.as_str(),
2968            None => Err("invalid serial configuration: no values supplied")?,
2969        };
2970        let first_value = keyvalues.first().unwrap().1.as_ref();
2971
2972        let ret = match first_key {
2973            "none" => SerialConfigCli::None,
2974            "null" => SerialConfigCli::Null,
2975            "console" => SerialConfigCli::Console,
2976            "stderr" => SerialConfigCli::Stderr,
2977            "file" => match first_value {
2978                Some(path) => SerialConfigCli::File(path.into()),
2979                None => Err("invalid serial configuration: file requires a value")?,
2980            },
2981            "term" => {
2982                // If user supplies a name key, use it to title the window
2983                let window_name = keyvalues.iter().find(|(key, _)| key == "name");
2984                let window_name = match window_name {
2985                    Some((_, Some(name))) => Some(name.clone()),
2986                    _ => None,
2987                };
2988
2989                SerialConfigCli::NewConsole(first_value.map(|p| p.into()), window_name)
2990            }
2991            "listen" => match first_value {
2992                Some(path) if let Some(tcp) = path.strip_prefix("tcp:") => {
2993                    let addr = tcp
2994                        .parse()
2995                        .map_err(|err| format!("invalid tcp address: {err}"))?;
2996                    SerialConfigCli::Tcp(addr)
2997                }
2998                Some(path) => SerialConfigCli::Pipe(path.into()),
2999                None => Err(
3000                    "invalid serial configuration: listen requires a value of tcp:addr or pipe",
3001                )?,
3002            },
3003            _ => {
3004                return Err(format!(
3005                    "invalid serial configuration: '{}' is not a known option",
3006                    first_key
3007                ));
3008            }
3009        };
3010
3011        Ok(ret)
3012    }
3013}
3014
3015impl SerialConfigCli {
3016    /// Parse a comma separated list of key=value options into a vector of
3017    /// key/value pairs.
3018    fn parse_keyvalues(s: &str) -> Result<Vec<(String, Option<String>)>, String> {
3019        let mut ret = Vec::new();
3020
3021        // For each comma separated item in the supplied list
3022        for item in s.split(',') {
3023            // Split on the = for key and value
3024            // If no = is found, treat key as key and value as None
3025            let mut eqsplit = item.split('=');
3026            let key = eqsplit.next();
3027            let value = eqsplit.next();
3028
3029            if let Some(key) = key {
3030                ret.push((key.to_owned(), value.map(|x| x.to_owned())));
3031            } else {
3032                // An empty key is invalid
3033                return Err("invalid key=value pair in serial config".into());
3034            }
3035        }
3036        Ok(ret)
3037    }
3038}
3039
3040#[derive(Clone, Debug, PartialEq)]
3041pub enum EndpointConfigCli {
3042    None,
3043    Consomme {
3044        cidr: Option<String>,
3045        host_fwd: Vec<HostPortConfigCli>,
3046    },
3047    Dio {
3048        id: Option<String>,
3049    },
3050    Tap {
3051        name: String,
3052    },
3053}
3054
3055/// Parsed host port forwarding configuration from the CLI.
3056#[derive(Clone, Debug, PartialEq)]
3057pub struct HostPortConfigCli {
3058    pub protocol: HostPortProtocolCli,
3059    pub host_address: Option<std::net::IpAddr>,
3060    pub host_port: u16,
3061    pub guest_port: u16,
3062}
3063
3064/// Protocol for host port forwarding.
3065#[derive(Clone, Debug, PartialEq)]
3066pub enum HostPortProtocolCli {
3067    Tcp,
3068    Udp,
3069}
3070
3071fn parse_hostfwd(s: &str) -> Result<HostPortConfigCli, String> {
3072    // Format: protocol:[hostaddr]:hostport-[guestaddr]:guestport
3073    // Examples: "tcp::3389-:3389", "tcp:127.0.0.1:8080-:80", "tcp:[::1]:8080-:80"
3074    let (host_part, guest_part) = s.split_once('-').ok_or_else(|| {
3075        format!(
3076            "invalid hostfwd format '{s}', \
3077             expected 'proto:[hostaddr]:hostport-[guestaddr]:guestport'"
3078        )
3079    })?;
3080
3081    // Extract protocol from host part (first colon-delimited field)
3082    let (proto, host_addr_port) = host_part.split_once(':').ok_or_else(|| {
3083        format!("invalid hostfwd host part '{host_part}', expected 'proto:[hostaddr]:hostport'")
3084    })?;
3085    let protocol = match proto {
3086        "tcp" => HostPortProtocolCli::Tcp,
3087        "udp" => HostPortProtocolCli::Udp,
3088        other => {
3089            return Err(format!(
3090                "unknown hostfwd protocol '{other}', expected 'tcp' or 'udp'"
3091            ));
3092        }
3093    };
3094
3095    let (host_address, host_port) = parse_addr_port(host_addr_port)
3096        .map_err(|e| format!("invalid hostfwd host address/port: {e}"))?;
3097    let (_, guest_port) = parse_addr_port(guest_part)
3098        .map_err(|e| format!("invalid hostfwd guest address/port: {e}"))?;
3099
3100    Ok(HostPortConfigCli {
3101        protocol,
3102        host_address,
3103        host_port,
3104        guest_port,
3105    })
3106}
3107
3108/// Parse an address-port pair in one of these forms:
3109/// - `[ipv6addr]:port`
3110/// - `addr:port`
3111/// - `:port`  (empty address)
3112/// - `port`   (no address)
3113fn parse_addr_port(s: &str) -> Result<(Option<std::net::IpAddr>, u16), String> {
3114    if let Some(rest) = s.strip_prefix('[') {
3115        // Bracketed IPv6 address: [addr]:port
3116        let (addr, port) = rest
3117            .split_once("]:")
3118            .ok_or_else(|| format!("expected '[addr]:port', got '[{rest}'"))?;
3119        let port: u16 = port.parse().map_err(|_| format!("invalid port '{port}'"))?;
3120        let addr: std::net::IpAddr = addr
3121            .parse()
3122            .map_err(|e| format!("invalid address '{addr}': {e}"))?;
3123        Ok((Some(addr), port))
3124    } else {
3125        match s.rsplit_once(':') {
3126            Some((addr, port)) => {
3127                let port: u16 = port.parse().map_err(|_| format!("invalid port '{port}'"))?;
3128                let addr = if addr.is_empty() {
3129                    None
3130                } else {
3131                    let parsed: std::net::IpAddr = addr
3132                        .parse()
3133                        .map_err(|e| format!("invalid address '{addr}': {e}"))?;
3134                    Some(parsed)
3135                };
3136                Ok((addr, port))
3137            }
3138            None => {
3139                let port: u16 = s.parse().map_err(|_| format!("invalid port '{s}'"))?;
3140                Ok((None, port))
3141            }
3142        }
3143    }
3144}
3145
3146impl FromStr for EndpointConfigCli {
3147    type Err = String;
3148
3149    fn from_str(s: &str) -> Result<Self, Self::Err> {
3150        let ret = match s.split(':').collect::<Vec<_>>().as_slice() {
3151            ["none"] => EndpointConfigCli::None,
3152            ["consomme", rest @ ..] => {
3153                let remaining = rest.join(":");
3154                let mut cidr = None;
3155                let mut host_fwd = Vec::new();
3156                for opt in remaining.split(',').filter(|s| !s.is_empty()) {
3157                    if let Some(fwd) = opt.strip_prefix("hostfwd=") {
3158                        host_fwd.push(parse_hostfwd(fwd)?);
3159                    } else if cidr.is_none() {
3160                        cidr = Some(opt.to_owned());
3161                    } else {
3162                        return Err(format!("unexpected consomme option '{opt}'"));
3163                    }
3164                }
3165                EndpointConfigCli::Consomme { cidr, host_fwd }
3166            }
3167            ["dio", s @ ..] => EndpointConfigCli::Dio {
3168                id: s.first().map(|s| (*s).to_owned()),
3169            },
3170            ["tap", name] => EndpointConfigCli::Tap {
3171                name: (*name).to_owned(),
3172            },
3173            _ => return Err("invalid network backend".into()),
3174        };
3175
3176        Ok(ret)
3177    }
3178}
3179
3180#[derive(Clone, Debug, PartialEq)]
3181pub struct NicConfigCli {
3182    pub vtl: DeviceVtl,
3183    pub endpoint: EndpointConfigCli,
3184    /// MAC address to expose to the guest. A random address is used if omitted.
3185    pub mac_address: Option<MacAddress>,
3186    pub max_queues: Option<u16>,
3187    pub enable_rx_gso: bool,
3188    pub underhill: bool,
3189    pub pcie_port: Option<String>,
3190}
3191
3192impl FromStr for NicConfigCli {
3193    type Err = String;
3194
3195    fn from_str(mut s: &str) -> Result<Self, Self::Err> {
3196        let mut vtl = DeviceVtl::Vtl0;
3197        let mut mac_address = None;
3198        let mut max_queues = None;
3199        let mut enable_rx_gso = false;
3200        let mut underhill = false;
3201        let mut pcie_port = None;
3202        while let Some((opt, rest)) = s.split_once(':') {
3203            if let Some((opt, val)) = opt.split_once('=') {
3204                match opt {
3205                    "queues" => {
3206                        max_queues = Some(val.parse().map_err(|_| "failed to parse queue count")?);
3207                    }
3208                    "mac" => {
3209                        mac_address = Some(val.parse().map_err(|_| "failed to parse MAC address")?);
3210                    }
3211                    "pcie_port" => {
3212                        if val.is_empty() {
3213                            return Err("`pcie_port=` requires port name argument".into());
3214                        }
3215                        pcie_port = Some(val.to_string());
3216                    }
3217                    _ => break,
3218                }
3219            } else {
3220                match opt {
3221                    "vtl2" => {
3222                        vtl = DeviceVtl::Vtl2;
3223                    }
3224                    "uh" => underhill = true,
3225                    "rx_gso" => enable_rx_gso = true,
3226                    _ => break,
3227                }
3228            }
3229            s = rest;
3230        }
3231
3232        if underhill && vtl != DeviceVtl::Vtl0 {
3233            return Err("`uh` is incompatible with `vtl2`".into());
3234        }
3235
3236        if pcie_port.is_some() && (underhill || vtl != DeviceVtl::Vtl0) {
3237            return Err("`pcie_port` is incompatible with `uh` and `vtl2`".into());
3238        }
3239
3240        let endpoint = s.parse()?;
3241        Ok(NicConfigCli {
3242            vtl,
3243            endpoint,
3244            mac_address,
3245            max_queues,
3246            enable_rx_gso,
3247            underhill,
3248            pcie_port,
3249        })
3250    }
3251}
3252
3253#[derive(Debug, Error)]
3254#[error("unknown VTL2 relocation type: {0}")]
3255pub struct UnknownVtl2RelocationType(String);
3256
3257fn parse_vtl2_relocation(s: &str) -> Result<Vtl2BaseAddressType, UnknownVtl2RelocationType> {
3258    match s {
3259        "disable" => Ok(Vtl2BaseAddressType::File),
3260        s if s.starts_with("auto=") => {
3261            let s = s.strip_prefix("auto=").unwrap_or_default();
3262            let size = if s == "filesize" {
3263                None
3264            } else {
3265                let size = parse_memory(s).map_err(|e| {
3266                    UnknownVtl2RelocationType(format!(
3267                        "unable to parse memory size from {} for 'auto=' type, {e}",
3268                        e
3269                    ))
3270                })?;
3271                Some(size)
3272            };
3273            Ok(Vtl2BaseAddressType::MemoryLayout { size })
3274        }
3275        s if s.starts_with("absolute=") => {
3276            let s = s.strip_prefix("absolute=");
3277            let addr = parse_number(s.unwrap_or_default()).map_err(|e| {
3278                UnknownVtl2RelocationType(format!(
3279                    "unable to parse number from {} for 'absolute=' type",
3280                    e
3281                ))
3282            })?;
3283            Ok(Vtl2BaseAddressType::Absolute(addr))
3284        }
3285        s if s.starts_with("vtl2=") => {
3286            let s = s.strip_prefix("vtl2=").unwrap_or_default();
3287            let size = if s == "filesize" {
3288                None
3289            } else {
3290                let size = parse_memory(s).map_err(|e| {
3291                    UnknownVtl2RelocationType(format!(
3292                        "unable to parse memory size from {} for 'vtl2=' type, {e}",
3293                        e
3294                    ))
3295                })?;
3296                Some(size)
3297            };
3298            Ok(Vtl2BaseAddressType::Vtl2Allocate { size })
3299        }
3300        _ => Err(UnknownVtl2RelocationType(s.to_owned())),
3301    }
3302}
3303
3304#[derive(Debug, Copy, Clone, PartialEq)]
3305pub enum SmtConfigCli {
3306    Auto,
3307    Force,
3308    Off,
3309}
3310
3311#[derive(Debug, Error)]
3312#[error("expected auto, force, or off")]
3313pub struct BadSmtConfig;
3314
3315impl FromStr for SmtConfigCli {
3316    type Err = BadSmtConfig;
3317
3318    fn from_str(s: &str) -> Result<Self, Self::Err> {
3319        let r = match s {
3320            "auto" => Self::Auto,
3321            "force" => Self::Force,
3322            "off" => Self::Off,
3323            _ => return Err(BadSmtConfig),
3324        };
3325        Ok(r)
3326    }
3327}
3328
3329#[cfg_attr(not(guest_arch = "x86_64"), expect(dead_code))]
3330fn parse_x2apic(s: &str) -> Result<X2ApicConfig, &'static str> {
3331    let r = match s {
3332        "auto" => X2ApicConfig::Auto,
3333        "supported" => X2ApicConfig::Supported,
3334        "off" => X2ApicConfig::Unsupported,
3335        "on" => X2ApicConfig::Enabled,
3336        _ => return Err("expected auto, supported, off, or on"),
3337    };
3338    Ok(r)
3339}
3340
3341#[derive(Debug, Copy, Clone, ValueEnum)]
3342pub enum Vtl0LateMapPolicyCli {
3343    Off,
3344    Log,
3345    Halt,
3346    Exception,
3347}
3348
3349/// PCIe MSI controller selection for aarch64.
3350#[derive(Debug, Copy, Clone, Default, ValueEnum)]
3351pub enum GicMsiCli {
3352    /// Use ITS when available, fall back to GICv2m.
3353    #[default]
3354    Auto,
3355    /// Force GICv3 ITS (LPI-based MSIs).
3356    Its,
3357    /// Force GICv2m (SPI-based MSIs).
3358    V2m,
3359}
3360
3361#[derive(Debug, Copy, Clone, ValueEnum)]
3362pub enum IsolationCli {
3363    Vbs,
3364    Snp,
3365}
3366
3367#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum)]
3368pub enum IgvmPersonalityCli {
3369    /// OpenHCL paravisor hosted in VTL2.
3370    Openhcl,
3371    /// UEFI firmware loaded directly from the IGVM.
3372    Uefi,
3373    /// Linux kernel loaded directly from the IGVM.
3374    LinuxDirect,
3375}
3376
3377impl FromStr for IgvmPersonalityCli {
3378    type Err = String;
3379
3380    fn from_str(value: &str) -> Result<Self, Self::Err> {
3381        ValueEnum::from_str(value, false)
3382    }
3383}
3384
3385#[derive(Debug, Copy, Clone, PartialEq)]
3386pub struct PcatBootOrderCli(pub [PcatBootDevice; 4]);
3387
3388impl FromStr for PcatBootOrderCli {
3389    type Err = &'static str;
3390
3391    fn from_str(s: &str) -> Result<Self, Self::Err> {
3392        let mut default_order = DEFAULT_PCAT_BOOT_ORDER.map(Some);
3393        let mut order = Vec::new();
3394
3395        for item in s.split(',') {
3396            let device = match item {
3397                "optical" => PcatBootDevice::Optical,
3398                "hdd" => PcatBootDevice::HardDrive,
3399                "net" => PcatBootDevice::Network,
3400                "floppy" => PcatBootDevice::Floppy,
3401                _ => return Err("unknown boot device type"),
3402            };
3403
3404            let default_pos = default_order
3405                .iter()
3406                .position(|x| x == &Some(device))
3407                .ok_or("cannot pass duplicate boot devices")?;
3408
3409            order.push(default_order[default_pos].take().unwrap());
3410        }
3411
3412        order.extend(default_order.into_iter().flatten());
3413        assert_eq!(order.len(), 4);
3414
3415        Ok(Self(order.try_into().unwrap()))
3416    }
3417}
3418
3419#[derive(Copy, Clone, Debug, ValueEnum)]
3420pub enum UefiConsoleModeCli {
3421    Default,
3422    Com1,
3423    Com2,
3424    None,
3425}
3426
3427impl FromStr for UefiConsoleModeCli {
3428    type Err = String;
3429
3430    fn from_str(value: &str) -> Result<Self, Self::Err> {
3431        ValueEnum::from_str(value, false)
3432    }
3433}
3434
3435#[derive(Copy, Clone, Debug, Default, ValueEnum)]
3436pub enum EfiDiagnosticsLogLevelCli {
3437    #[default]
3438    Default,
3439    Info,
3440    Full,
3441}
3442
3443impl FromStr for EfiDiagnosticsLogLevelCli {
3444    type Err = String;
3445
3446    fn from_str(value: &str) -> Result<Self, Self::Err> {
3447        ValueEnum::from_str(value, false)
3448    }
3449}
3450
3451#[derive(Clone, Debug, PartialEq)]
3452pub struct PcieRootComplexCli {
3453    pub name: String,
3454    pub segment: u16,
3455    pub start_bus: u8,
3456    pub end_bus: u8,
3457    pub low_mmio: u32,
3458    pub high_mmio: u64,
3459    pub low_mmio_base: Option<u64>,
3460    pub high_mmio_base: Option<u64>,
3461    pub preserve_bars: bool,
3462    pub hdm: u64,
3463    pub hdm_window_restrictions: CfmwsWindowRestrictions,
3464    pub vnode: Option<u32>,
3465}
3466
3467/// A `0x`-prefixed hexadecimal address, used for MMIO base overrides.
3468struct HexAddress(u64);
3469
3470impl FromStr for HexAddress {
3471    type Err = anyhow::Error;
3472
3473    fn from_str(s: &str) -> anyhow::Result<Self> {
3474        Ok(HexAddress(parse_address(s)?))
3475    }
3476}
3477
3478/// A CFMWS window-restrictions bitmask (`0x21` or `33`).
3479struct CfmwsWindowRestrictionsCli(CfmwsWindowRestrictions);
3480
3481impl FromStr for CfmwsWindowRestrictionsCli {
3482    type Err = anyhow::Error;
3483
3484    fn from_str(s: &str) -> anyhow::Result<Self> {
3485        Ok(CfmwsWindowRestrictionsCli(
3486            parse_cxl_cfmws_window_restriction_u16_bitmask(s)?,
3487        ))
3488    }
3489}
3490
3491/// Raw `--pcie-root-complex` options, parsed declaratively. Validated and
3492/// mapped into the public [`PcieRootComplexCli`] by its `FromStr`.
3493#[derive(vmm_cli::KeyValueArgs)]
3494struct PcieRootComplexArgs {
3495    #[kv(positional)]
3496    name: String,
3497    #[kv(default)]
3498    segment: u16,
3499    #[kv(default)]
3500    start_bus: u8,
3501    #[kv(default = 255)]
3502    end_bus: u8,
3503    #[kv(default = vmm_cli::MemorySize(64 * 1024 * 1024))]
3504    low_mmio: vmm_cli::MemorySize,
3505    #[kv(default = vmm_cli::MemorySize(1024 * 1024 * 1024))]
3506    high_mmio: vmm_cli::MemorySize,
3507    low_mmio_base: Option<HexAddress>,
3508    high_mmio_base: Option<HexAddress>,
3509    #[kv(flag)]
3510    preserve_bars: bool,
3511    #[kv(default = vmm_cli::MemorySize(1024 * 1024 * 1024))]
3512    hdm: vmm_cli::MemorySize,
3513    #[kv(default = CfmwsWindowRestrictionsCli(CfmwsWindowRestrictions::DEVICE_COHERENT))]
3514    hdm_window_restrictions: CfmwsWindowRestrictionsCli,
3515    #[kv(key = "node")]
3516    vnode: Option<u32>,
3517}
3518
3519impl FromStr for PcieRootComplexCli {
3520    type Err = anyhow::Error;
3521
3522    fn from_str(s: &str) -> Result<Self, Self::Err> {
3523        let args: PcieRootComplexArgs = s.parse()?;
3524
3525        if args.start_bus > args.end_bus {
3526            anyhow::bail!("start_bus must be <= end_bus");
3527        }
3528
3529        let low_mmio = u32::try_from(args.low_mmio.0).context("low MMIO size exceeds 32 bits")?;
3530
3531        Ok(PcieRootComplexCli {
3532            name: args.name,
3533            segment: args.segment,
3534            start_bus: args.start_bus,
3535            end_bus: args.end_bus,
3536            low_mmio,
3537            high_mmio: args.high_mmio.0,
3538            low_mmio_base: args.low_mmio_base.map(|a| a.0),
3539            high_mmio_base: args.high_mmio_base.map(|a| a.0),
3540            preserve_bars: args.preserve_bars,
3541            hdm: args.hdm.0,
3542            hdm_window_restrictions: args.hdm_window_restrictions.0,
3543            vnode: args.vnode,
3544        })
3545    }
3546}
3547
3548fn parse_cxl_cfmws_window_restriction_u16_bitmask(
3549    s: &str,
3550) -> anyhow::Result<CfmwsWindowRestrictions> {
3551    let bits = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
3552        u16::from_str_radix(hex, 16).context("invalid hex bitmask")?
3553    } else {
3554        u16::from_str(s).context("invalid decimal bitmask")?
3555    };
3556
3557    CfmwsWindowRestrictions::try_from_bits(bits)
3558        .context("bitmask includes reserved CFMWS window restriction bits")
3559}
3560
3561#[derive(Clone, Debug, PartialEq)]
3562pub struct PcieRootPortCli {
3563    pub root_complex_name: String,
3564    pub name: String,
3565    pub devfn: Option<u8>,
3566    pub hotplug: bool,
3567    pub acs_capabilities_supported: Option<u16>,
3568    pub cxl: bool,
3569    pub pasid: bool,
3570}
3571
3572/// A colon-joined `parent:child` name pair used as the positional head of
3573/// `--pcie-root-port` and `--pcie-switch`.
3574struct PortNamePair {
3575    parent: String,
3576    child: String,
3577}
3578
3579impl FromStr for PortNamePair {
3580    type Err = anyhow::Error;
3581
3582    fn from_str(s: &str) -> anyhow::Result<Self> {
3583        let mut it = s.split(':');
3584        let parent = it
3585            .next()
3586            .filter(|x| !x.is_empty())
3587            .context("expected parent name")?;
3588        let child = it
3589            .next()
3590            .filter(|x| !x.is_empty())
3591            .context("expected child name")?;
3592        anyhow::ensure!(it.next().is_none(), "unexpected token in '{s}'");
3593        Ok(PortNamePair {
3594            parent: parent.to_string(),
3595            child: child.to_string(),
3596        })
3597    }
3598}
3599
3600/// A PCIe device/function address (`XX[.Y]`) parsed into a devfn.
3601struct PcieAddr(u8);
3602
3603impl FromStr for PcieAddr {
3604    type Err = anyhow::Error;
3605
3606    fn from_str(s: &str) -> anyhow::Result<Self> {
3607        Ok(PcieAddr(parse_pcie_addr(s)?))
3608    }
3609}
3610
3611/// An ACS capability bitmask (hex `0x..` or decimal).
3612struct AcsMask(u16);
3613
3614impl FromStr for AcsMask {
3615    type Err = anyhow::Error;
3616
3617    fn from_str(s: &str) -> anyhow::Result<Self> {
3618        Ok(AcsMask(parse_acs_capability_mask(s)?))
3619    }
3620}
3621
3622/// Raw `--pcie-root-port` options, mapped into [`PcieRootPortCli`].
3623#[derive(vmm_cli::KeyValueArgs)]
3624struct RootPortArgs {
3625    #[kv(positional)]
3626    names: PortNamePair,
3627    addr: Option<PcieAddr>,
3628    #[kv(flag)]
3629    hotplug: bool,
3630    acs: Option<AcsMask>,
3631    #[kv(flag)]
3632    cxl: bool,
3633    #[kv(flag)]
3634    pasid: bool,
3635}
3636
3637impl FromStr for PcieRootPortCli {
3638    type Err = anyhow::Error;
3639
3640    fn from_str(s: &str) -> Result<Self, Self::Err> {
3641        let args: RootPortArgs = s.parse()?;
3642        Ok(PcieRootPortCli {
3643            root_complex_name: args.names.parent,
3644            name: args.names.child,
3645            devfn: args.addr.map(|a| a.0),
3646            hotplug: args.hotplug,
3647            acs_capabilities_supported: args.acs.map(|a| a.0),
3648            cxl: args.cxl,
3649            pasid: args.pasid,
3650        })
3651    }
3652}
3653
3654/// Parses a PCIe address of the form `XX[.Y]`, where `XX` is the device number
3655/// (0-31) and the optional `Y` is the function number (0-7), into a devfn
3656/// (`device << 3 | function`).
3657fn parse_pcie_addr(s: &str) -> anyhow::Result<u8> {
3658    let parse_int = |v: &str| -> anyhow::Result<u8> {
3659        if let Some(hex) = v.strip_prefix("0x").or_else(|| v.strip_prefix("0X")) {
3660            u8::from_str_radix(hex, 16).context("invalid hex number")
3661        } else {
3662            v.parse().context("invalid number")
3663        }
3664    };
3665
3666    let mut parts = s.split('.');
3667    let device = parse_int(parts.next().context("expected device number")?)?;
3668    let function = match parts.next() {
3669        Some(f) => parse_int(f)?,
3670        None => 0,
3671    };
3672    if parts.next().is_some() {
3673        anyhow::bail!("unexpected token in addr '{s}'");
3674    }
3675    if device > 31 {
3676        anyhow::bail!("device number {device} out of range (0-31)");
3677    }
3678    if function > 7 {
3679        anyhow::bail!("function number {function} out of range (0-7)");
3680    }
3681    Ok((device << 3) | function)
3682}
3683
3684#[derive(Clone, Debug, PartialEq)]
3685pub struct GenericPcieSwitchCli {
3686    pub port_name: String,
3687    pub name: String,
3688    pub num_downstream_ports: u8,
3689    pub hotplug: bool,
3690    pub acs_capabilities_supported: Option<u16>,
3691    pub pasid: bool,
3692}
3693
3694/// Raw `--pcie-switch` options, mapped into [`GenericPcieSwitchCli`].
3695#[derive(vmm_cli::KeyValueArgs)]
3696struct SwitchArgs {
3697    #[kv(positional)]
3698    names: PortNamePair,
3699    #[kv(default = 4)]
3700    num_downstream_ports: u8,
3701    #[kv(flag)]
3702    hotplug: bool,
3703    acs: Option<AcsMask>,
3704    #[kv(flag)]
3705    pasid: bool,
3706}
3707
3708impl FromStr for GenericPcieSwitchCli {
3709    type Err = anyhow::Error;
3710
3711    fn from_str(s: &str) -> Result<Self, Self::Err> {
3712        let args: SwitchArgs = s.parse()?;
3713        Ok(GenericPcieSwitchCli {
3714            port_name: args.names.parent,
3715            name: args.names.child,
3716            num_downstream_ports: args.num_downstream_ports,
3717            hotplug: args.hotplug,
3718            acs_capabilities_supported: args.acs.map(|a| a.0),
3719            pasid: args.pasid,
3720        })
3721    }
3722}
3723
3724/// CLI configuration mapping a PCIe port name to a generic-initiator NUMA node.
3725#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueArgs)]
3726pub struct PcieGenericInitiatorCli {
3727    /// Name of the PCIe port (root port or switch downstream port) behind
3728    /// which the generic-initiator device resides.
3729    #[kv(key = "port")]
3730    pub port_name: String,
3731    /// NUMA node the device is a generic initiator for.
3732    pub node: u32,
3733}
3734
3735/// CLI configuration for an emulated xHCI controller.
3736#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueArgs)]
3737pub struct UsbXhciCli {
3738    /// Name of the PCIe port used by the controller.
3739    #[kv(positional)]
3740    pub port_name: String,
3741}
3742
3743/// USB vendor or product ID in decimal or hexadecimal notation.
3744#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3745pub struct UsbIdCli(pub u16);
3746
3747impl FromStr for UsbIdCli {
3748    type Err = anyhow::Error;
3749
3750    fn from_str(value: &str) -> Result<Self, Self::Err> {
3751        Ok(Self(
3752            if let Some(hex) = value
3753                .strip_prefix("0x")
3754                .or_else(|| value.strip_prefix("0X"))
3755            {
3756                u16::from_str_radix(hex, 16).context("invalid hexadecimal USB ID")?
3757            } else {
3758                value.parse().context("invalid decimal USB ID")?
3759            },
3760        ))
3761    }
3762}
3763
3764/// A validated, one-based physical USB connector.
3765#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3766pub struct UsbConnectorCli(u8);
3767
3768impl UsbConnectorCli {
3769    /// The user-supplied one-based connector number.
3770    pub fn number(self) -> u8 {
3771        self.0
3772    }
3773}
3774
3775impl FromStr for UsbConnectorCli {
3776    type Err = anyhow::Error;
3777
3778    fn from_str(value: &str) -> Result<Self, Self::Err> {
3779        let connector = value.parse()?;
3780        anyhow::ensure!(connector != 0, "USB connector numbers are one-based");
3781        Ok(Self(connector))
3782    }
3783}
3784
3785/// Optional placement overrides for a single USB device.
3786#[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
3787pub struct UsbDeviceLocationCli {
3788    /// Controller's PCIe port; omitted when the sole controller should be selected.
3789    pub on: Option<String>,
3790    /// One-based USB connector; omitted to select the first free connector.
3791    pub connector: Option<UsbConnectorCli>,
3792}
3793
3794/// A concrete attachment or an automatic device-discovery request.
3795#[derive(Clone, Debug)]
3796pub enum UsbDeviceCli {
3797    /// Attach one typed device with optional controller and connector overrides.
3798    Device {
3799        /// Controller and connector selection.
3800        location: UsbDeviceLocationCli,
3801        /// Backend-specific configuration.
3802        backend: UsbBackend,
3803    },
3804    /// Discover WinUSB devices and attach them to free connectors.
3805    WinUsbAll {
3806        /// Controller's PCIe port; omitted when the sole controller should be selected.
3807        on: Option<String>,
3808    },
3809}
3810
3811impl UsbDeviceCli {
3812    /// Explicit controller PCIe port, or none when it should be inferred.
3813    pub fn controller_pcie_port(&self) -> Option<&str> {
3814        match self {
3815            Self::Device { location, .. } => location.on.as_deref(),
3816            Self::WinUsbAll { on } => on.as_deref(),
3817        }
3818    }
3819}
3820
3821/// Connector selection and optional identity overrides shared by mock devices.
3822#[derive(vmm_cli::KeyValueArgs)]
3823struct UsbMockArgs {
3824    /// Optional controller PCIe port and USB connector overrides.
3825    #[kv(flatten)]
3826    location: UsbDeviceLocationCli,
3827    /// Optional USB vendor ID override.
3828    vid: Option<UsbIdCli>,
3829    /// Optional USB product ID override.
3830    pid: Option<UsbIdCli>,
3831    /// Optional serial-number override.
3832    serial: Option<String>,
3833}
3834
3835impl UsbMockArgs {
3836    fn into_parts(
3837        self,
3838    ) -> (
3839        UsbDeviceLocationCli,
3840        usb_config_resources::UsbIdentityConfig,
3841    ) {
3842        (
3843            self.location,
3844            usb_config_resources::UsbIdentityConfig {
3845                vendor_id: self.vid.map(|id| id.0),
3846                product_id: self.pid.map(|id| id.0),
3847                serial_number: self.serial,
3848            },
3849        )
3850    }
3851}
3852
3853/// Mock-storage arguments, including an optional capacity override.
3854#[derive(vmm_cli::KeyValueArgs)]
3855struct UsbStorageArgs {
3856    /// Connector selection and optional device identity overrides.
3857    #[kv(flatten)]
3858    mock: UsbMockArgs,
3859    /// Optional capacity in 512-byte logical blocks.
3860    blocks: Option<u64>,
3861}
3862
3863/// Explicit host-device selection for the `winusb` kind.
3864#[derive(vmm_cli::KeyValueArgs)]
3865struct UsbWinUsbArgs {
3866    /// Optional controller PCIe port and USB connector overrides.
3867    #[kv(flatten)]
3868    location: UsbDeviceLocationCli,
3869    /// Windows PnP instance ID of the host device to select.
3870    instance_id: String,
3871}
3872
3873/// Startup discovery arguments for the `winusb-all` kind.
3874#[derive(vmm_cli::KeyValueArgs)]
3875struct UsbWinUsbAllArgs {
3876    /// Controller's PCIe port; omitted when the sole controller should be selected.
3877    on: Option<String>,
3878}
3879
3880impl FromStr for UsbDeviceCli {
3881    type Err = anyhow::Error;
3882
3883    fn from_str(value: &str) -> Result<Self, Self::Err> {
3884        use usb_config_resources::*;
3885        let (kind, options) = value.split_once(',').unwrap_or((value, ""));
3886        let (location, backend) = match kind {
3887            "mock-loopback" => {
3888                let args: UsbMockArgs = options.parse()?;
3889                let (location, identity) = args.into_parts();
3890                (
3891                    location,
3892                    UsbBackend::Loopback(MockLoopbackConfig { identity }),
3893                )
3894            }
3895            "mock-hid" => {
3896                let args: UsbMockArgs = options.parse()?;
3897                let (location, identity) = args.into_parts();
3898                (location, UsbBackend::Hid(MockHidConfig { identity }))
3899            }
3900            "mock-storage" => {
3901                let args: UsbStorageArgs = options.parse()?;
3902                anyhow::ensure!(
3903                    args.blocks != Some(0),
3904                    "mock-storage blocks must be greater than zero"
3905                );
3906                let (location, identity) = args.mock.into_parts();
3907                (
3908                    location,
3909                    UsbBackend::Storage(MockStorageConfig {
3910                        identity,
3911                        block_count: args.blocks,
3912                    }),
3913                )
3914            }
3915            "mock-mutt" => {
3916                let args: UsbMockArgs = options.parse()?;
3917                let (location, identity) = args.into_parts();
3918                (location, UsbBackend::Mutt(MockMuttConfig { identity }))
3919            }
3920            "mock-supermutt" => (options.parse()?, UsbBackend::SuperMutt(MockSuperMuttConfig)),
3921            "winusb" => {
3922                let args: UsbWinUsbArgs = options.parse()?;
3923                anyhow::ensure!(
3924                    !args.instance_id.trim().is_empty() && !args.instance_id.contains('\0'),
3925                    "WinUSB instance IDs must be nonempty and contain no NUL characters"
3926                );
3927                (
3928                    args.location,
3929                    UsbBackend::WinUsb(WinUsbConfig {
3930                        instance_id: args.instance_id,
3931                    }),
3932                )
3933            }
3934            "winusb-all" => {
3935                let args: UsbWinUsbAllArgs = options.parse()?;
3936                return Ok(Self::WinUsbAll { on: args.on });
3937            }
3938            _ => anyhow::bail!("unknown USB device kind {kind:?}"),
3939        };
3940        Ok(Self::Device { location, backend })
3941    }
3942}
3943
3944/// CLI configuration for a PCIe remote device.
3945#[derive(Clone, Debug, PartialEq, vmm_cli::KeyValueArgs)]
3946pub struct PcieRemoteCli {
3947    /// Name of the PCIe downstream port to attach to.
3948    #[kv(positional)]
3949    pub port_name: String,
3950    /// TCP socket address for the remote simulator.
3951    #[kv(key = "socket")]
3952    pub socket_addr: Option<String>,
3953    /// Hardware unit identifier for plug request.
3954    #[kv(default)]
3955    pub hu: u16,
3956    /// Controller identifier for plug request.
3957    #[kv(default)]
3958    pub controller: u16,
3959}
3960
3961/// CLI configuration for a VFIO-assigned PCI device.
3962///
3963/// Syntax: `host=<bdf>,port=<name>[,iommu=<id>][,barN=host|barN=0x<addr>]`
3964#[cfg(target_os = "linux")]
3965#[derive(Clone, Debug)]
3966pub struct VfioDeviceCli {
3967    /// Name of the PCIe downstream port to attach to.
3968    pub port_name: String,
3969    /// PCI BDF address of the device on the host (e.g., "0000:01:00.0").
3970    pub pci_id: String,
3971    /// Optional iommufd context ID. When set, uses VFIO cdev + iommufd
3972    /// instead of the legacy group/container path.
3973    pub iommu: Option<String>,
3974    /// Per-BAR pre-programming configuration.
3975    pub bar_addresses: [vfio_assigned_device_resources::BarAddressConfig; 6],
3976}
3977
3978/// Per-BAR address configuration parsed from the CLI.
3979#[cfg(target_os = "linux")]
3980struct BarAddressCli(vfio_assigned_device_resources::BarAddressConfig);
3981
3982#[cfg(target_os = "linux")]
3983impl FromStr for BarAddressCli {
3984    type Err = anyhow::Error;
3985
3986    fn from_str(s: &str) -> anyhow::Result<Self> {
3987        let config = if s == "host" {
3988            vfio_assigned_device_resources::BarAddressConfig::HostAssigned
3989        } else if let Some(value) = s.strip_prefix("0x") {
3990            let address = u64::from_str_radix(value, 16).context("invalid BAR address")?;
3991            anyhow::ensure!(address != 0, "BAR address must be nonzero");
3992            vfio_assigned_device_resources::BarAddressConfig::Fixed(address)
3993        } else {
3994            anyhow::bail!("expected 'host' or a hexadecimal address starting with '0x'");
3995        };
3996        Ok(Self(config))
3997    }
3998}
3999
4000/// Per-BAR address configuration, flattened into
4001/// [`VfioArgs`].
4002#[cfg(target_os = "linux")]
4003#[derive(vmm_cli::KeyValueArgs)]
4004struct BarFlags {
4005    bar0: Option<BarAddressCli>,
4006    bar1: Option<BarAddressCli>,
4007    bar2: Option<BarAddressCli>,
4008    bar3: Option<BarAddressCli>,
4009    bar4: Option<BarAddressCli>,
4010    bar5: Option<BarAddressCli>,
4011}
4012
4013/// Raw `--vfio` options, resolved and validated into a [`VfioDeviceCli`].
4014#[cfg(target_os = "linux")]
4015#[derive(vmm_cli::KeyValueArgs)]
4016struct VfioArgs {
4017    host: String,
4018    port: String,
4019    iommu: Option<String>,
4020    #[kv(flatten)]
4021    bars: BarFlags,
4022}
4023
4024#[cfg(target_os = "linux")]
4025impl FromStr for VfioDeviceCli {
4026    type Err = anyhow::Error;
4027
4028    fn from_str(s: &str) -> Result<Self, Self::Err> {
4029        let args: VfioArgs = s.parse()?;
4030
4031        // Reject path separators to prevent sysfs path traversal via Path::join.
4032        if args.host.contains('/') || args.host.contains("..") {
4033            anyhow::bail!("PCI address must not contain path separators");
4034        }
4035
4036        let bars = args.bars;
4037        let bar_addresses = [
4038            bars.bar0.map(|bar| bar.0).unwrap_or_default(),
4039            bars.bar1.map(|bar| bar.0).unwrap_or_default(),
4040            bars.bar2.map(|bar| bar.0).unwrap_or_default(),
4041            bars.bar3.map(|bar| bar.0).unwrap_or_default(),
4042            bars.bar4.map(|bar| bar.0).unwrap_or_default(),
4043            bars.bar5.map(|bar| bar.0).unwrap_or_default(),
4044        ];
4045
4046        Ok(VfioDeviceCli {
4047            port_name: args.port,
4048            pci_id: args.host,
4049            iommu: args.iommu,
4050            bar_addresses,
4051        })
4052    }
4053}
4054
4055cfg_select! {
4056    guest_arch = "aarch64" => {
4057        /// CLI configuration for an SMMUv3 instance.
4058        ///
4059        /// Syntax: `rc=<name>[,accel][,oas=auto|N][,ssidsize=auto|N]`.
4060        /// Both `oas` and `ssidsize` default to `auto`.
4061        #[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
4062        pub struct SmmuCli {
4063            /// Name of the PCIe root complex this SMMU covers.
4064            #[kv(key = "rc")]
4065            pub rc_name: String,
4066            /// Enable HW-accelerated nested translation (iommufd).
4067            #[kv(flag)]
4068            pub accel: bool,
4069            /// Output address size policy.
4070            #[kv(default)]
4071            pub oas: SmmuOasCli,
4072            /// SubstreamID width policy.
4073            #[kv(default)]
4074            pub ssidsize: SmmuSsidSizeCli,
4075        }
4076
4077        /// Output address size (OAS) policy parsed from `--smmu`.
4078        #[derive(Clone, Copy, Debug, Default)]
4079        pub enum SmmuOasCli {
4080            /// Advertise a fixed default OAS (see the `--smmu` docs for the sizing
4081            /// policy and when a larger fixed OAS is required).
4082            #[default]
4083            Auto,
4084            /// Fixed OAS in bits (one of 32, 36, 40, 42, 44, 48, 52).
4085            Fixed(u8),
4086        }
4087
4088        impl FromStr for SmmuOasCli {
4089            type Err = anyhow::Error;
4090
4091            fn from_str(s: &str) -> Result<Self, Self::Err> {
4092                Ok(if s == "auto" {
4093                    SmmuOasCli::Auto
4094                } else {
4095                    SmmuOasCli::Fixed(s.parse().context("oas must be 'auto' or a number")?)
4096                })
4097            }
4098        }
4099
4100        /// SubstreamID width (SSIDSIZE) policy parsed from `--smmu`.
4101        #[derive(Clone, Copy, Debug, Default)]
4102        pub enum SmmuSsidSizeCli {
4103            /// Disable substreams in software mode; under acceleration, adopt the
4104            /// host's width before device start freezes the capabilities.
4105            #[default]
4106            Auto,
4107            /// Fixed width in bits (0..=20). Zero disables substreams.
4108            Fixed(u8),
4109        }
4110
4111        impl FromStr for SmmuSsidSizeCli {
4112            type Err = anyhow::Error;
4113
4114            fn from_str(s: &str) -> Result<Self, Self::Err> {
4115                Ok(if s == "auto" {
4116                    Self::Auto
4117                } else {
4118                    Self::Fixed(s.parse().context("ssidsize must be 'auto' or a number")?)
4119                })
4120            }
4121        }
4122    }
4123    _ => {}
4124}
4125
4126/// CLI configuration for an iommufd context.
4127///
4128/// Syntax: `id=<name>`
4129#[cfg(target_os = "linux")]
4130#[derive(Clone, Debug, vmm_cli::KeyValueArgs)]
4131pub struct IommuCli {
4132    /// Unique identifier for this iommufd context.
4133    pub id: String,
4134}
4135
4136/// Read a environment variable that may / may-not have a target-specific
4137/// prefix. e.g: `default_value_from_arch_env("FOO")` would first try and read
4138/// from `FOO`, and if that's not found, it will try `X86_64_FOO`.
4139///
4140/// Must return an `OsString`, in order to be compatible with `clap`'s
4141/// default_value code. As such - to encode the absence of the env-var, an empty
4142/// OsString is returned.
4143fn default_value_from_arch_env(name: &str) -> OsString {
4144    let prefix = cfg_select! {
4145        guest_arch = "x86_64" => "X86_64",
4146        guest_arch = "aarch64" => "AARCH64",
4147    };
4148    let prefixed = format!("{}_{}", prefix, name);
4149    std::env::var_os(name)
4150        .or_else(|| std::env::var_os(prefixed))
4151        .unwrap_or_default()
4152}
4153
4154pub fn default_uefi_firmware() -> Option<PathBuf> {
4155    OptionalPathBuf::from(default_value_from_arch_env("OPENVMM_UEFI_FIRMWARE").as_os_str()).0
4156}
4157
4158/// Workaround to use `Option<PathBuf>` alongside [`default_value_from_arch_env`]
4159#[derive(Clone)]
4160pub struct OptionalPathBuf(pub Option<PathBuf>);
4161
4162impl From<&std::ffi::OsStr> for OptionalPathBuf {
4163    fn from(s: &std::ffi::OsStr) -> Self {
4164        OptionalPathBuf(if s.is_empty() { None } else { Some(s.into()) })
4165    }
4166}
4167
4168#[cfg(target_os = "linux")]
4169#[derive(Clone)]
4170pub enum VhostUserDeviceTypeCli {
4171    /// Block device — config from backend via GET_CONFIG, with num_queues
4172    /// patched by the frontend.
4173    Blk {
4174        num_queues: Option<u16>,
4175        queue_size: Option<u16>,
4176    },
4177    /// Filesystem device — frontend-owned config with mount tag.
4178    Fs {
4179        tag: String,
4180        num_queues: Option<u16>,
4181        queue_size: Option<u16>,
4182    },
4183    /// Generic device identified by numeric virtio device ID.
4184    Other {
4185        device_id: u16,
4186        queue_sizes: Vec<u16>,
4187    },
4188}
4189
4190#[cfg(target_os = "linux")]
4191#[derive(Clone)]
4192pub struct VhostUserCli {
4193    pub socket_path: String,
4194    pub device_type: VhostUserDeviceTypeCli,
4195    pub pcie_port: Option<String>,
4196}
4197
4198/// Raw `--vhost-user` options, resolved into a [`VhostUserCli`] by its
4199/// `FromStr`.
4200#[cfg(target_os = "linux")]
4201#[derive(vmm_cli::KeyValueArgs)]
4202struct VhostUserArgs {
4203    #[kv(positional)]
4204    socket_path: String,
4205    #[kv(key = "type")]
4206    type_name: Option<String>,
4207    device_id: Option<u16>,
4208    tag: Option<String>,
4209    pcie_port: Option<String>,
4210    num_queues: Option<u16>,
4211    queue_size: Option<u16>,
4212    queue_sizes: Option<vmm_cli::BracketList<u16>>,
4213}
4214
4215#[cfg(target_os = "linux")]
4216impl FromStr for VhostUserCli {
4217    type Err = anyhow::Error;
4218
4219    fn from_str(s: &str) -> anyhow::Result<Self> {
4220        let mut args: VhostUserArgs = s.parse()?;
4221        let type_name = args.type_name.take();
4222
4223        if type_name.is_some() == args.device_id.is_some() {
4224            anyhow::bail!("must specify type=<name> or device_id=<N>");
4225        }
4226
4227        // Each variant consumes the options it accepts; whatever is left over
4228        // afterward was used with the wrong device type.
4229        let device_type = match type_name.as_deref() {
4230            Some("fs") => VhostUserDeviceTypeCli::Fs {
4231                tag: args.tag.take().context("type=fs requires tag=<name>")?,
4232                num_queues: args.num_queues.take(),
4233                queue_size: args.queue_size.take(),
4234            },
4235            Some("blk") => VhostUserDeviceTypeCli::Blk {
4236                num_queues: args.num_queues.take(),
4237                queue_size: args.queue_size.take(),
4238            },
4239            Some(ty) => anyhow::bail!("unknown vhost-user device type: '{ty}'"),
4240            None => {
4241                let queue_sizes = args
4242                    .queue_sizes
4243                    .take()
4244                    .context("device_id= requires queue_sizes=[N,N,...]")?
4245                    .0;
4246                anyhow::ensure!(!queue_sizes.is_empty(), "queue_sizes must be non-empty");
4247                VhostUserDeviceTypeCli::Other {
4248                    device_id: args.device_id.unwrap(),
4249                    queue_sizes,
4250                }
4251            }
4252        };
4253
4254        if args.tag.is_some() {
4255            anyhow::bail!("tag= is only valid for type=fs");
4256        }
4257        if args.queue_sizes.is_some() {
4258            anyhow::bail!("queue_sizes= is only valid for device_id=");
4259        }
4260        if args.num_queues.is_some() || args.queue_size.is_some() {
4261            anyhow::bail!(
4262                "num_queues= and queue_size= are not valid for device_id=; use queue_sizes="
4263            );
4264        }
4265
4266        Ok(VhostUserCli {
4267            socket_path: args.socket_path,
4268            device_type,
4269            pcie_port: args.pcie_port,
4270        })
4271    }
4272}
4273
4274#[cfg(test)]
4275mod tests {
4276    use super::*;
4277
4278    use std::path::Path;
4279    use test_with_tracing::test;
4280
4281    #[test]
4282    fn vmgs_provision_conditions() {
4283        for (option, expected) in [
4284            ("", ProvisionCondition::OnEmpty),
4285            (",fmt-on-fail", ProvisionCondition::OnFailure),
4286            (",fmt", ProvisionCondition::Single),
4287        ] {
4288            let vmgs: VmgsCli = format!("mem:VMGS_DEFAULT{option}").parse().unwrap();
4289            assert!(matches!(
4290                (vmgs.provision, expected),
4291                (ProvisionCondition::OnEmpty, ProvisionCondition::OnEmpty)
4292                    | (ProvisionCondition::OnFailure, ProvisionCondition::OnFailure)
4293                    | (ProvisionCondition::Single, ProvisionCondition::Single)
4294            ));
4295        }
4296    }
4297
4298    /// Controller arguments contain one PCIe port name and no device-specific options.
4299    #[test]
4300    fn test_parse_usb_controller() {
4301        let controller = UsbXhciCli::from_str("rc0rp0").unwrap();
4302        assert_eq!(controller.port_name, "rc0rp0");
4303        assert!(UsbXhciCli::from_str("").is_err());
4304        assert!(UsbXhciCli::from_str("rc0rp0,connector=1").is_err());
4305    }
4306
4307    /// Bare mock kinds select the right variant and leave optional fields unset.
4308    #[test]
4309    fn test_parse_usb_mock_defaults() {
4310        for kind in [
4311            "mock-loopback",
4312            "mock-hid",
4313            "mock-storage",
4314            "mock-mutt",
4315            "mock-supermutt",
4316        ] {
4317            let UsbDeviceCli::Device { location, backend } = UsbDeviceCli::from_str(kind).unwrap()
4318            else {
4319                panic!("expected a device for {kind}");
4320            };
4321            assert_eq!(location.on, None);
4322            assert_eq!(location.connector, None);
4323            let identity = match (kind, backend) {
4324                ("mock-loopback", UsbBackend::Loopback(config)) => config.identity,
4325                ("mock-hid", UsbBackend::Hid(config)) => config.identity,
4326                ("mock-storage", UsbBackend::Storage(config)) => {
4327                    assert_eq!(config.block_count, None);
4328                    config.identity
4329                }
4330                ("mock-mutt", UsbBackend::Mutt(config)) => config.identity,
4331                ("mock-supermutt", UsbBackend::SuperMutt(_)) => continue,
4332                _ => panic!("wrong backend variant for {kind}"),
4333            };
4334            assert_eq!(identity, usb_config_resources::UsbIdentityConfig::default());
4335        }
4336    }
4337
4338    /// Mock placement and identity overrides retain their parsed values for each kind.
4339    #[test]
4340    fn test_parse_usb_mock_overrides() {
4341        for kind in ["mock-loopback", "mock-hid", "mock-storage", "mock-mutt"] {
4342            let capacity = if kind == "mock-storage" {
4343                ",blocks=4096"
4344            } else {
4345                ""
4346            };
4347            let selection = format!(
4348                "{kind},on=usb0,connector=7,vid=0x1234,pid=65535,serial=SERIAL42{capacity}"
4349            );
4350            let UsbDeviceCli::Device { location, backend } =
4351                UsbDeviceCli::from_str(&selection).unwrap()
4352            else {
4353                panic!("expected a device for {kind}");
4354            };
4355            assert_eq!(location.on.as_deref(), Some("usb0"));
4356            assert_eq!(location.connector.map(UsbConnectorCli::number), Some(7));
4357            let identity = match (kind, backend) {
4358                ("mock-loopback", UsbBackend::Loopback(config)) => config.identity,
4359                ("mock-hid", UsbBackend::Hid(config)) => config.identity,
4360                ("mock-storage", UsbBackend::Storage(config)) => {
4361                    assert_eq!(config.block_count, Some(4096));
4362                    config.identity
4363                }
4364                ("mock-mutt", UsbBackend::Mutt(config)) => config.identity,
4365                _ => panic!("wrong backend variant for {kind}"),
4366            };
4367            assert_eq!(identity.vendor_id, Some(0x1234));
4368            assert_eq!(identity.product_id, Some(65535));
4369            assert_eq!(identity.serial_number.as_deref(), Some("SERIAL42"));
4370        }
4371    }
4372
4373    /// Host-device IDs and optional placement remain distinct from discovery requests.
4374    #[test]
4375    fn test_parse_usb_host_selections() {
4376        for (selection, expected_pcie_port, expected_connector) in [
4377            (r"winusb,instance_id=USB\A&B C", None, None),
4378            (
4379                r"winusb,on=usb0,connector=3,instance_id=USB\A&B C",
4380                Some("usb0"),
4381                Some(3),
4382            ),
4383        ] {
4384            let UsbDeviceCli::Device {
4385                location,
4386                backend: UsbBackend::WinUsb(config),
4387            } = UsbDeviceCli::from_str(selection).unwrap()
4388            else {
4389                panic!("expected explicit WinUSB selection");
4390            };
4391            assert_eq!(location.on.as_deref(), expected_pcie_port);
4392            assert_eq!(
4393                location.connector.map(UsbConnectorCli::number),
4394                expected_connector
4395            );
4396            assert_eq!(config.instance_id, r"USB\A&B C");
4397        }
4398        for (selection, expected_pcie_port) in
4399            [("winusb-all", None), ("winusb-all,on=usb1", Some("usb1"))]
4400        {
4401            let UsbDeviceCli::WinUsbAll { on } = UsbDeviceCli::from_str(selection).unwrap() else {
4402                panic!("expected WinUSB discovery request");
4403            };
4404            assert_eq!(on.as_deref(), expected_pcie_port);
4405        }
4406    }
4407
4408    /// Reject malformed values, repeated fields, and options belonging to another kind.
4409    #[test]
4410    fn test_parse_usb_invalid_options() {
4411        for selection in [
4412            "",
4413            "unknown",
4414            "usb0:hid",
4415            "mock-hid,connector=0",
4416            "mock-hid,connector=256",
4417            "mock-hid,vid=0x10000",
4418            "mock-hid,pid=bad",
4419            "mock-hid,on=usb0,on=usb1",
4420            "mock-hid,blocks=1",
4421            "mock-hid,serial=",
4422            "mock-storage,blocks=0",
4423            "mock-supermutt,vid=1",
4424            "winusb",
4425            "winusb,instance_id=",
4426            "winusb,instance_id=USB\0INSTANCE",
4427            "winusb,instance_id=USB,serial=x",
4428            "winusb-all,connector=1",
4429        ] {
4430            assert!(
4431                UsbDeviceCli::from_str(selection).is_err(),
4432                "accepted {selection:?}"
4433            );
4434        }
4435    }
4436
4437    #[test]
4438    fn force_guest_memory_bounce_is_vm_wide_and_defaults_off() {
4439        assert!(
4440            !Options::try_parse_from(["openvmm"])
4441                .unwrap()
4442                .force_guest_memory_bounce
4443        );
4444        assert!(
4445            Options::try_parse_from(["openvmm", "--force-guest-memory-bounce"])
4446                .unwrap()
4447                .force_guest_memory_bounce
4448        );
4449    }
4450
4451    /// `--version` reports the resolved build identity rather than clap's
4452    /// default, which would be the parser crate's own name and version.
4453    #[test]
4454    fn version_reports_build_info() {
4455        let short = version_output(["openvmm", "-V"]);
4456        assert_eq!(
4457            short,
4458            format!("openvmm {}\n", openvmm_build_info::get().version())
4459        );
4460
4461        let long = version_output(["openvmm", "--version"]);
4462        assert_eq!(
4463            long,
4464            format!("openvmm {}\n", openvmm_build_info::get().long_version())
4465        );
4466    }
4467
4468    fn version_output(args: [&str; 2]) -> String {
4469        let Err(error) = Options::try_parse_from(args) else {
4470            panic!("{args:?} unexpectedly parsed as runtime options");
4471        };
4472        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayVersion);
4473        error.to_string()
4474    }
4475
4476    #[test]
4477    fn test_parse_rpc() {
4478        // explicit path, default transport
4479        let rpc = RpcCli::from_str("path=/tmp/openvmm.sock").unwrap();
4480        assert_eq!(rpc.path, Path::new("/tmp/openvmm.sock"));
4481        assert_eq!(rpc.transport, RpcTransportCli::Auto);
4482
4483        // explicit transport
4484        for (s, transport) in [
4485            ("auto", RpcTransportCli::Auto),
4486            ("ttrpc", RpcTransportCli::Ttrpc),
4487            ("grpc", RpcTransportCli::Grpc),
4488        ] {
4489            let rpc = RpcCli::from_str(&format!("path=/tmp/s.sock,transport={s}")).unwrap();
4490            assert_eq!(rpc.path, Path::new("/tmp/s.sock"));
4491            assert_eq!(rpc.transport, transport);
4492        }
4493
4494        // errors
4495        assert!(RpcCli::from_str("").is_err());
4496        assert!(RpcCli::from_str("transport=ttrpc").is_err());
4497        assert!(RpcCli::from_str("path=").is_err());
4498        assert!(RpcCli::from_str("path=/tmp/s.sock,transport=bogus").is_err());
4499        assert!(RpcCli::from_str("path=/tmp/s.sock,bogus=1").is_err());
4500        assert!(RpcCli::from_str("path=/a,path=/b").is_err());
4501    }
4502
4503    #[test]
4504    fn test_parse_file_opts() {
4505        // file: prefix with create
4506        let disk = DiskCliKind::from_str("file:test.vhd;create=1G").unwrap();
4507        assert!(matches!(
4508            &disk,
4509            DiskCliKind::File { path, create_with_len: Some(len), direct: false }
4510                if path == Path::new("test.vhd") && *len == 1024 * 1024 * 1024
4511        ));
4512
4513        // bare path with create (no file: prefix)
4514        let disk = DiskCliKind::from_str("test.vhd;create=1G").unwrap();
4515        assert!(matches!(
4516            &disk,
4517            DiskCliKind::File { path, create_with_len: Some(len), direct: false }
4518                if path == Path::new("test.vhd") && *len == 1024 * 1024 * 1024
4519        ));
4520
4521        // direct flag
4522        let disk = DiskCliKind::from_str("file:/dev/sdb;direct").unwrap();
4523        assert!(matches!(
4524            &disk,
4525            DiskCliKind::File { path, create_with_len: None, direct: true }
4526                if path == Path::new("/dev/sdb")
4527        ));
4528
4529        // direct + create in either order
4530        let disk = DiskCliKind::from_str("file:disk.img;direct;create=1G").unwrap();
4531        assert!(matches!(
4532            &disk,
4533            DiskCliKind::File { path, create_with_len: Some(len), direct: true }
4534                if path == Path::new("disk.img") && *len == 1024 * 1024 * 1024
4535        ));
4536
4537        let disk = DiskCliKind::from_str("file:disk.img;create=1G;direct").unwrap();
4538        assert!(matches!(
4539            &disk,
4540            DiskCliKind::File { path, create_with_len: Some(len), direct: true }
4541                if path == Path::new("disk.img") && *len == 1024 * 1024 * 1024
4542        ));
4543
4544        // plain path, no options
4545        let disk = DiskCliKind::from_str("file:disk.img").unwrap();
4546        assert!(matches!(
4547            &disk,
4548            DiskCliKind::File { path, create_with_len: None, direct: false }
4549                if path == Path::new("disk.img")
4550        ));
4551
4552        // invalid option rejected
4553        assert!(DiskCliKind::from_str("file:disk.img;bogus").is_err());
4554
4555        // direct rejected for sql disks
4556        assert!(DiskCliKind::from_str("sql:db.sqlite;direct").is_err());
4557    }
4558
4559    #[test]
4560    fn test_parse_memory_disk() {
4561        let s = "mem:1G";
4562        let disk = DiskCliKind::from_str(s).unwrap();
4563        match disk {
4564            DiskCliKind::Memory(size) => {
4565                assert_eq!(size, 1024 * 1024 * 1024); // 1G
4566            }
4567            _ => panic!("Expected Memory variant"),
4568        }
4569    }
4570
4571    #[test]
4572    fn test_parse_pcie_disk() {
4573        assert_eq!(
4574            DiskCli::from_str("mem:1G,pcie_port=p0").unwrap().pcie_port,
4575            Some("p0".to_string())
4576        );
4577        assert_eq!(
4578            DiskCli::from_str("file:path.vhdx,pcie_port=p0")
4579                .unwrap()
4580                .pcie_port,
4581            Some("p0".to_string())
4582        );
4583        assert_eq!(
4584            DiskCli::from_str("memdiff:file:path.vhdx,pcie_port=p0")
4585                .unwrap()
4586                .pcie_port,
4587            Some("p0".to_string())
4588        );
4589
4590        // Missing port name
4591        assert!(DiskCli::from_str("file:disk.vhd,pcie_port=").is_err());
4592
4593        // Incompatible with various other disk fields
4594        assert!(DiskCli::from_str("file:disk.vhd,pcie_port=p0,vtl2").is_err());
4595        assert!(DiskCli::from_str("file:disk.vhd,pcie_port=p0,uh").is_err());
4596        assert!(DiskCli::from_str("file:disk.vhd,pcie_port=p0,uh-nvme").is_err());
4597    }
4598
4599    #[test]
4600    fn test_parse_virtio_blk_queue_count() {
4601        assert_eq!(DiskCli::from_str("mem:1G").unwrap().num_queues, None);
4602        for count in [1, 2, 4, 256] {
4603            let disk = format!("mem:1G,ro,pcie_port=p0,num_queues={count}");
4604            assert_eq!(DiskCli::from_str(&disk).unwrap().num_queues, Some(count));
4605        }
4606        for count in ["0", "257", "65536", "-1", "", "many"] {
4607            let disk = format!("mem:1G,num_queues={count}");
4608            assert!(DiskCli::from_str(&disk).is_err(), "{disk}");
4609        }
4610    }
4611
4612    #[test]
4613    fn test_virtio_blk_per_disk_queue_options() {
4614        let opt = Options::try_parse_from([
4615            "openvmm",
4616            "--virtio-blk-queues",
4617            "8",
4618            "--virtio-blk",
4619            "mem:1G,num_queues=4",
4620            "--virtio-blk",
4621            "mem:1G,num_queues=1",
4622            "--virtio-blk",
4623            "mem:1G",
4624        ])
4625        .unwrap();
4626        assert_eq!(opt.virtio_blk_queues, 8);
4627        assert_eq!(
4628            opt.virtio_blk
4629                .iter()
4630                .map(|disk| disk.num_queues)
4631                .collect::<Vec<_>>(),
4632            [Some(4), Some(1), None]
4633        );
4634    }
4635
4636    #[test]
4637    fn test_parse_memory_diff_disk() {
4638        let s = "memdiff:file:base.img";
4639        let disk = DiskCliKind::from_str(s).unwrap();
4640        match disk {
4641            DiskCliKind::MemoryDiff(inner) => match *inner {
4642                DiskCliKind::File {
4643                    path,
4644                    create_with_len,
4645                    ..
4646                } => {
4647                    assert_eq!(path, PathBuf::from("base.img"));
4648                    assert_eq!(create_with_len, None);
4649                }
4650                _ => panic!("Expected File variant inside MemoryDiff"),
4651            },
4652            _ => panic!("Expected MemoryDiff variant"),
4653        }
4654    }
4655
4656    #[test]
4657    fn test_parse_sqlite_disk() {
4658        let s = "sql:db.sqlite;create=2G";
4659        let disk = DiskCliKind::from_str(s).unwrap();
4660        match disk {
4661            DiskCliKind::Sqlite {
4662                path,
4663                create_with_len,
4664            } => {
4665                assert_eq!(path, PathBuf::from("db.sqlite"));
4666                assert_eq!(create_with_len, Some(2 * 1024 * 1024 * 1024));
4667            }
4668            _ => panic!("Expected Sqlite variant"),
4669        }
4670
4671        // Test without create option
4672        let s = "sql:db.sqlite";
4673        let disk = DiskCliKind::from_str(s).unwrap();
4674        match disk {
4675            DiskCliKind::Sqlite {
4676                path,
4677                create_with_len,
4678            } => {
4679                assert_eq!(path, PathBuf::from("db.sqlite"));
4680                assert_eq!(create_with_len, None);
4681            }
4682            _ => panic!("Expected Sqlite variant"),
4683        }
4684    }
4685
4686    #[test]
4687    fn test_parse_sqlite_diff_disk() {
4688        // Test with create option
4689        let s = "sqldiff:diff.sqlite;create:file:base.img";
4690        let disk = DiskCliKind::from_str(s).unwrap();
4691        match disk {
4692            DiskCliKind::SqliteDiff { path, create, disk } => {
4693                assert_eq!(path, PathBuf::from("diff.sqlite"));
4694                assert!(create);
4695                match *disk {
4696                    DiskCliKind::File {
4697                        path,
4698                        create_with_len,
4699                        ..
4700                    } => {
4701                        assert_eq!(path, PathBuf::from("base.img"));
4702                        assert_eq!(create_with_len, None);
4703                    }
4704                    _ => panic!("Expected File variant inside SqliteDiff"),
4705                }
4706            }
4707            _ => panic!("Expected SqliteDiff variant"),
4708        }
4709
4710        // Test without create option
4711        let s = "sqldiff:diff.sqlite:file:base.img";
4712        let disk = DiskCliKind::from_str(s).unwrap();
4713        match disk {
4714            DiskCliKind::SqliteDiff { path, create, disk } => {
4715                assert_eq!(path, PathBuf::from("diff.sqlite"));
4716                assert!(!create);
4717                match *disk {
4718                    DiskCliKind::File {
4719                        path,
4720                        create_with_len,
4721                        ..
4722                    } => {
4723                        assert_eq!(path, PathBuf::from("base.img"));
4724                        assert_eq!(create_with_len, None);
4725                    }
4726                    _ => panic!("Expected File variant inside SqliteDiff"),
4727                }
4728            }
4729            _ => panic!("Expected SqliteDiff variant"),
4730        }
4731    }
4732
4733    #[test]
4734    fn test_parse_autocache_sqlite_disk() {
4735        // Test with cache path provided
4736        let disk =
4737            DiskCliKind::parse_autocache(":file:disk.vhd", Ok("/tmp/cache".to_string())).unwrap();
4738        assert!(matches!(
4739            disk,
4740            DiskCliKind::AutoCacheSqlite {
4741                cache_path,
4742                key,
4743                disk: _disk,
4744            } if cache_path == "/tmp/cache" && key.is_none()
4745        ));
4746
4747        // Test with key
4748        let disk =
4749            DiskCliKind::parse_autocache("mykey:file:disk.vhd", Ok("/tmp/cache".to_string()))
4750                .unwrap();
4751        assert!(matches!(
4752            disk,
4753            DiskCliKind::AutoCacheSqlite {
4754                cache_path,
4755                key: Some(key),
4756                disk: _disk,
4757            } if cache_path == "/tmp/cache" && key == "mykey"
4758        ));
4759
4760        // Test without cache path
4761        assert!(
4762            DiskCliKind::parse_autocache(":file:disk.vhd", Err(std::env::VarError::NotPresent),)
4763                .is_err()
4764        );
4765    }
4766
4767    #[test]
4768    fn test_parse_disk_errors() {
4769        assert!(DiskCliKind::from_str("invalid:").is_err());
4770        assert!(DiskCliKind::from_str("memory:extra").is_err());
4771
4772        // Test sqlite: without environment variable
4773        assert!(DiskCliKind::from_str("sqlite:").is_err());
4774    }
4775
4776    #[test]
4777    fn test_parse_errors() {
4778        // Invalid memory size
4779        assert!(DiskCliKind::from_str("mem:invalid").is_err());
4780
4781        // Invalid syntax for SQLiteDiff
4782        assert!(DiskCliKind::from_str("sqldiff:path").is_err());
4783
4784        // Missing OPENVMM_AUTO_CACHE_PATH for AutoCacheSqlite
4785        assert!(
4786            DiskCliKind::parse_autocache("key:file:disk.vhd", Err(std::env::VarError::NotPresent),)
4787                .is_err()
4788        );
4789
4790        // Invalid blob kind
4791        assert!(DiskCliKind::from_str("blob:invalid:url").is_err());
4792
4793        // Invalid cipher
4794        assert!(DiskCliKind::from_str("crypt:invalid:key.bin:file:disk.vhd").is_err());
4795
4796        // Invalid format for crypt (missing parts)
4797        assert!(DiskCliKind::from_str("crypt:xts-aes-256:key.bin").is_err());
4798
4799        // Invalid disk kind
4800        assert!(DiskCliKind::from_str("invalid:path").is_err());
4801
4802        // Missing create size
4803        assert!(DiskCliKind::from_str("file:disk.vhd;create=").is_err());
4804    }
4805
4806    #[test]
4807    fn test_fs_args_from_str() {
4808        let args = FsArgs::from_str("tag1,/path/to/fs").unwrap();
4809        assert_eq!(args.tag, "tag1");
4810        assert_eq!(args.path, "/path/to/fs");
4811
4812        // Test error cases
4813        assert!(FsArgs::from_str("tag1").is_err());
4814        assert!(FsArgs::from_str("tag1,/path,extra").is_err());
4815    }
4816
4817    #[test]
4818    fn test_fs_args_with_options_from_str() {
4819        let args = FsArgsWithOptions::from_str("tag1,/path/to/fs,opt1,opt2").unwrap();
4820        assert_eq!(args.tag, "tag1");
4821        assert_eq!(args.path, "/path/to/fs");
4822        assert_eq!(args.options, "opt1;opt2");
4823
4824        // Test without options
4825        let args = FsArgsWithOptions::from_str("tag1,/path/to/fs").unwrap();
4826        assert_eq!(args.tag, "tag1");
4827        assert_eq!(args.path, "/path/to/fs");
4828        assert_eq!(args.options, "");
4829
4830        // Test error case
4831        assert!(FsArgsWithOptions::from_str("tag1").is_err());
4832    }
4833
4834    #[test]
4835    fn test_serial_config_from_str() {
4836        assert_eq!(
4837            SerialConfigCli::from_str("none").unwrap(),
4838            SerialConfigCli::None
4839        );
4840        assert_eq!(
4841            SerialConfigCli::from_str("null").unwrap(),
4842            SerialConfigCli::Null
4843        );
4844        assert_eq!(
4845            SerialConfigCli::from_str("console").unwrap(),
4846            SerialConfigCli::Console
4847        );
4848        assert_eq!(
4849            SerialConfigCli::from_str("stderr").unwrap(),
4850            SerialConfigCli::Stderr
4851        );
4852
4853        // Test file config
4854        let file_config = SerialConfigCli::from_str("file=/path/to/file").unwrap();
4855        if let SerialConfigCli::File(path) = file_config {
4856            assert_eq!(path.to_str().unwrap(), "/path/to/file");
4857        } else {
4858            panic!("Expected File variant");
4859        }
4860
4861        // Test term config with name, but no specific path
4862        match SerialConfigCli::from_str("term,name=MyTerm").unwrap() {
4863            SerialConfigCli::NewConsole(None, Some(name)) => {
4864                assert_eq!(name, "MyTerm");
4865            }
4866            _ => panic!("Expected NewConsole variant with name"),
4867        }
4868
4869        // Test term config without name, but no specific path
4870        match SerialConfigCli::from_str("term").unwrap() {
4871            SerialConfigCli::NewConsole(None, None) => (),
4872            _ => panic!("Expected NewConsole variant without name"),
4873        }
4874
4875        // Test term config with name
4876        match SerialConfigCli::from_str("term=/dev/pts/0,name=MyTerm").unwrap() {
4877            SerialConfigCli::NewConsole(Some(path), Some(name)) => {
4878                assert_eq!(path.to_str().unwrap(), "/dev/pts/0");
4879                assert_eq!(name, "MyTerm");
4880            }
4881            _ => panic!("Expected NewConsole variant with name"),
4882        }
4883
4884        // Test term config without name
4885        match SerialConfigCli::from_str("term=/dev/pts/0").unwrap() {
4886            SerialConfigCli::NewConsole(Some(path), None) => {
4887                assert_eq!(path.to_str().unwrap(), "/dev/pts/0");
4888            }
4889            _ => panic!("Expected NewConsole variant without name"),
4890        }
4891
4892        // Test TCP config
4893        match SerialConfigCli::from_str("listen=tcp:127.0.0.1:1234").unwrap() {
4894            SerialConfigCli::Tcp(addr) => {
4895                assert_eq!(addr.to_string(), "127.0.0.1:1234");
4896            }
4897            _ => panic!("Expected Tcp variant"),
4898        }
4899
4900        // Test pipe config
4901        match SerialConfigCli::from_str("listen=/path/to/pipe").unwrap() {
4902            SerialConfigCli::Pipe(path) => {
4903                assert_eq!(path.to_str().unwrap(), "/path/to/pipe");
4904            }
4905            _ => panic!("Expected Pipe variant"),
4906        }
4907
4908        // Test error cases
4909        assert!(SerialConfigCli::from_str("").is_err());
4910        assert!(SerialConfigCli::from_str("unknown").is_err());
4911        assert!(SerialConfigCli::from_str("file").is_err());
4912        assert!(SerialConfigCli::from_str("listen").is_err());
4913        assert!(SerialConfigCli::from_str("listen=tcp:").is_err());
4914        assert!(SerialConfigCli::from_str("listen=tcp:invalid").is_err());
4915    }
4916
4917    #[test]
4918    fn test_endpoint_config_from_str() {
4919        // Test none
4920        assert!(matches!(
4921            EndpointConfigCli::from_str("none").unwrap(),
4922            EndpointConfigCli::None
4923        ));
4924
4925        // Test consomme without cidr
4926        match EndpointConfigCli::from_str("consomme").unwrap() {
4927            EndpointConfigCli::Consomme {
4928                cidr: None,
4929                host_fwd,
4930            } => assert!(host_fwd.is_empty()),
4931            _ => panic!("Expected Consomme variant without cidr"),
4932        }
4933
4934        // Test consomme with cidr
4935        match EndpointConfigCli::from_str("consomme:192.168.0.0/24").unwrap() {
4936            EndpointConfigCli::Consomme {
4937                cidr: Some(cidr),
4938                host_fwd,
4939            } => {
4940                assert_eq!(cidr, "192.168.0.0/24");
4941                assert!(host_fwd.is_empty());
4942            }
4943            _ => panic!("Expected Consomme variant with cidr"),
4944        }
4945
4946        // Test consomme with hostfwd
4947        match EndpointConfigCli::from_str("consomme:hostfwd=udp:127.0.0.1:5000-:5000").unwrap() {
4948            EndpointConfigCli::Consomme { cidr, host_fwd } => {
4949                assert!(cidr.is_none());
4950                assert_eq!(host_fwd.len(), 1);
4951                assert_eq!(host_fwd[0].protocol, HostPortProtocolCli::Udp);
4952                assert_eq!(
4953                    host_fwd[0].host_address,
4954                    Some(std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
4955                );
4956                assert_eq!(host_fwd[0].host_port, 5000);
4957                assert_eq!(host_fwd[0].guest_port, 5000);
4958            }
4959            _ => panic!("Expected Consomme variant with hostfwd"),
4960        }
4961
4962        // Test consomme with cidr and hostfwd
4963        match EndpointConfigCli::from_str("consomme:10.0.0.0/24,hostfwd=tcp::2222-:22").unwrap() {
4964            EndpointConfigCli::Consomme { cidr, host_fwd } => {
4965                assert_eq!(cidr.as_deref(), Some("10.0.0.0/24"));
4966                assert_eq!(host_fwd.len(), 1);
4967                assert_eq!(host_fwd[0].protocol, HostPortProtocolCli::Tcp);
4968                assert_eq!(host_fwd[0].host_port, 2222);
4969                assert_eq!(host_fwd[0].guest_port, 22);
4970            }
4971            _ => panic!("Expected Consomme variant with cidr and hostfwd"),
4972        }
4973
4974        // Test consomme with multiple hostfwd
4975        match EndpointConfigCli::from_str("consomme:hostfwd=tcp::2222-:22,hostfwd=tcp::3389-:3389")
4976            .unwrap()
4977        {
4978            EndpointConfigCli::Consomme { cidr, host_fwd } => {
4979                assert!(cidr.is_none());
4980                assert_eq!(host_fwd.len(), 2);
4981                assert_eq!(host_fwd[0].host_port, 2222);
4982                assert_eq!(host_fwd[0].guest_port, 22);
4983                assert_eq!(host_fwd[1].host_port, 3389);
4984                assert_eq!(host_fwd[1].guest_port, 3389);
4985            }
4986            _ => panic!("Expected Consomme variant with multiple hostfwd"),
4987        }
4988
4989        // Test consomme with different host and guest ports
4990        match EndpointConfigCli::from_str("consomme:hostfwd=tcp:127.0.0.1:8080-:80").unwrap() {
4991            EndpointConfigCli::Consomme { cidr, host_fwd } => {
4992                assert!(cidr.is_none());
4993                assert_eq!(host_fwd.len(), 1);
4994                assert_eq!(host_fwd[0].protocol, HostPortProtocolCli::Tcp);
4995                assert_eq!(
4996                    host_fwd[0].host_address,
4997                    Some(std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)))
4998                );
4999                assert_eq!(host_fwd[0].host_port, 8080);
5000                assert_eq!(host_fwd[0].guest_port, 80);
5001            }
5002            _ => panic!("Expected Consomme variant with host/guest port mapping"),
5003        }
5004
5005        // Test consomme with guest address (accepted but ignored by backend)
5006        match EndpointConfigCli::from_str("consomme:hostfwd=tcp::8080-10.0.0.2:80").unwrap() {
5007            EndpointConfigCli::Consomme { cidr, host_fwd } => {
5008                assert!(cidr.is_none());
5009                assert_eq!(host_fwd[0].host_port, 8080);
5010                assert_eq!(host_fwd[0].guest_port, 80);
5011            }
5012            _ => panic!("Expected Consomme variant with guest address"),
5013        }
5014
5015        // Test consomme with IPv6 host address (bracketed)
5016        match EndpointConfigCli::from_str("consomme:hostfwd=tcp:[::1]:8080-:80").unwrap() {
5017            EndpointConfigCli::Consomme { cidr, host_fwd } => {
5018                assert!(cidr.is_none());
5019                assert_eq!(host_fwd.len(), 1);
5020                assert_eq!(host_fwd[0].protocol, HostPortProtocolCli::Tcp);
5021                assert_eq!(
5022                    host_fwd[0].host_address,
5023                    Some(std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST))
5024                );
5025                assert_eq!(host_fwd[0].host_port, 8080);
5026                assert_eq!(host_fwd[0].guest_port, 80);
5027            }
5028            _ => panic!("Expected Consomme variant with IPv6 hostfwd"),
5029        }
5030
5031        // Test consomme with IPv6 guest address (bracketed)
5032        match EndpointConfigCli::from_str("consomme:hostfwd=tcp::8080-[::1]:80").unwrap() {
5033            EndpointConfigCli::Consomme { cidr, host_fwd } => {
5034                assert!(cidr.is_none());
5035                assert_eq!(host_fwd[0].host_port, 8080);
5036                assert_eq!(host_fwd[0].guest_port, 80);
5037            }
5038            _ => panic!("Expected Consomme variant with IPv6 guest address"),
5039        }
5040
5041        // Test dio without id
5042        match EndpointConfigCli::from_str("dio").unwrap() {
5043            EndpointConfigCli::Dio { id: None } => (),
5044            _ => panic!("Expected Dio variant without id"),
5045        }
5046
5047        // Test dio with id
5048        match EndpointConfigCli::from_str("dio:test_id").unwrap() {
5049            EndpointConfigCli::Dio { id: Some(id) } => {
5050                assert_eq!(id, "test_id");
5051            }
5052            _ => panic!("Expected Dio variant with id"),
5053        }
5054
5055        // Test tap
5056        match EndpointConfigCli::from_str("tap:tap0").unwrap() {
5057            EndpointConfigCli::Tap { name } => {
5058                assert_eq!(name, "tap0");
5059            }
5060            _ => panic!("Expected Tap variant"),
5061        }
5062
5063        // Test error case
5064        assert!(EndpointConfigCli::from_str("invalid").is_err());
5065    }
5066
5067    #[test]
5068    fn test_nic_config_from_str() {
5069        use openvmm_defs::config::DeviceVtl;
5070
5071        // Test basic endpoint
5072        let config = NicConfigCli::from_str("none").unwrap();
5073        assert_eq!(config.vtl, DeviceVtl::Vtl0);
5074        assert!(config.mac_address.is_none());
5075        assert!(config.max_queues.is_none());
5076        assert!(!config.enable_rx_gso);
5077        assert!(!config.underhill);
5078        assert!(config.pcie_port.is_none());
5079        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5080
5081        let config = NicConfigCli::from_str("rx_gso:tap:tap0").unwrap();
5082        assert!(config.enable_rx_gso);
5083        assert!(matches!(
5084            config.endpoint,
5085            EndpointConfigCli::Tap { ref name } if name == "tap0"
5086        ));
5087
5088        // Test with vtl2
5089        let config = NicConfigCli::from_str("vtl2:none").unwrap();
5090        assert_eq!(config.vtl, DeviceVtl::Vtl2);
5091        assert!(config.pcie_port.is_none());
5092        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5093
5094        // Test with queues
5095        let config = NicConfigCli::from_str("queues=4:none").unwrap();
5096        assert_eq!(config.max_queues, Some(4));
5097        assert!(config.pcie_port.is_none());
5098        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5099
5100        // Test with explicit MAC address
5101        let config = NicConfigCli::from_str("mac=00-15-5d-12-12-13:none").unwrap();
5102        assert_eq!(
5103            config.mac_address,
5104            Some(MacAddress::new([0x00, 0x15, 0x5d, 0x12, 0x12, 0x13]))
5105        );
5106        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5107
5108        // Test with underhill
5109        let config = NicConfigCli::from_str("uh:none").unwrap();
5110        assert!(config.underhill);
5111        assert!(config.pcie_port.is_none());
5112        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5113
5114        // Test with pcie_port
5115        let config = NicConfigCli::from_str("pcie_port=rp0:none").unwrap();
5116        assert_eq!(config.pcie_port.unwrap(), "rp0".to_string());
5117        assert!(matches!(config.endpoint, EndpointConfigCli::None));
5118
5119        // Test error cases
5120        assert!(NicConfigCli::from_str("queues=invalid:none").is_err());
5121        assert!(NicConfigCli::from_str("mac=invalid:none").is_err());
5122        assert!(NicConfigCli::from_str("uh:vtl2:none").is_err()); // uh incompatible with vtl2
5123        assert!(NicConfigCli::from_str("pcie_port=rp0:vtl2:none").is_err());
5124        assert!(NicConfigCli::from_str("uh:pcie_port=rp0:none").is_err());
5125        assert!(NicConfigCli::from_str("pcie_port=:none").is_err());
5126        assert!(NicConfigCli::from_str("pcie_port:none").is_err());
5127    }
5128
5129    #[test]
5130    fn test_parse_pcie_port_prefix() {
5131        // Successful prefix parsing
5132        let (port, rest) = parse_pcie_port_prefix("pcie_port=rp0:tag,path");
5133        assert_eq!(port.unwrap(), "rp0");
5134        assert_eq!(rest, "tag,path");
5135
5136        // No prefix
5137        let (port, rest) = parse_pcie_port_prefix("tag,path");
5138        assert!(port.is_none());
5139        assert_eq!(rest, "tag,path");
5140
5141        // Empty port name — not parsed as a prefix
5142        let (port, rest) = parse_pcie_port_prefix("pcie_port=:tag,path");
5143        assert!(port.is_none());
5144        assert_eq!(rest, "pcie_port=:tag,path");
5145
5146        // Missing colon — not parsed as a prefix
5147        let (port, rest) = parse_pcie_port_prefix("pcie_port=rp0");
5148        assert!(port.is_none());
5149        assert_eq!(rest, "pcie_port=rp0");
5150    }
5151
5152    #[test]
5153    fn test_cxl_test_device_cli_parse_valid() {
5154        let cfg = CxlTestDeviceCli::from_str("mem:1G,pcie_port=rp0").unwrap();
5155        assert_eq!(cfg.hdm_size, 1024 * 1024 * 1024);
5156        assert_eq!(cfg.pcie_port, "rp0");
5157    }
5158
5159    #[test]
5160    fn test_cxl_test_device_cli_parse_invalid() {
5161        assert!(CxlTestDeviceCli::from_str("file:disk.img,pcie_port=rp0").is_err());
5162        assert!(CxlTestDeviceCli::from_str("mem:1G").is_err());
5163        assert!(CxlTestDeviceCli::from_str("mem:1G,pcie_port=").is_err());
5164    }
5165
5166    #[test]
5167    fn test_fs_args_pcie_port() {
5168        // Without pcie_port
5169        let args = FsArgs::from_str("myfs,/path").unwrap();
5170        assert_eq!(args.tag, "myfs");
5171        assert_eq!(args.path, "/path");
5172        assert!(args.pcie_port.is_none());
5173
5174        // With pcie_port
5175        let args = FsArgs::from_str("pcie_port=rp0:myfs,/path").unwrap();
5176        assert_eq!(args.pcie_port.unwrap(), "rp0");
5177        assert_eq!(args.tag, "myfs");
5178        assert_eq!(args.path, "/path");
5179
5180        // Error: wrong number of fields
5181        assert!(FsArgs::from_str("myfs").is_err());
5182        assert!(FsArgs::from_str("pcie_port=rp0:myfs").is_err());
5183    }
5184
5185    #[test]
5186    fn test_fs_args_with_options_pcie_port() {
5187        // Without pcie_port
5188        let args = FsArgsWithOptions::from_str("myfs,/path,uid=1000").unwrap();
5189        assert_eq!(args.tag, "myfs");
5190        assert_eq!(args.path, "/path");
5191        assert_eq!(args.options, "uid=1000");
5192        assert!(args.pcie_port.is_none());
5193
5194        // With pcie_port
5195        let args = FsArgsWithOptions::from_str("pcie_port=rp0:myfs,/path,uid=1000").unwrap();
5196        assert_eq!(args.pcie_port.unwrap(), "rp0");
5197        assert_eq!(args.tag, "myfs");
5198        assert_eq!(args.path, "/path");
5199        assert_eq!(args.options, "uid=1000");
5200
5201        // Error: missing path
5202        assert!(FsArgsWithOptions::from_str("myfs").is_err());
5203    }
5204
5205    #[test]
5206    fn test_virtio_pmem_args_pcie_port() {
5207        // Without pcie_port
5208        let args = VirtioPmemArgs::from_str("/path/to/file").unwrap();
5209        assert_eq!(args.path, "/path/to/file");
5210        assert!(args.pcie_port.is_none());
5211
5212        // With pcie_port
5213        let args = VirtioPmemArgs::from_str("pcie_port=rp0:/path/to/file").unwrap();
5214        assert_eq!(args.pcie_port.unwrap(), "rp0");
5215        assert_eq!(args.path, "/path/to/file");
5216
5217        // Error: empty path
5218        assert!(VirtioPmemArgs::from_str("").is_err());
5219        assert!(VirtioPmemArgs::from_str("pcie_port=rp0:").is_err());
5220    }
5221
5222    #[test]
5223    fn test_smt_config_from_str() {
5224        assert_eq!(SmtConfigCli::from_str("auto").unwrap(), SmtConfigCli::Auto);
5225        assert_eq!(
5226            SmtConfigCli::from_str("force").unwrap(),
5227            SmtConfigCli::Force
5228        );
5229        assert_eq!(SmtConfigCli::from_str("off").unwrap(), SmtConfigCli::Off);
5230
5231        // Test error cases
5232        assert!(SmtConfigCli::from_str("invalid").is_err());
5233        assert!(SmtConfigCli::from_str("").is_err());
5234    }
5235
5236    #[test]
5237    fn test_pcat_boot_order_from_str() {
5238        // Test single device
5239        let order = PcatBootOrderCli::from_str("optical").unwrap();
5240        assert_eq!(order.0[0], PcatBootDevice::Optical);
5241
5242        // Test multiple devices
5243        let order = PcatBootOrderCli::from_str("hdd,net").unwrap();
5244        assert_eq!(order.0[0], PcatBootDevice::HardDrive);
5245        assert_eq!(order.0[1], PcatBootDevice::Network);
5246
5247        // Test error cases
5248        assert!(PcatBootOrderCli::from_str("invalid").is_err());
5249        assert!(PcatBootOrderCli::from_str("optical,optical").is_err()); // duplicate device
5250    }
5251
5252    #[test]
5253    fn test_floppy_disk_from_str() {
5254        // Test basic disk
5255        let disk = FloppyDiskCli::from_str("file:/path/to/floppy.img").unwrap();
5256        assert!(!disk.read_only);
5257        match disk.kind {
5258            DiskCliKind::File {
5259                path,
5260                create_with_len,
5261                ..
5262            } => {
5263                assert_eq!(path.to_str().unwrap(), "/path/to/floppy.img");
5264                assert_eq!(create_with_len, None);
5265            }
5266            _ => panic!("Expected File variant"),
5267        }
5268
5269        // Test with read-only flag
5270        let disk = FloppyDiskCli::from_str("file:/path/to/floppy.img,ro").unwrap();
5271        assert!(disk.read_only);
5272
5273        // Test error cases
5274        assert!(FloppyDiskCli::from_str("").is_err());
5275        assert!(FloppyDiskCli::from_str("file:/path/to/floppy.img,invalid").is_err());
5276    }
5277
5278    #[test]
5279    fn test_pcie_root_complex_from_str() {
5280        const ONE_MB: u64 = 1024 * 1024;
5281        const ONE_GB: u64 = 1024 * ONE_MB;
5282
5283        const DEFAULT_LOW_MMIO: u32 = (64 * ONE_MB) as u32;
5284        const DEFAULT_HIGH_MMIO: u64 = ONE_GB;
5285        const DEFAULT_HDM: u64 = ONE_GB;
5286        const DEFAULT_HDM_WINDOW_RESTRICTIONS: CfmwsWindowRestrictions =
5287            CfmwsWindowRestrictions::DEVICE_COHERENT;
5288
5289        assert_eq!(
5290            PcieRootComplexCli::from_str("rc0").unwrap(),
5291            PcieRootComplexCli {
5292                name: "rc0".to_string(),
5293                segment: 0,
5294                start_bus: 0,
5295                end_bus: 255,
5296                low_mmio: DEFAULT_LOW_MMIO,
5297                high_mmio: DEFAULT_HIGH_MMIO,
5298                hdm: DEFAULT_HDM,
5299                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5300                vnode: None,
5301                low_mmio_base: None,
5302                high_mmio_base: None,
5303                preserve_bars: false,
5304            }
5305        );
5306
5307        assert_eq!(
5308            PcieRootComplexCli::from_str("rc1,segment=1").unwrap(),
5309            PcieRootComplexCli {
5310                name: "rc1".to_string(),
5311                segment: 1,
5312                start_bus: 0,
5313                end_bus: 255,
5314                low_mmio: DEFAULT_LOW_MMIO,
5315                high_mmio: DEFAULT_HIGH_MMIO,
5316                hdm: DEFAULT_HDM,
5317                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5318                vnode: None,
5319                low_mmio_base: None,
5320                high_mmio_base: None,
5321                preserve_bars: false,
5322            }
5323        );
5324
5325        assert_eq!(
5326            PcieRootComplexCli::from_str("rc2,start_bus=32").unwrap(),
5327            PcieRootComplexCli {
5328                name: "rc2".to_string(),
5329                segment: 0,
5330                start_bus: 32,
5331                end_bus: 255,
5332                low_mmio: DEFAULT_LOW_MMIO,
5333                high_mmio: DEFAULT_HIGH_MMIO,
5334                hdm: DEFAULT_HDM,
5335                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5336                vnode: None,
5337                low_mmio_base: None,
5338                high_mmio_base: None,
5339                preserve_bars: false,
5340            }
5341        );
5342
5343        assert_eq!(
5344            PcieRootComplexCli::from_str("rc3,end_bus=31").unwrap(),
5345            PcieRootComplexCli {
5346                name: "rc3".to_string(),
5347                segment: 0,
5348                start_bus: 0,
5349                end_bus: 31,
5350                low_mmio: DEFAULT_LOW_MMIO,
5351                high_mmio: DEFAULT_HIGH_MMIO,
5352                hdm: DEFAULT_HDM,
5353                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5354                vnode: None,
5355                low_mmio_base: None,
5356                high_mmio_base: None,
5357                preserve_bars: false,
5358            }
5359        );
5360
5361        assert_eq!(
5362            PcieRootComplexCli::from_str("rc4,start_bus=32,end_bus=127,high_mmio=2G").unwrap(),
5363            PcieRootComplexCli {
5364                name: "rc4".to_string(),
5365                segment: 0,
5366                start_bus: 32,
5367                end_bus: 127,
5368                low_mmio: DEFAULT_LOW_MMIO,
5369                high_mmio: 2 * ONE_GB,
5370                hdm: DEFAULT_HDM,
5371                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5372                vnode: None,
5373                low_mmio_base: None,
5374                high_mmio_base: None,
5375                preserve_bars: false,
5376            }
5377        );
5378
5379        assert_eq!(
5380            PcieRootComplexCli::from_str("rc5,segment=2,start_bus=32,end_bus=127").unwrap(),
5381            PcieRootComplexCli {
5382                name: "rc5".to_string(),
5383                segment: 2,
5384                start_bus: 32,
5385                end_bus: 127,
5386                low_mmio: DEFAULT_LOW_MMIO,
5387                high_mmio: DEFAULT_HIGH_MMIO,
5388                hdm: DEFAULT_HDM,
5389                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5390                vnode: None,
5391                low_mmio_base: None,
5392                high_mmio_base: None,
5393                preserve_bars: false,
5394            }
5395        );
5396
5397        assert_eq!(
5398            PcieRootComplexCli::from_str("rc6,low_mmio=1M,high_mmio=64G").unwrap(),
5399            PcieRootComplexCli {
5400                name: "rc6".to_string(),
5401                segment: 0,
5402                start_bus: 0,
5403                end_bus: 255,
5404                low_mmio: ONE_MB as u32,
5405                high_mmio: 64 * ONE_GB,
5406                hdm: DEFAULT_HDM,
5407                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5408                vnode: None,
5409                low_mmio_base: None,
5410                high_mmio_base: None,
5411                preserve_bars: false,
5412            }
5413        );
5414
5415        assert_eq!(
5416            PcieRootComplexCli::from_str("rc7,hdm=2G").unwrap(),
5417            PcieRootComplexCli {
5418                name: "rc7".to_string(),
5419                segment: 0,
5420                start_bus: 0,
5421                end_bus: 255,
5422                low_mmio: DEFAULT_LOW_MMIO,
5423                high_mmio: DEFAULT_HIGH_MMIO,
5424                hdm: 2 * ONE_GB,
5425                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5426                vnode: None,
5427                low_mmio_base: None,
5428                high_mmio_base: None,
5429                preserve_bars: false,
5430            }
5431        );
5432
5433        assert_eq!(
5434            PcieRootComplexCli::from_str("rc8,hdm_window_restrictions=0x21").unwrap(),
5435            PcieRootComplexCli {
5436                name: "rc8".to_string(),
5437                segment: 0,
5438                start_bus: 0,
5439                end_bus: 255,
5440                low_mmio: DEFAULT_LOW_MMIO,
5441                high_mmio: DEFAULT_HIGH_MMIO,
5442                hdm: DEFAULT_HDM,
5443                hdm_window_restrictions: CfmwsWindowRestrictions::try_from_bits(0x21).unwrap(),
5444                vnode: None,
5445                low_mmio_base: None,
5446                high_mmio_base: None,
5447                preserve_bars: false,
5448            }
5449        );
5450
5451        // Error cases
5452        assert!(PcieRootComplexCli::from_str("").is_err());
5453        assert!(PcieRootComplexCli::from_str("poorly,").is_err());
5454        assert!(PcieRootComplexCli::from_str("configured,complex").is_err());
5455        assert!(PcieRootComplexCli::from_str("fails,start_bus=foo").is_err());
5456        assert!(PcieRootComplexCli::from_str("fails,start_bus=32,end_bus=31").is_err());
5457        assert!(PcieRootComplexCli::from_str("rc,start_bus=256").is_err());
5458        assert!(PcieRootComplexCli::from_str("rc,end_bus=256").is_err());
5459        assert!(PcieRootComplexCli::from_str("rc,low_mmio=5G").is_err());
5460        assert!(PcieRootComplexCli::from_str("rc,low_mmio=aG").is_err());
5461        assert!(PcieRootComplexCli::from_str("rc,high_mmio=bad").is_err());
5462        assert!(PcieRootComplexCli::from_str("rc,high_mmio").is_err());
5463        assert!(PcieRootComplexCli::from_str("rc,hdm=bad").is_err());
5464        assert!(PcieRootComplexCli::from_str("rc,hdm").is_err());
5465        assert!(PcieRootComplexCli::from_str("rc,hdm_window_restrictions=bad").is_err());
5466        assert!(PcieRootComplexCli::from_str("rc,hdm_window_restrictions").is_err());
5467        assert!(PcieRootComplexCli::from_str("rc,cxl").is_err());
5468
5469        // node option
5470        assert_eq!(
5471            PcieRootComplexCli::from_str("rc9,node=1").unwrap(),
5472            PcieRootComplexCli {
5473                name: "rc9".to_string(),
5474                segment: 0,
5475                start_bus: 0,
5476                end_bus: 255,
5477                low_mmio: DEFAULT_LOW_MMIO,
5478                high_mmio: DEFAULT_HIGH_MMIO,
5479                hdm: DEFAULT_HDM,
5480                hdm_window_restrictions: DEFAULT_HDM_WINDOW_RESTRICTIONS,
5481                vnode: Some(1),
5482                low_mmio_base: None,
5483                high_mmio_base: None,
5484                preserve_bars: false,
5485            }
5486        );
5487    }
5488
5489    #[test]
5490    fn test_pcie_root_port_from_str() {
5491        assert_eq!(
5492            PcieRootPortCli::from_str("rc0:rc0rp0").unwrap(),
5493            PcieRootPortCli {
5494                root_complex_name: "rc0".to_string(),
5495                name: "rc0rp0".to_string(),
5496                devfn: None,
5497                hotplug: false,
5498                acs_capabilities_supported: None,
5499                cxl: false,
5500                pasid: false,
5501            }
5502        );
5503
5504        assert_eq!(
5505            PcieRootPortCli::from_str("my_rc:port2").unwrap(),
5506            PcieRootPortCli {
5507                root_complex_name: "my_rc".to_string(),
5508                name: "port2".to_string(),
5509                devfn: None,
5510                hotplug: false,
5511                acs_capabilities_supported: None,
5512                cxl: false,
5513                pasid: false,
5514            }
5515        );
5516
5517        // Test with hotplug flag
5518        assert_eq!(
5519            PcieRootPortCli::from_str("my_rc:port2,hotplug").unwrap(),
5520            PcieRootPortCli {
5521                root_complex_name: "my_rc".to_string(),
5522                name: "port2".to_string(),
5523                devfn: None,
5524                hotplug: true,
5525                acs_capabilities_supported: None,
5526                cxl: false,
5527                pasid: false,
5528            }
5529        );
5530
5531        assert_eq!(
5532            PcieRootPortCli::from_str("my_rc:port3,acs=0").unwrap(),
5533            PcieRootPortCli {
5534                root_complex_name: "my_rc".to_string(),
5535                name: "port3".to_string(),
5536                devfn: None,
5537                hotplug: false,
5538                acs_capabilities_supported: Some(0),
5539                cxl: false,
5540                pasid: false,
5541            }
5542        );
5543
5544        assert_eq!(
5545            PcieRootPortCli::from_str("my_rc:port3,acs=0x5f").unwrap(),
5546            PcieRootPortCli {
5547                root_complex_name: "my_rc".to_string(),
5548                name: "port3".to_string(),
5549                devfn: None,
5550                hotplug: false,
5551                acs_capabilities_supported: Some(0x005f),
5552                cxl: false,
5553                pasid: false,
5554            }
5555        );
5556
5557        assert_eq!(
5558            PcieRootPortCli::from_str("my_rc:port4,cxl").unwrap(),
5559            PcieRootPortCli {
5560                root_complex_name: "my_rc".to_string(),
5561                name: "port4".to_string(),
5562                devfn: None,
5563                hotplug: false,
5564                acs_capabilities_supported: None,
5565                cxl: true,
5566                pasid: false,
5567            }
5568        );
5569
5570        // Test addr= (device only, and device.function)
5571        assert_eq!(
5572            PcieRootPortCli::from_str("my_rc:port5,addr=5").unwrap(),
5573            PcieRootPortCli {
5574                root_complex_name: "my_rc".to_string(),
5575                name: "port5".to_string(),
5576                devfn: Some(5 << 3),
5577                hotplug: false,
5578                acs_capabilities_supported: None,
5579                cxl: false,
5580                pasid: false,
5581            }
5582        );
5583        assert_eq!(
5584            PcieRootPortCli::from_str("my_rc:port6,addr=5.1").unwrap(),
5585            PcieRootPortCli {
5586                root_complex_name: "my_rc".to_string(),
5587                name: "port6".to_string(),
5588                devfn: Some((5 << 3) | 1),
5589                hotplug: false,
5590                acs_capabilities_supported: None,
5591                cxl: false,
5592                pasid: false,
5593            }
5594        );
5595        assert_eq!(
5596            PcieRootPortCli::from_str("my_rc:port7,addr=0x1f.7").unwrap(),
5597            PcieRootPortCli {
5598                root_complex_name: "my_rc".to_string(),
5599                name: "port7".to_string(),
5600                devfn: Some(0xff),
5601                hotplug: false,
5602                acs_capabilities_supported: None,
5603                cxl: false,
5604                pasid: false,
5605            }
5606        );
5607
5608        assert_eq!(
5609            PcieRootPortCli::from_str("my_rc:port8,pasid").unwrap(),
5610            PcieRootPortCli {
5611                root_complex_name: "my_rc".to_string(),
5612                name: "port8".to_string(),
5613                devfn: None,
5614                hotplug: false,
5615                acs_capabilities_supported: None,
5616                cxl: false,
5617                pasid: true,
5618            }
5619        );
5620
5621        // Error cases
5622        assert!(PcieRootPortCli::from_str("").is_err());
5623        assert!(PcieRootPortCli::from_str("rp0").is_err());
5624        assert!(PcieRootPortCli::from_str("rp0,opt").is_err());
5625        assert!(PcieRootPortCli::from_str("rc0:rp0:rp3").is_err());
5626        assert!(PcieRootPortCli::from_str("rc0:rp0,invalid_option").is_err());
5627        assert!(PcieRootPortCli::from_str("rc0:rp0,cxl=true").is_err());
5628        assert!(PcieRootPortCli::from_str("rc0:rp0,addr=32").is_err());
5629        assert!(PcieRootPortCli::from_str("rc0:rp0,addr=0.8").is_err());
5630        assert!(PcieRootPortCli::from_str("rc0:rp0,addr=1.2.3").is_err());
5631        assert!(PcieRootPortCli::from_str("rc0:rp0,addr").is_err());
5632        assert!(PcieRootPortCli::from_str("rc0:rp0,pasid=foo").is_err());
5633    }
5634
5635    #[test]
5636    fn test_pcie_generic_initiator_from_str() {
5637        assert_eq!(
5638            PcieGenericInitiatorCli::from_str("port=rp0,node=1").unwrap(),
5639            PcieGenericInitiatorCli {
5640                port_name: "rp0".to_string(),
5641                node: 1,
5642            }
5643        );
5644
5645        // Order should not matter.
5646        assert_eq!(
5647            PcieGenericInitiatorCli::from_str("node=2,port=sw0-downstream-1").unwrap(),
5648            PcieGenericInitiatorCli {
5649                port_name: "sw0-downstream-1".to_string(),
5650                node: 2,
5651            }
5652        );
5653
5654        // Error cases
5655        assert!(PcieGenericInitiatorCli::from_str("").is_err());
5656        assert!(PcieGenericInitiatorCli::from_str("port=rp0").is_err());
5657        assert!(PcieGenericInitiatorCli::from_str("node=1").is_err());
5658        assert!(PcieGenericInitiatorCli::from_str("rp0=1").is_err());
5659        assert!(PcieGenericInitiatorCli::from_str("port=,node=1").is_err());
5660        assert!(PcieGenericInitiatorCli::from_str("port=rp0,node=x").is_err());
5661        assert!(PcieGenericInitiatorCli::from_str("port=rp0,node=1,extra").is_err());
5662    }
5663
5664    #[test]
5665    fn test_pcie_switch_from_str() {
5666        assert_eq!(
5667            GenericPcieSwitchCli::from_str("rp0:switch0").unwrap(),
5668            GenericPcieSwitchCli {
5669                port_name: "rp0".to_string(),
5670                name: "switch0".to_string(),
5671                num_downstream_ports: 4,
5672                hotplug: false,
5673                acs_capabilities_supported: None,
5674                pasid: false,
5675            }
5676        );
5677
5678        assert_eq!(
5679            GenericPcieSwitchCli::from_str("port1:my_switch,num_downstream_ports=4").unwrap(),
5680            GenericPcieSwitchCli {
5681                port_name: "port1".to_string(),
5682                name: "my_switch".to_string(),
5683                num_downstream_ports: 4,
5684                hotplug: false,
5685                acs_capabilities_supported: None,
5686                pasid: false,
5687            }
5688        );
5689
5690        assert_eq!(
5691            GenericPcieSwitchCli::from_str("rp2:sw,num_downstream_ports=8").unwrap(),
5692            GenericPcieSwitchCli {
5693                port_name: "rp2".to_string(),
5694                name: "sw".to_string(),
5695                num_downstream_ports: 8,
5696                hotplug: false,
5697                acs_capabilities_supported: None,
5698                pasid: false,
5699            }
5700        );
5701
5702        // Test hierarchical connections
5703        assert_eq!(
5704            GenericPcieSwitchCli::from_str("switch0-downstream-1:child_switch").unwrap(),
5705            GenericPcieSwitchCli {
5706                port_name: "switch0-downstream-1".to_string(),
5707                name: "child_switch".to_string(),
5708                num_downstream_ports: 4,
5709                hotplug: false,
5710                acs_capabilities_supported: None,
5711                pasid: false,
5712            }
5713        );
5714
5715        // Test hotplug flag
5716        assert_eq!(
5717            GenericPcieSwitchCli::from_str("rp0:switch0,hotplug").unwrap(),
5718            GenericPcieSwitchCli {
5719                port_name: "rp0".to_string(),
5720                name: "switch0".to_string(),
5721                num_downstream_ports: 4,
5722                hotplug: true,
5723                acs_capabilities_supported: None,
5724                pasid: false,
5725            }
5726        );
5727
5728        // Test hotplug with num_downstream_ports
5729        assert_eq!(
5730            GenericPcieSwitchCli::from_str("rp0:switch0,num_downstream_ports=8,hotplug").unwrap(),
5731            GenericPcieSwitchCli {
5732                port_name: "rp0".to_string(),
5733                name: "switch0".to_string(),
5734                num_downstream_ports: 8,
5735                hotplug: true,
5736                acs_capabilities_supported: None,
5737                pasid: false,
5738            }
5739        );
5740
5741        assert_eq!(
5742            GenericPcieSwitchCli::from_str("rp0:switch0,acs=0").unwrap(),
5743            GenericPcieSwitchCli {
5744                port_name: "rp0".to_string(),
5745                name: "switch0".to_string(),
5746                num_downstream_ports: 4,
5747                hotplug: false,
5748                acs_capabilities_supported: Some(0),
5749                pasid: false,
5750            }
5751        );
5752
5753        assert_eq!(
5754            GenericPcieSwitchCli::from_str("rp0:switch0,acs=95").unwrap(),
5755            GenericPcieSwitchCli {
5756                port_name: "rp0".to_string(),
5757                name: "switch0".to_string(),
5758                num_downstream_ports: 4,
5759                hotplug: false,
5760                acs_capabilities_supported: Some(95),
5761                pasid: false,
5762            }
5763        );
5764
5765        assert_eq!(
5766            GenericPcieSwitchCli::from_str("rp0:switch0,pasid").unwrap(),
5767            GenericPcieSwitchCli {
5768                port_name: "rp0".to_string(),
5769                name: "switch0".to_string(),
5770                num_downstream_ports: 4,
5771                hotplug: false,
5772                acs_capabilities_supported: None,
5773                pasid: true,
5774            }
5775        );
5776
5777        // Error cases
5778        assert!(GenericPcieSwitchCli::from_str("").is_err());
5779        assert!(GenericPcieSwitchCli::from_str("switch0").is_err());
5780        assert!(GenericPcieSwitchCli::from_str("rp0:switch0:extra").is_err());
5781        assert!(GenericPcieSwitchCli::from_str("rp0:switch0,invalid_opt=value").is_err());
5782        assert!(GenericPcieSwitchCli::from_str("rp0:switch0,num_downstream_ports=bad").is_err());
5783        assert!(GenericPcieSwitchCli::from_str("rp0:switch0,num_downstream_ports=").is_err());
5784        assert!(GenericPcieSwitchCli::from_str("rp0:switch0,invalid_flag").is_err());
5785        assert!(GenericPcieSwitchCli::from_str("rp0:switch0,pasid=bar").is_err());
5786    }
5787
5788    #[test]
5789    fn test_pcie_remote_from_str() {
5790        // Basic port name only
5791        assert_eq!(
5792            PcieRemoteCli::from_str("rc0rp0").unwrap(),
5793            PcieRemoteCli {
5794                port_name: "rc0rp0".to_string(),
5795                socket_addr: None,
5796                hu: 0,
5797                controller: 0,
5798            }
5799        );
5800
5801        // With socket address
5802        assert_eq!(
5803            PcieRemoteCli::from_str("rc0rp0,socket=localhost:22567").unwrap(),
5804            PcieRemoteCli {
5805                port_name: "rc0rp0".to_string(),
5806                socket_addr: Some("localhost:22567".to_string()),
5807                hu: 0,
5808                controller: 0,
5809            }
5810        );
5811
5812        // With all options
5813        assert_eq!(
5814            PcieRemoteCli::from_str("myport,socket=localhost:22568,hu=1,controller=2").unwrap(),
5815            PcieRemoteCli {
5816                port_name: "myport".to_string(),
5817                socket_addr: Some("localhost:22568".to_string()),
5818                hu: 1,
5819                controller: 2,
5820            }
5821        );
5822
5823        // Only hu and controller
5824        assert_eq!(
5825            PcieRemoteCli::from_str("port0,hu=5,controller=3").unwrap(),
5826            PcieRemoteCli {
5827                port_name: "port0".to_string(),
5828                socket_addr: None,
5829                hu: 5,
5830                controller: 3,
5831            }
5832        );
5833
5834        // Error cases
5835        assert!(PcieRemoteCli::from_str("").is_err());
5836        assert!(PcieRemoteCli::from_str("port,socket=").is_err());
5837        assert!(PcieRemoteCli::from_str("port,hu=").is_err());
5838        assert!(PcieRemoteCli::from_str("port,hu=bad").is_err());
5839        assert!(PcieRemoteCli::from_str("port,controller=").is_err());
5840        assert!(PcieRemoteCli::from_str("port,controller=bad").is_err());
5841        assert!(PcieRemoteCli::from_str("port,unknown=value").is_err());
5842    }
5843
5844    #[test]
5845    fn test_parse_memory_units() {
5846        assert_eq!(parse_memory("64G").unwrap(), 64 * 1024 * 1024 * 1024);
5847        assert_eq!(parse_memory("64GB").unwrap(), 64 * 1024 * 1024 * 1024);
5848        assert_eq!(parse_memory("3MB").unwrap(), 3 * 1024 * 1024);
5849        assert_eq!(parse_memory("512KB").unwrap(), 512 * 1024);
5850        assert!(parse_memory("3MiB").is_err());
5851    }
5852
5853    #[test]
5854    fn test_memory_config_size_only() {
5855        assert_eq!(
5856            parse_memory_config("64G").unwrap(),
5857            MemoryCli {
5858                size: Some(vmm_cli::MemorySize(64 * 1024 * 1024 * 1024)),
5859                ..Default::default()
5860            }
5861        );
5862    }
5863
5864    #[test]
5865    fn test_memory_config_key_value() {
5866        assert_eq!(
5867            parse_memory_config("size=2G,shared=off,prefetch=on,thp=on").unwrap(),
5868            MemoryCli {
5869                size: Some(vmm_cli::MemorySize(2 * 1024 * 1024 * 1024)),
5870                shared: Some(false),
5871                prefetch: true,
5872                transparent_hugepages: Some(true),
5873                ..Default::default()
5874            }
5875        );
5876
5877        assert_eq!(
5878            parse_memory_config("size=4GB,hugepages=on,hugepage_size=2MB").unwrap(),
5879            MemoryCli {
5880                size: Some(vmm_cli::MemorySize(4 * 1024 * 1024 * 1024)),
5881                hugepages: true,
5882                hugepage_size: Some(vmm_cli::MemorySize(2 * 1024 * 1024)),
5883                ..Default::default()
5884            }
5885        );
5886
5887        assert_eq!(
5888            parse_memory_config("file=/tmp/memory.bin").unwrap(),
5889            MemoryCli {
5890                file: Some(PathBuf::from("/tmp/memory.bin")),
5891                ..Default::default()
5892            }
5893        );
5894    }
5895
5896    #[test]
5897    fn test_memory_config_rejects_invalid_combinations() {
5898        assert!(parse_memory_config("size=1G,size=2G").is_err());
5899        assert!(parse_memory_config("hugepage_size=2M").is_err());
5900        assert!(parse_memory_config("hugepages=on,shared=off").is_err());
5901        assert!(parse_memory_config("hugepages=on,file=/tmp/memory.bin").is_err());
5902
5903        // Semantic validation of the hugepage size happens in the memory
5904        // builder, not in CLI parsing.
5905        assert_eq!(
5906            parse_memory_config("hugepages=on,hugepage_size=3MB")
5907                .unwrap()
5908                .hugepage_size,
5909            Some(vmm_cli::MemorySize(3 * 1024 * 1024))
5910        );
5911    }
5912
5913    #[test]
5914    fn test_smbios_requires_type() {
5915        // `type=` is mandatory; there is no default.
5916        assert!(parse_smbios("manufacturer=Contoso,family=Foo").is_err());
5917    }
5918
5919    #[test]
5920    fn test_smbios_all_system_keys() {
5921        let parsed = parse_smbios(
5922            "type=1,manufacturer=M,product=P,version=V,serial=S,sku=K,family=F,\
5923             uuid=12345678-9abc-def0-1234-56789abcdef0",
5924        )
5925        .unwrap();
5926        assert_eq!(
5927            parsed,
5928            SmbiosCli {
5929                system: SmbiosSystemCli {
5930                    manufacturer: Some("M".to_string()),
5931                    product_name: Some("P".to_string()),
5932                    version: Some("V".to_string()),
5933                    serial_number: Some("S".to_string()),
5934                    sku_number: Some("K".to_string()),
5935                    family: Some("F".to_string()),
5936                    uuid: Some(SmbiosUuid::Fixed(
5937                        "12345678-9abc-def0-1234-56789abcdef0"
5938                            .parse::<Guid>()
5939                            .unwrap()
5940                    )),
5941                },
5942                ..Default::default()
5943            }
5944        );
5945    }
5946
5947    #[test]
5948    fn test_smbios_bios_keys() {
5949        let parsed =
5950            parse_smbios("type=0,vendor=Contoso,version=1.0,date=01/01/2026,release=4.1").unwrap();
5951        assert_eq!(
5952            parsed,
5953            SmbiosCli {
5954                bios: SmbiosBiosCli {
5955                    vendor: Some("Contoso".to_string()),
5956                    version: Some("1.0".to_string()),
5957                    release_date: Some("01/01/2026".to_string()),
5958                    release: Some(SmbiosRelease(4, 1)),
5959                },
5960                ..Default::default()
5961            }
5962        );
5963    }
5964
5965    #[test]
5966    fn test_smbios_release_parsing() {
5967        // Valid MAJOR.MINOR.
5968        assert_eq!(
5969            parse_smbios("type=0,release=4.1").unwrap().bios.release,
5970            Some(SmbiosRelease(4, 1))
5971        );
5972        assert_eq!(
5973            parse_smbios("type=0,release=255.0").unwrap().bios.release,
5974            Some(SmbiosRelease(255, 0))
5975        );
5976        // Missing the dot, extra components, out-of-range, and non-numeric all
5977        // error.
5978        assert!(parse_smbios("type=0,release=4").is_err());
5979        assert!(parse_smbios("type=0,release=4.1.0").is_err());
5980        assert!(parse_smbios("type=0,release=256.0").is_err());
5981        assert!(parse_smbios("type=0,release=x.y").is_err());
5982        // `release` is a type=0 key only.
5983        assert!(parse_smbios("type=1,release=4.1").is_err());
5984    }
5985
5986    #[test]
5987    fn test_smbios_uuid() {
5988        // An explicit GUID parses to `Fixed`.
5989        assert_eq!(
5990            parse_smbios("type=1,uuid=12345678-9abc-def0-1234-56789abcdef0")
5991                .unwrap()
5992                .system
5993                .uuid,
5994            Some(SmbiosUuid::Fixed(
5995                "12345678-9abc-def0-1234-56789abcdef0"
5996                    .parse::<Guid>()
5997                    .unwrap()
5998            ))
5999        );
6000        // The literal `random` parses to `Random`.
6001        assert_eq!(
6002            parse_smbios("type=1,uuid=random").unwrap().system.uuid,
6003            Some(SmbiosUuid::Random)
6004        );
6005    }
6006
6007    #[test]
6008    fn test_smbios_version_disambiguated_by_type() {
6009        // `version` belongs to BIOS under type=0 and System under type=1.
6010        let bios = parse_smbios("type=0,version=1.0").unwrap();
6011        assert_eq!(bios.bios.version.as_deref(), Some("1.0"));
6012        assert_eq!(bios.system.version, None);
6013
6014        let system = parse_smbios("type=1,version=2.0").unwrap();
6015        assert_eq!(system.system.version.as_deref(), Some("2.0"));
6016        assert_eq!(system.bios.version, None);
6017    }
6018
6019    #[test]
6020    fn test_smbios_rejects_invalid() {
6021        // Missing type.
6022        assert!(parse_smbios("manufacturer=M").is_err());
6023        // Unknown key for the type.
6024        assert!(parse_smbios("type=0,manufacturer=M").is_err());
6025        assert!(parse_smbios("type=1,nonsense=x").is_err());
6026        // Unknown / unsupported type.
6027        assert!(parse_smbios("type=2,vendor=M").is_err());
6028        assert!(parse_smbios("type=bad,vendor=M").is_err());
6029        // Malformed key=value.
6030        assert!(parse_smbios("type=1,manufacturer").is_err());
6031        assert!(parse_smbios("=value").is_err());
6032        assert!(parse_smbios("type=1,manufacturer=").is_err());
6033        // Duplicate key within one argument.
6034        assert!(parse_smbios("type=1,manufacturer=A,manufacturer=B").is_err());
6035        assert!(parse_smbios("type=0,type=1,vendor=M").is_err());
6036        // Invalid UUID.
6037        assert!(parse_smbios("type=1,uuid=not-a-guid").is_err());
6038    }
6039
6040    #[test]
6041    fn test_smbios_merge_across_arguments() {
6042        let mut merged = SmbiosCli::default();
6043        merged
6044            .merge(parse_smbios("type=0,vendor=Contoso").unwrap())
6045            .unwrap();
6046        merged
6047            .merge(parse_smbios("type=1,manufacturer=M,family=F").unwrap())
6048            .unwrap();
6049        assert_eq!(
6050            merged,
6051            SmbiosCli {
6052                bios: SmbiosBiosCli {
6053                    vendor: Some("Contoso".to_string()),
6054                    ..Default::default()
6055                },
6056                system: SmbiosSystemCli {
6057                    manufacturer: Some("M".to_string()),
6058                    family: Some("F".to_string()),
6059                    ..Default::default()
6060                },
6061            }
6062        );
6063    }
6064
6065    #[test]
6066    fn test_smbios_merge_rejects_conflicts() {
6067        let mut merged = SmbiosCli::default();
6068        merged
6069            .merge(parse_smbios("type=1,manufacturer=A").unwrap())
6070            .unwrap();
6071        // The same field set by a second argument is a hard error.
6072        assert!(
6073            merged
6074                .merge(parse_smbios("type=1,manufacturer=B").unwrap())
6075                .is_err()
6076        );
6077    }
6078
6079    #[test]
6080    fn test_smbios_arg_repeatable() {
6081        let opt = Options::try_parse_from([
6082            "openvmm",
6083            "--smbios",
6084            "type=1,manufacturer=Contoso",
6085            "--smbios",
6086            "type=0,vendor=Acme",
6087        ])
6088        .unwrap();
6089        assert_eq!(opt.smbios.len(), 2);
6090        assert_eq!(
6091            opt.smbios[0].system.manufacturer.as_deref(),
6092            Some("Contoso")
6093        );
6094        assert_eq!(opt.smbios[1].bios.vendor.as_deref(), Some("Acme"));
6095    }
6096
6097    #[test]
6098    fn test_memory_options_merge_legacy_aliases() {
6099        let opt = Options::try_parse_from([
6100            "openvmm",
6101            "--memory",
6102            "2G",
6103            "--prefetch",
6104            "--private-memory",
6105            "--thp",
6106        ])
6107        .unwrap();
6108        opt.validate_memory_options().unwrap();
6109        assert_eq!(opt.memory_size(), 2 * 1024 * 1024 * 1024);
6110        assert!(opt.prefetch_memory());
6111        assert!(opt.private_memory());
6112        assert!(opt.transparent_hugepages());
6113    }
6114
6115    #[test]
6116    fn test_serial_debugger_mode_option_parsed() {
6117        // No COM port configured: no debugger mode.
6118        let opt = Options::try_parse_from(["openvmm"]).unwrap();
6119        assert!(opt.com1.is_none());
6120
6121        // A plain backend is not in debugger mode.
6122        let opt = Options::try_parse_from(["openvmm", "--com1", "none"]).unwrap();
6123        let com1 = opt.com1.unwrap();
6124        assert!(!com1.debugger_mode);
6125        assert_eq!(com1.backend, SerialConfigCli::None);
6126
6127        // The `debugger-mode:` prefix enables debugger mode for just that port,
6128        // and the remainder still parses as the backend.
6129        let opt = Options::try_parse_from([
6130            "openvmm",
6131            "--com1",
6132            "debugger-mode:listen=/tmp/kd",
6133            "--com2",
6134            "none",
6135        ])
6136        .unwrap();
6137        let com1 = opt.com1.unwrap();
6138        assert!(com1.debugger_mode);
6139        assert_eq!(com1.backend, SerialConfigCli::Pipe("/tmp/kd".into()));
6140        // Other ports remain independent (not in debugger mode).
6141        assert!(!opt.com2.unwrap().debugger_mode);
6142
6143        // The prefix must not eat colons in the backend (e.g. a tcp address).
6144        let opt = Options::try_parse_from([
6145            "openvmm",
6146            "--com1",
6147            "debugger-mode:listen=tcp:127.0.0.1:5555",
6148        ])
6149        .unwrap();
6150        let com1 = opt.com1.unwrap();
6151        assert!(com1.debugger_mode);
6152        assert_eq!(
6153            com1.backend,
6154            SerialConfigCli::Tcp("127.0.0.1:5555".parse().unwrap())
6155        );
6156    }
6157
6158    #[test]
6159    fn test_no_hv_requires_no_vmbus() {
6160        assert!(Options::try_parse_from(["openvmm", "--no-hv"]).is_err());
6161
6162        let opt = Options::try_parse_from(["openvmm", "--uefi", "--no-hv", "--no-vmbus"]).unwrap();
6163        assert!(opt.no_hv);
6164        assert!(opt.no_vmbus);
6165
6166        assert!(
6167            Options::try_parse_from(["openvmm", "--uefi", "--no-hv", "--no-vmbus", "--hv"])
6168                .is_err()
6169        );
6170    }
6171
6172    #[test]
6173    fn test_memory_options_allow_legacy_thp_with_new_private_memory() {
6174        let opt = Options::try_parse_from(["openvmm", "--memory", "shared=off", "--thp"]).unwrap();
6175        opt.validate_memory_options().unwrap();
6176        assert!(opt.private_memory());
6177        assert!(opt.transparent_hugepages());
6178    }
6179
6180    #[test]
6181    fn test_memory_options_reject_conflicting_legacy_aliases() {
6182        let opt = Options::try_parse_from(["openvmm", "--memory", "shared=on", "--private-memory"])
6183            .unwrap();
6184        assert!(opt.validate_memory_options().is_err());
6185    }
6186
6187    #[test]
6188    fn test_isolation_options_reject_snp_uefi() {
6189        let opt = Options::try_parse_from(["openvmm", "--isolation", "snp", "--uefi"]).unwrap();
6190
6191        assert_eq!(
6192            opt.validate_isolation_options().unwrap_err().to_string(),
6193            "SNP isolation currently only supports Linux direct boot"
6194        );
6195    }
6196
6197    #[test]
6198    fn test_isolation_options_reject_snp_hugepages() {
6199        for args in [
6200            vec![
6201                "openvmm",
6202                "--isolation",
6203                "snp",
6204                "--memory",
6205                "size=1G,hugepages=on",
6206            ],
6207            vec![
6208                "openvmm",
6209                "--isolation",
6210                "snp",
6211                "--numa",
6212                "size=1G,hugepages=on",
6213            ],
6214        ] {
6215            let opt = Options::try_parse_from(args).unwrap();
6216            assert_eq!(
6217                opt.validate_isolation_options().unwrap_err().to_string(),
6218                "SNP isolation currently does not support hugetlb memory"
6219            );
6220        }
6221    }
6222
6223    #[test]
6224    fn test_restricted_injection_requires_snp() {
6225        let opt = Options::try_parse_from(["openvmm", "--snp-restricted-injection"]).unwrap();
6226
6227        assert_eq!(
6228            opt.validate_isolation_options().unwrap_err().to_string(),
6229            "--snp-restricted-injection requires --isolation snp"
6230        );
6231
6232        let opt = Options::try_parse_from([
6233            "openvmm",
6234            "--isolation",
6235            "snp",
6236            "--snp-restricted-injection",
6237            "--memory",
6238            "thp=off",
6239        ])
6240        .unwrap();
6241        assert_eq!(
6242            opt.validate_isolation_options().unwrap_err().to_string(),
6243            "--snp-restricted-injection requires --hypervisor mshv"
6244        );
6245
6246        let opt = Options::try_parse_from([
6247            "openvmm",
6248            "--hypervisor",
6249            "mshv",
6250            "--isolation",
6251            "snp",
6252            "--snp-restricted-injection",
6253            "--memory",
6254            "thp=off",
6255        ])
6256        .unwrap();
6257        opt.validate_isolation_options().unwrap();
6258
6259        let opt = Options::try_parse_from([
6260            "openvmm",
6261            "--hypervisor",
6262            "mshv",
6263            "--isolation",
6264            "snp",
6265            "--snp-restricted-injection",
6266            "--pcat",
6267        ])
6268        .unwrap();
6269        assert_eq!(
6270            opt.validate_isolation_options().unwrap_err().to_string(),
6271            "--snp-restricted-injection requires Linux direct boot"
6272        );
6273
6274        let opt = Options::try_parse_from([
6275            "openvmm",
6276            "--hypervisor",
6277            "mshv",
6278            "--isolation",
6279            "snp",
6280            "--snp-restricted-injection",
6281            "--restore-snapshot",
6282            "snapshot",
6283        ])
6284        .unwrap();
6285        assert_eq!(
6286            opt.validate_isolation_options().unwrap_err().to_string(),
6287            "--snp-restricted-injection requires Linux direct boot"
6288        );
6289    }
6290
6291    #[test]
6292    fn test_isolation_options_allow_vbs_uefi() {
6293        let opt = Options::try_parse_from(["openvmm", "--isolation", "vbs", "--uefi"]).unwrap();
6294
6295        opt.validate_isolation_options().unwrap();
6296    }
6297
6298    #[test]
6299    fn test_isolation_options_allow_vbs_hugepages() {
6300        let opt = Options::try_parse_from([
6301            "openvmm",
6302            "--isolation",
6303            "vbs",
6304            "--memory",
6305            "size=1G,hugepages=on",
6306        ])
6307        .unwrap();
6308
6309        opt.validate_isolation_options().unwrap();
6310    }
6311
6312    #[test]
6313    fn test_igvm_requires_firmware_and_personality() {
6314        for (options, missing) in [
6315            ("firmware=guest.igvm", "personality"),
6316            ("personality=openhcl", "firmware"),
6317        ] {
6318            for extra in [vec![], vec!["--hv", "--vtl2"]] {
6319                let mut args = vec!["openvmm", "--igvm", options];
6320                args.extend(extra);
6321                let err = Options::try_parse_from(args).err().unwrap();
6322                assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
6323                assert!(err.to_string().contains(missing));
6324                assert!(err.to_string().contains("required"));
6325            }
6326        }
6327        let opt = Options::try_parse_from(["openvmm"]).unwrap();
6328        opt.validate_igvm_options().unwrap();
6329    }
6330
6331    #[test]
6332    fn test_igvm_personality_values() {
6333        for (value, expected) in [
6334            ("openhcl", IgvmPersonalityCli::Openhcl),
6335            ("uefi", IgvmPersonalityCli::Uefi),
6336            ("linux-direct", IgvmPersonalityCli::LinuxDirect),
6337        ] {
6338            let options = format!("firmware=guest.igvm,personality={value}");
6339            let mut args = vec!["openvmm", "--igvm", &options];
6340            if expected == IgvmPersonalityCli::Openhcl {
6341                args.extend(["--hv", "--vtl2"]);
6342            }
6343            let opt = Options::try_parse_from(args).unwrap();
6344            opt.validate_igvm_options().unwrap();
6345            assert_eq!(
6346                opt.igvm,
6347                Some(IgvmCli {
6348                    firmware: PathBuf::from("guest.igvm"),
6349                    personality: expected,
6350                })
6351            );
6352        }
6353    }
6354
6355    #[test]
6356    fn test_igvm_options_accept_reordered_keys_and_windows_paths() {
6357        let opt = Options::try_parse_from([
6358            "openvmm",
6359            "--igvm",
6360            r"personality=uefi,firmware=C:\VM Images\guest=1.igvm",
6361        ])
6362        .unwrap();
6363        assert_eq!(
6364            opt.igvm,
6365            Some(IgvmCli {
6366                firmware: PathBuf::from(r"C:\VM Images\guest=1.igvm"),
6367                personality: IgvmPersonalityCli::Uefi,
6368            })
6369        );
6370    }
6371
6372    #[test]
6373    fn test_igvm_options_reject_invalid_values() {
6374        for options in [
6375            "",
6376            "guest.igvm",
6377            "firmware=,personality=uefi",
6378            "firmware=guest.igvm,personality=",
6379            "firmware=guest.igvm,personality=pcat",
6380            "firmware=guest.igvm,personality=UEFI",
6381            "firmware=guest.igvm,personality=uefi,unknown=on",
6382            "firmware=guest.igvm,firmware=other.igvm,personality=uefi",
6383            "firmware=guest.igvm,personality=uefi,personality=linux-direct",
6384        ] {
6385            let err = Options::try_parse_from(["openvmm", "--igvm", options])
6386                .err()
6387                .unwrap();
6388            assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
6389        }
6390    }
6391
6392    #[test]
6393    fn test_igvm_rejects_separate_personality_flag() {
6394        let err = Options::try_parse_from([
6395            "openvmm",
6396            "--igvm",
6397            "firmware=guest.igvm,personality=uefi",
6398            "--igvm-personality",
6399            "uefi",
6400        ])
6401        .err()
6402        .unwrap();
6403        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
6404    }
6405
6406    #[test]
6407    fn test_openhcl_igvm_personality() {
6408        let opt = Options::try_parse_from([
6409            "openvmm",
6410            "--igvm",
6411            "firmware=guest.igvm,personality=openhcl",
6412            "--hv",
6413            "--vtl2",
6414        ])
6415        .unwrap();
6416        opt.validate_igvm_options().unwrap();
6417        assert_eq!(
6418            opt.igvm.as_ref().unwrap().personality,
6419            IgvmPersonalityCli::Openhcl
6420        );
6421        assert!(opt.effective_uefi().unwrap().is_none());
6422    }
6423
6424    #[test]
6425    fn test_openhcl_igvm_requires_explicit_vtl2_and_hv() {
6426        for extra in [vec![], vec!["--hv"], vec!["--vtl2"]] {
6427            let mut args = vec![
6428                "openvmm",
6429                "--igvm",
6430                "firmware=guest.igvm,personality=openhcl",
6431            ];
6432            args.extend(extra);
6433            match Options::try_parse_from(args) {
6434                Ok(opt) => assert_eq!(
6435                    opt.validate_igvm_options().unwrap_err().to_string(),
6436                    "--igvm personality=openhcl requires --hv --vtl2"
6437                ),
6438                Err(err) => {
6439                    assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
6440                    assert!(err.to_string().contains("--hv"));
6441                }
6442            }
6443        }
6444    }
6445
6446    #[test]
6447    fn test_non_openhcl_igvm_personalities_reject_vtl2_and_uefi() {
6448        for personality in ["uefi", "linux-direct"] {
6449            let options = format!("firmware=guest.igvm,personality={personality}");
6450            for extra in [vec!["--uefi"], vec!["--hv", "--vtl2"]] {
6451                let mut args = vec!["openvmm", "--igvm", &options];
6452                args.extend(extra);
6453                let opt = Options::try_parse_from(args).unwrap();
6454                assert!(opt.validate_igvm_options().is_err());
6455            }
6456        }
6457    }
6458
6459    #[test]
6460    fn test_openhcl_igvm_accepts_uefi_settings() {
6461        let opt = Options::try_parse_from([
6462            "openvmm",
6463            "--igvm",
6464            "firmware=guest.igvm,personality=openhcl",
6465            "--hv",
6466            "--vtl2",
6467            "--uefi",
6468            "console=com1,disable_frontpage",
6469        ])
6470        .unwrap();
6471        opt.validate_igvm_options().unwrap();
6472        let uefi = opt.effective_uefi().unwrap().unwrap();
6473        assert!(matches!(uefi.console, Some(UefiConsoleModeCli::Com1)));
6474        assert!(uefi.disable_frontpage);
6475    }
6476
6477    #[test]
6478    fn test_igvm_personality_conflicts_with_pcat() {
6479        for personality in ["openhcl", "uefi", "linux-direct"] {
6480            let options = format!("firmware=guest.igvm,personality={personality}");
6481            assert!(Options::try_parse_from(["openvmm", "--igvm", &options, "--pcat"]).is_err());
6482        }
6483    }
6484
6485    #[test]
6486    fn test_pidfile_option_parsed() {
6487        let opt = Options::try_parse_from(["openvmm", "--pidfile", "/tmp/test.pid"]).unwrap();
6488        assert_eq!(opt.pidfile, Some(PathBuf::from("/tmp/test.pid")));
6489    }
6490
6491    #[test]
6492    fn test_tpm_version_option() {
6493        let opt = Options::try_parse_from(["openvmm"]).unwrap();
6494        assert_eq!(opt.tpm, None);
6495
6496        let opt = Options::try_parse_from(["openvmm", "--tpm"]).unwrap();
6497        assert_eq!(opt.tpm, Some(TpmVersionCli::V185));
6498
6499        let opt = Options::try_parse_from(["openvmm", "--tpm", "--uefi"]).unwrap();
6500        assert_eq!(opt.tpm, Some(TpmVersionCli::V185));
6501        assert!(opt.uefi.is_some());
6502
6503        let opt = Options::try_parse_from(["openvmm", "--tpm", "138"]).unwrap();
6504        assert_eq!(opt.tpm, Some(TpmVersionCli::V138));
6505
6506        let opt = Options::try_parse_from(["openvmm", "--tpm=185"]).unwrap();
6507        assert_eq!(opt.tpm, Some(TpmVersionCli::V185));
6508
6509        let opt = Options::try_parse_from(["openvmm", "--tpm", "1.38"]).unwrap();
6510        assert_eq!(opt.tpm, Some(TpmVersionCli::V138));
6511
6512        assert!(Options::try_parse_from(["openvmm", "--tpm", "137"]).is_err());
6513    }
6514
6515    #[test]
6516    fn test_uefi_options() {
6517        let options = Options::try_parse_from(["openvmm", "--uefi"]).unwrap();
6518        assert!(options.effective_uefi().unwrap().is_some());
6519
6520        let options = Options::try_parse_from([
6521            "openvmm",
6522            "--uefi",
6523            "firmware=foo/bar,debug,force_firmware_version,console=com1,diagnostics=full",
6524        ])
6525        .unwrap();
6526        let uefi = options.effective_uefi().unwrap().unwrap();
6527        assert_eq!(uefi.firmware, Some("foo/bar".into()));
6528        assert!(uefi.debug);
6529        assert!(uefi.force_firmware_version);
6530        assert!(matches!(uefi.console, Some(UefiConsoleModeCli::Com1)));
6531        assert!(matches!(
6532            uefi.diagnostics,
6533            Some(EfiDiagnosticsLogLevelCli::Full)
6534        ));
6535
6536        let options = Options::try_parse_from([
6537            "openvmm",
6538            "--uefi",
6539            "--uefi-firmware",
6540            "legacy.fd",
6541            "--uefi-debug",
6542        ])
6543        .unwrap();
6544        let uefi = options.effective_uefi().unwrap().unwrap();
6545        assert_eq!(uefi.firmware, Some("legacy.fd".into()));
6546        assert!(uefi.debug);
6547
6548        assert!(Options::try_parse_from(["openvmm", "--uefi", "unknown"]).is_err());
6549        let options = Options::try_parse_from(["openvmm", "--uefi", "debug=on"]).unwrap();
6550        assert!(options.effective_uefi().unwrap().unwrap().debug);
6551        let options = Options::try_parse_from(["openvmm", "--uefi", "debug=off"]).unwrap();
6552        assert!(!options.effective_uefi().unwrap().unwrap().debug);
6553        assert!(Options::try_parse_from(["openvmm", "--uefi", "debug,debug"]).is_err());
6554
6555        let options = Options::try_parse_from([
6556            "openvmm",
6557            "--uefi",
6558            "firmware=new.fd",
6559            "--uefi-firmware",
6560            "legacy.fd",
6561        ])
6562        .unwrap();
6563        assert!(options.effective_uefi().is_err());
6564    }
6565
6566    #[test]
6567    fn test_guest_power_action_flags() {
6568        // Defaults preserve the historical behavior: reset and watchdog reboot,
6569        // power-off and crash keep the stopped VM.
6570        let opt = Options::try_parse_from(["openvmm"]).unwrap();
6571        assert_eq!(opt.guest_reset_action, GuestPowerAction::Reset);
6572        assert_eq!(opt.guest_shutdown_action, GuestPowerAction::Halt);
6573        assert_eq!(opt.guest_crash_action, GuestPowerAction::Halt);
6574        assert_eq!(opt.guest_watchdog_action, GuestPowerAction::Reset);
6575        // The CLI defaults must match the shared GuestPowerActions::default() the
6576        // ttrpc server uses, so the two launch paths never drift.
6577        assert_eq!(
6578            crate::vm_controller::GuestPowerActions {
6579                shutdown: opt.guest_shutdown_action,
6580                reset: opt.guest_reset_action,
6581                crash: opt.guest_crash_action,
6582                watchdog: opt.guest_watchdog_action,
6583            },
6584            crate::vm_controller::GuestPowerActions::default(),
6585        );
6586
6587        let opt = Options::try_parse_from([
6588            "openvmm",
6589            "--guest-watchdog",
6590            "--guest-reset-action",
6591            "exit",
6592            "--guest-shutdown-action",
6593            "exit:5",
6594            "--guest-crash-action",
6595            "reset",
6596            "--guest-watchdog-action",
6597            "halt",
6598        ])
6599        .unwrap();
6600        // A bare `exit` is status 0; `exit:5` carries the code through.
6601        assert_eq!(opt.guest_reset_action, GuestPowerAction::Exit(0));
6602        assert_eq!(opt.guest_shutdown_action, GuestPowerAction::Exit(5));
6603        assert_eq!(opt.guest_crash_action, GuestPowerAction::Reset);
6604        assert_eq!(opt.guest_watchdog_action, GuestPowerAction::Halt);
6605
6606        // Malformed and out-of-range exit codes are rejected (status is 0-255).
6607        assert!(Options::try_parse_from(["openvmm", "--guest-reset-action", "exit:nope"]).is_err());
6608        assert!(Options::try_parse_from(["openvmm", "--guest-reset-action", "exit:300"]).is_err());
6609        assert!(Options::try_parse_from(["openvmm", "--guest-reset-action", "exit:-1"]).is_err());
6610
6611        // --guest-watchdog-action requires the watchdog device (--guest-watchdog).
6612        assert!(Options::try_parse_from(["openvmm", "--guest-watchdog-action", "halt"]).is_err());
6613    }
6614
6615    #[cfg(target_os = "linux")]
6616    #[test]
6617    fn test_vfio_device_cli_parse() {
6618        use vfio_assigned_device_resources::BarAddressConfig;
6619
6620        // Required keys only.
6621        let v = VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0").unwrap();
6622        assert_eq!(v.pci_id, "0000:01:00.0");
6623        assert_eq!(v.port_name, "rp0");
6624        assert_eq!(v.iommu, None);
6625
6626        // With optional iommu= key. Keys may appear in any order.
6627        let v = VfioDeviceCli::from_str("port=rp1,iommu=iommu0,host=0000:02:00.0").unwrap();
6628        assert_eq!(v.pci_id, "0000:02:00.0");
6629        assert_eq!(v.port_name, "rp1");
6630        assert_eq!(v.iommu.as_deref(), Some("iommu0"));
6631
6632        let v = VfioDeviceCli::from_str(
6633            "host=0000:03:00.0,port=rp2,bar0=host,bar2=0x80000000,bar4=0x110000000000",
6634        )
6635        .unwrap();
6636        assert_eq!(v.bar_addresses[0], BarAddressConfig::HostAssigned);
6637        assert_eq!(v.bar_addresses[1], BarAddressConfig::GuestAssigned);
6638        assert_eq!(v.bar_addresses[2], BarAddressConfig::Fixed(0x80000000));
6639        assert_eq!(v.bar_addresses[4], BarAddressConfig::Fixed(0x110000000000));
6640    }
6641
6642    #[cfg(target_os = "linux")]
6643    #[test]
6644    fn test_vfio_device_cli_errors() {
6645        // Missing required keys.
6646        assert!(VfioDeviceCli::from_str("port=rp0").is_err());
6647        assert!(VfioDeviceCli::from_str("host=0000:01:00.0").is_err());
6648
6649        // Unknown key.
6650        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,foo=bar").is_err());
6651
6652        // Duplicate keys are rejected.
6653        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,host=0000:02:00.0,port=rp0").is_err());
6654        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,port=rp1").is_err());
6655        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,iommu=a,iommu=b").is_err());
6656
6657        // Empty values are rejected.
6658        assert!(VfioDeviceCli::from_str("host=,port=rp0").is_err());
6659        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=").is_err());
6660        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,iommu=").is_err());
6661
6662        // Missing '=' separator.
6663        assert!(VfioDeviceCli::from_str("host").is_err());
6664        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,iommu").is_err());
6665
6666        // Path-traversal characters in the host BDF are rejected.
6667        assert!(VfioDeviceCli::from_str("host=../../etc/passwd,port=rp0").is_err());
6668        assert!(VfioDeviceCli::from_str("host=foo/bar,port=rp0").is_err());
6669
6670        // Invalid and duplicate BAR configurations are rejected.
6671        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,bar0=0").is_err());
6672        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,bar0=0x0").is_err());
6673        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,bar0=0xnope").is_err());
6674        assert!(VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,bar0=pt").is_err());
6675        assert!(
6676            VfioDeviceCli::from_str("host=0000:01:00.0,port=rp0,bar0=0x1000,bar0=host").is_err()
6677        );
6678    }
6679
6680    #[cfg(target_os = "linux")]
6681    #[test]
6682    fn test_iommu_cli_parse() {
6683        let c = IommuCli::from_str("id=iommu0").unwrap();
6684        assert_eq!(c.id, "iommu0");
6685
6686        // Wrong key.
6687        assert!(IommuCli::from_str("name=iommu0").is_err());
6688
6689        // Missing '=' separator.
6690        assert!(IommuCli::from_str("iommu0").is_err());
6691
6692        // Empty id.
6693        assert!(IommuCli::from_str("id=").is_err());
6694    }
6695
6696    #[cfg(target_os = "linux")]
6697    #[test]
6698    fn test_vhost_user_cli() {
6699        // type=blk: socket is positional; num_queues/queue_size optional.
6700        let v = VhostUserCli::from_str("/run/blk.sock,type=blk,num_queues=2").unwrap();
6701        assert_eq!(v.socket_path, "/run/blk.sock");
6702        assert!(matches!(
6703            v.device_type,
6704            VhostUserDeviceTypeCli::Blk {
6705                num_queues: Some(2),
6706                queue_size: None
6707            }
6708        ));
6709        assert_eq!(v.pcie_port, None);
6710
6711        // type=fs requires a tag.
6712        let v = VhostUserCli::from_str("/run/fs.sock,type=fs,tag=myfs,pcie_port=p0").unwrap();
6713        assert!(matches!(
6714            &v.device_type,
6715            VhostUserDeviceTypeCli::Fs { tag, .. } if tag == "myfs"
6716        ));
6717        assert_eq!(v.pcie_port.as_deref(), Some("p0"));
6718
6719        // device_id with a bracketed queue_sizes list.
6720        let v = VhostUserCli::from_str("/run/x.sock,device_id=9,queue_sizes=[16,32]").unwrap();
6721        assert!(matches!(
6722            &v.device_type,
6723            VhostUserDeviceTypeCli::Other { device_id: 9, queue_sizes } if *queue_sizes == vec![16, 32]
6724        ));
6725
6726        // Errors.
6727        assert!(VhostUserCli::from_str("/run/x.sock").is_err()); // neither type nor device_id
6728        assert!(VhostUserCli::from_str("/run/x.sock,type=blk,device_id=1").is_err()); // both
6729        assert!(VhostUserCli::from_str("/run/x.sock,type=fs").is_err()); // fs without tag
6730        assert!(VhostUserCli::from_str("/run/x.sock,type=zzz").is_err()); // unknown type
6731        assert!(VhostUserCli::from_str("/run/x.sock,type=blk,tag=t").is_err()); // tag on non-fs
6732        assert!(VhostUserCli::from_str("/run/x.sock,type=blk,queue_sizes=[1]").is_err()); // queue_sizes on non-device_id
6733        assert!(VhostUserCli::from_str("/run/x.sock,device_id=1,num_queues=2").is_err()); // num_queues on device_id
6734        assert!(VhostUserCli::from_str("/run/x.sock,device_id=1,queue_sizes=[]").is_err()); // empty list
6735        assert!(VhostUserCli::from_str("/run/x.sock,device_id=1").is_err()); // device_id without queue_sizes
6736    }
6737
6738    #[cfg(target_os = "linux")]
6739    #[test]
6740    fn test_vhost_vsock_cli() {
6741        let opt = Options::try_parse_from(["openvmm", "--virtio-vsock-vhost-cid", "3"]).unwrap();
6742        assert_eq!(opt.virtio_vsock_vhost_cid, Some(3));
6743
6744        let opt =
6745            Options::try_parse_from(["openvmm", "--virtio-vsock-path", "/tmp/vsock"]).unwrap();
6746        assert_eq!(opt.virtio_vsock_path.as_deref(), Some("/tmp/vsock"));
6747
6748        assert!(Options::try_parse_from(["openvmm", "--virtio-vsock-vhost-cid", "2"]).is_err());
6749        assert!(
6750            Options::try_parse_from([
6751                "openvmm",
6752                "--virtio-vsock-vhost-cid",
6753                "3",
6754                "--virtio-vsock-path",
6755                "/tmp/vsock",
6756            ])
6757            .is_err()
6758        );
6759    }
6760
6761    #[test]
6762    fn test_virtio_vsock_bus_cli() {
6763        let opt = Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "mmio"]).unwrap();
6764        assert_eq!(opt.virtio_vsock_bus, Some(VirtioBusCli::Mmio));
6765
6766        let opt = Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "pci"]).unwrap();
6767        assert_eq!(opt.virtio_vsock_bus, Some(VirtioBusCli::Pci));
6768
6769        let opt = Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "pcie"]).unwrap();
6770        assert_eq!(
6771            opt.virtio_vsock_bus,
6772            Some(VirtioBusCli::Pcie("vsock".to_string()))
6773        );
6774
6775        let opt =
6776            Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "pcie:custom"]).unwrap();
6777        assert_eq!(
6778            opt.virtio_vsock_bus,
6779            Some(VirtioBusCli::Pcie("custom".to_string()))
6780        );
6781
6782        let opt =
6783            Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "PCIE:custom"]).unwrap();
6784        assert_eq!(
6785            opt.virtio_vsock_bus,
6786            Some(VirtioBusCli::Pcie("custom".to_string()))
6787        );
6788
6789        assert!(Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "auto"]).is_err());
6790        assert!(Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "vpci"]).is_err());
6791        assert!(Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "pcie:"]).is_err());
6792        assert!(
6793            Options::try_parse_from(["openvmm", "--virtio-vsock-bus", "pcie:custom:extra"])
6794                .is_err()
6795        );
6796
6797        let opt =
6798            Options::try_parse_from(["openvmm", "--virtio-rng", "--virtio-rng-bus", "pcie:custom"])
6799                .unwrap();
6800        assert_eq!(opt.virtio_rng_bus, VirtioBusCli::Pcie("custom".to_string()));
6801    }
6802
6803    #[test]
6804    fn test_virtio_rtc_cli() {
6805        let opt = Options::try_parse_from(["openvmm"]).unwrap();
6806        assert!(opt.virtio_rtc.is_none());
6807
6808        let opt =
6809            Options::try_parse_from(["openvmm", "--virtio-rtc", "--processors", "2"]).unwrap();
6810        assert_eq!(
6811            opt.virtio_rtc,
6812            Some(VirtioRtcCli {
6813                bus: VirtioBusCli::Auto
6814            })
6815        );
6816
6817        let opt = Options::try_parse_from(["openvmm", "--virtio-rtc", "bus=pcie:rp0"]).unwrap();
6818        assert_eq!(
6819            opt.virtio_rtc,
6820            Some(VirtioRtcCli {
6821                bus: VirtioBusCli::Pcie("rp0".to_string())
6822            })
6823        );
6824
6825        for value in ["mmio", "bus", "bus=", "bus=pcie:", "bus=pcie:rp0,bus=mmio"] {
6826            assert!(Options::try_parse_from(["openvmm", "--virtio-rtc", value]).is_err());
6827        }
6828    }
6829
6830    #[test]
6831    fn test_nvme_controller_cli_pcie() {
6832        let c = NvmeControllerCli::from_str("id=nvme0,pcie_port=p0").unwrap();
6833        assert_eq!(c.id, "nvme0");
6834        assert_eq!(c.transport, NvmeControllerTransport::Pcie("p0".into()));
6835    }
6836
6837    #[test]
6838    fn test_nvme_controller_cli_vpci_no_guid() {
6839        let c = NvmeControllerCli::from_str("id=nvme1,vpci").unwrap();
6840        assert_eq!(c.id, "nvme1");
6841        assert!(matches!(c.transport, NvmeControllerTransport::Vpci(None)));
6842        assert!(NvmeControllerCli::from_str("id=nvme1,vpci=").is_err());
6843    }
6844
6845    #[test]
6846    fn test_nvme_controller_cli_vpci_with_guid() {
6847        let c = NvmeControllerCli::from_str("id=nvme2,vpci=008091f6-9688-497d-9091-af347dc9173c")
6848            .unwrap();
6849        assert_eq!(c.id, "nvme2");
6850        assert!(matches!(
6851            c.transport,
6852            NvmeControllerTransport::Vpci(Some(_))
6853        ));
6854    }
6855
6856    #[test]
6857    fn test_nvme_controller_cli_errors() {
6858        // Missing id.
6859        assert!(NvmeControllerCli::from_str("pcie_port=p0").is_err());
6860        // Missing transport.
6861        assert!(NvmeControllerCli::from_str("id=nvme0").is_err());
6862        // Both transports.
6863        assert!(NvmeControllerCli::from_str("id=nvme0,pcie_port=p0,vpci").is_err());
6864        // Unknown option.
6865        assert!(NvmeControllerCli::from_str("id=nvme0,pcie_port=p0,foo=bar").is_err());
6866        // Empty id.
6867        assert!(NvmeControllerCli::from_str("id=,pcie_port=p0").is_err());
6868        // Empty pcie_port.
6869        assert!(NvmeControllerCli::from_str("id=nvme0,pcie_port=").is_err());
6870        // Invalid GUID.
6871        let err = NvmeControllerCli::from_str("id=nvme0,vpci=not-a-guid").unwrap_err();
6872        assert!(err.to_string().contains("invalid value for option 'vpci'"));
6873    }
6874
6875    #[test]
6876    fn test_disk_cli_controller() {
6877        let d = DiskCli::from_str("file:disk.vhd,on=nvme0").unwrap();
6878        assert_eq!(d.controller.as_deref(), Some("nvme0"));
6879        assert_eq!(d.nsid, None);
6880    }
6881
6882    #[test]
6883    fn test_disk_cli_serial() {
6884        let d = DiskCli::from_str("file:disk.vhd,serial=DATA-DISK").unwrap();
6885        assert_eq!(d.serial.as_deref(), Some("DATA-DISK"));
6886        assert!(DiskCli::from_str("file:disk.vhd,serial=").is_err());
6887        assert!(DiskCli::from_str("file:disk.vhd,serial=DATA[1]").is_err());
6888        assert!(DiskCli::from_str("file:disk.vhd,serial=DATA,DISK").is_err());
6889        assert!(DiskCli::from_str("file:disk.vhd,serial=DATA\u{1f}DISK").is_err());
6890        assert!(DiskCli::from_str("file:disk.vhd,serial=non-ascii-\u{e9}").is_err());
6891    }
6892
6893    #[test]
6894    fn test_disk_cli_controller_with_nsid() {
6895        let d = DiskCli::from_str("file:disk.vhd,on=nvme0,nsid=3").unwrap();
6896        assert_eq!(d.controller.as_deref(), Some("nvme0"));
6897        assert_eq!(d.nsid, Some(3));
6898    }
6899
6900    #[test]
6901    fn test_disk_cli_controller_errors() {
6902        // nsid without on.
6903        assert!(DiskCli::from_str("file:disk.vhd,nsid=1").is_err());
6904        // lun without on.
6905        assert!(DiskCli::from_str("file:disk.vhd,lun=0").is_err());
6906        // on with pcie_port.
6907        assert!(DiskCli::from_str("file:disk.vhd,on=nvme0,pcie_port=p0").is_err());
6908        // Empty controller name.
6909        assert!(DiskCli::from_str("file:disk.vhd,on=").is_err());
6910        // Invalid nsid.
6911        assert!(DiskCli::from_str("file:disk.vhd,on=nvme0,nsid=abc").is_err());
6912        // nsid and lun together.
6913        assert!(DiskCli::from_str("file:disk.vhd,on=c,nsid=1,lun=0").is_err());
6914    }
6915
6916    #[test]
6917    fn test_disk_cli_controller_with_lun() {
6918        let d = DiskCli::from_str("file:disk.vhd,on=scsi0,lun=3").unwrap();
6919        assert_eq!(d.controller.as_deref(), Some("scsi0"));
6920        assert_eq!(d.lun, Some(3));
6921        assert_eq!(d.nsid, None);
6922    }
6923
6924    #[test]
6925    fn test_scsi_controller_cli() {
6926        let c = ScsiControllerCli::from_str("id=scsi0").unwrap();
6927        assert_eq!(c.id, "scsi0");
6928        assert_eq!(c.sub_channels, 0);
6929    }
6930
6931    #[test]
6932    fn test_scsi_controller_cli_with_sub_channels() {
6933        let c = ScsiControllerCli::from_str("id=scsi1,sub_channels=4").unwrap();
6934        assert_eq!(c.id, "scsi1");
6935        assert_eq!(c.sub_channels, 4);
6936    }
6937
6938    #[test]
6939    fn test_scsi_controller_cli_errors() {
6940        // Missing id.
6941        assert!(ScsiControllerCli::from_str("sub_channels=4").is_err());
6942        // Empty id.
6943        assert!(ScsiControllerCli::from_str("id=").is_err());
6944        // Unknown option.
6945        assert!(ScsiControllerCli::from_str("id=scsi0,foo=bar").is_err());
6946        // Invalid sub_channels.
6947        assert!(ScsiControllerCli::from_str("id=scsi0,sub_channels=abc").is_err());
6948    }
6949
6950    #[test]
6951    fn test_disk_cli_relay() {
6952        let d = DiskCli::from_str("file:disk.vhd,on=src,relay=tgt").unwrap();
6953        assert_eq!(d.relay.as_ref().unwrap().0, "tgt");
6954        assert_eq!(d.relay.as_ref().unwrap().1, None);
6955    }
6956
6957    #[test]
6958    fn test_disk_cli_relay_with_location() {
6959        let d = DiskCli::from_str("file:disk.vhd,on=src,relay=tgt:3").unwrap();
6960        assert_eq!(d.relay.as_ref().unwrap().0, "tgt");
6961        assert_eq!(d.relay.as_ref().unwrap().1, Some(3));
6962    }
6963
6964    #[test]
6965    fn test_disk_cli_relay_errors() {
6966        // relay without on.
6967        assert!(DiskCli::from_str("file:disk.vhd,relay=tgt").is_err());
6968        // relay with uh.
6969        assert!(DiskCli::from_str("file:disk.vhd,on=src,relay=tgt,uh").is_err());
6970        // relay with invalid location.
6971        assert!(DiskCli::from_str("file:disk.vhd,on=src,relay=tgt:abc").is_err());
6972        // empty relay.
6973        assert!(DiskCli::from_str("file:disk.vhd,on=src,relay=").is_err());
6974    }
6975
6976    #[test]
6977    fn test_nvme_controller_cli_vtl2() {
6978        let c = NvmeControllerCli::from_str("id=nvme0,vpci,vtl2").unwrap();
6979        assert_eq!(c.vtl, DeviceVtl::Vtl2);
6980    }
6981
6982    #[test]
6983    fn test_scsi_controller_cli_vtl2() {
6984        let c = ScsiControllerCli::from_str("id=scsi0,vtl2").unwrap();
6985        assert_eq!(c.vtl, DeviceVtl::Vtl2);
6986    }
6987
6988    #[test]
6989    fn test_openhcl_controller_cli() {
6990        let c = OpenhclControllerCli::from_str("id=vtl0-scsi,type=scsi").unwrap();
6991        assert_eq!(c.id, "vtl0-scsi");
6992        assert_eq!(c.controller_type, OpenhclControllerType::Scsi);
6993        assert_eq!(c.guid, None);
6994    }
6995
6996    #[test]
6997    fn test_openhcl_controller_cli_nvme_with_guid() {
6998        let c = OpenhclControllerCli::from_str(
6999            "id=vtl0-nvme,type=nvme,guid=09a59b81-2bf6-4164-81d7-3a0dc977ba65",
7000        )
7001        .unwrap();
7002        assert_eq!(c.controller_type, OpenhclControllerType::Nvme);
7003        assert!(c.guid.is_some());
7004    }
7005
7006    #[test]
7007    fn test_openhcl_controller_cli_errors() {
7008        // Missing id.
7009        assert!(OpenhclControllerCli::from_str("type=scsi").is_err());
7010        // Missing type.
7011        assert!(OpenhclControllerCli::from_str("id=foo").is_err());
7012        // Invalid type.
7013        assert!(OpenhclControllerCli::from_str("id=foo,type=ide").is_err());
7014        // Invalid guid.
7015        assert!(OpenhclControllerCli::from_str("id=foo,type=scsi,guid=bad").is_err());
7016    }
7017
7018    #[test]
7019    fn test_parse_vp_list() {
7020        use vmm_cli::BracketRangeList;
7021
7022        let parse = |s: &str| {
7023            s.parse::<BracketRangeList>()
7024                .and_then(|v| v.expand_below(1024))
7025        };
7026
7027        // Individual indices.
7028        assert_eq!(parse("[0,1,2,3]").unwrap(), vec![0, 1, 2, 3]);
7029
7030        // Single index.
7031        assert_eq!(parse("[5]").unwrap(), vec![5]);
7032
7033        // Dash range.
7034        assert_eq!(parse("[0-3]").unwrap(), vec![0, 1, 2, 3]);
7035
7036        // Mixed indices and ranges.
7037        assert_eq!(parse("[0,1,4-6,10]").unwrap(), vec![0, 1, 4, 5, 6, 10]);
7038
7039        // Whitespace tolerance.
7040        assert_eq!(parse("[0, 1, 2-4]").unwrap(), vec![0, 1, 2, 3, 4]);
7041
7042        // Missing brackets.
7043        assert!(parse("0,1,2").is_err());
7044        assert!(parse("0-3").is_err());
7045
7046        // Inverted range.
7047        assert!(parse("[3-0]").is_err());
7048
7049        // Non-numeric.
7050        assert!(parse("[a,b]").is_err());
7051    }
7052
7053    #[test]
7054    fn test_parse_numa_node() {
7055        use super::parse_numa_node;
7056
7057        // Basic node with size only.
7058        let n = parse_numa_node("size=2G").unwrap();
7059        assert_eq!(
7060            n.memory.size,
7061            Some(vmm_cli::MemorySize(2 * 1024 * 1024 * 1024))
7062        );
7063        assert!(n.vps.is_none());
7064        assert!(n.host_numa_node.is_none());
7065
7066        // Node with bracket VP list.
7067        let n = parse_numa_node("size=1G,vps=[0,1,2,3]").unwrap();
7068        assert_eq!(n.vps.unwrap().expand_below(1024).unwrap(), [0, 1, 2, 3]);
7069
7070        // Node with VP range in brackets.
7071        let n = parse_numa_node("size=1G,vps=[0-3]").unwrap();
7072        assert_eq!(n.vps.unwrap().expand_below(1024).unwrap(), [0, 1, 2, 3]);
7073
7074        // Node with host_numa_node.
7075        let n = parse_numa_node("size=1G,host_numa_node=1").unwrap();
7076        assert_eq!(n.host_numa_node, Some(1));
7077
7078        // All options together.
7079        let n = parse_numa_node("size=1G,vps=[0,1],host_numa_node=0,hugepages=on").unwrap();
7080        assert_eq!(n.vps.unwrap().expand_below(1024).unwrap(), [0, 1]);
7081        assert_eq!(n.host_numa_node, Some(0));
7082        assert!(n.memory.hugepages);
7083
7084        // Missing size.
7085        assert!(parse_numa_node("vps=[0,1]").is_err());
7086
7087        // Bare vps without brackets.
7088        assert!(parse_numa_node("size=1G,vps=0,1").is_err());
7089
7090        // Duplicate vps.
7091        assert!(parse_numa_node("size=1G,vps=[0],vps=[1]").is_err());
7092
7093        // `file` is rejected for NUMA nodes.
7094        assert!(parse_numa_node("size=1G,file=/tmp/x").is_err());
7095
7096        // Empty vps=[] for memory-only node.
7097        let n = parse_numa_node("size=1G,vps=[]").unwrap();
7098        assert!(n.vps.unwrap().0.is_empty());
7099    }
7100
7101    #[test]
7102    fn test_parse_numa_distance() {
7103        use super::parse_numa_distance;
7104
7105        let d = parse_numa_distance("0:1:20").unwrap();
7106        assert_eq!(d.src, 0);
7107        assert_eq!(d.dst, 1);
7108        assert_eq!(d.distance, 20);
7109
7110        // Self-distance.
7111        let d = parse_numa_distance("0:0:10").unwrap();
7112        assert_eq!(d.distance, 10);
7113
7114        // Distance below minimum.
7115        assert!(parse_numa_distance("0:1:5").is_err());
7116
7117        // Wrong format.
7118        assert!(parse_numa_distance("0:1").is_err());
7119        assert!(parse_numa_distance("0:1:20:extra").is_err());
7120    }
7121
7122    #[cfg(guest_arch = "aarch64")]
7123    #[test]
7124    fn test_smmu_cli_from_str() {
7125        // Minimal: only rc=, sizing policies default to auto, accel off.
7126        let s = SmmuCli::from_str("rc=pcie0").unwrap();
7127        assert_eq!(s.rc_name, "pcie0");
7128        assert!(!s.accel);
7129        assert!(matches!(s.oas, SmmuOasCli::Auto));
7130        assert!(matches!(s.ssidsize, SmmuSsidSizeCli::Auto));
7131
7132        // accel flag.
7133        let s = SmmuCli::from_str("rc=pcie0,accel").unwrap();
7134        assert_eq!(s.rc_name, "pcie0");
7135        assert!(s.accel);
7136        assert!(matches!(s.oas, SmmuOasCli::Auto));
7137        assert!(matches!(s.ssidsize, SmmuSsidSizeCli::Auto));
7138
7139        // Explicit oas=auto.
7140        let s = SmmuCli::from_str("rc=pcie0,oas=auto").unwrap();
7141        assert!(matches!(s.oas, SmmuOasCli::Auto));
7142
7143        // Fixed oas.
7144        let s = SmmuCli::from_str("rc=pcie0,oas=52").unwrap();
7145        assert!(matches!(s.oas, SmmuOasCli::Fixed(52)));
7146
7147        // All keys/flags together, order independent.
7148        let s = SmmuCli::from_str("ssidsize=12,oas=48,accel,rc=pcie1").unwrap();
7149        assert_eq!(s.rc_name, "pcie1");
7150        assert!(s.accel);
7151        assert!(matches!(s.oas, SmmuOasCli::Fixed(48)));
7152        assert!(matches!(s.ssidsize, SmmuSsidSizeCli::Fixed(12)));
7153
7154        // Missing required rc=.
7155        assert!(SmmuCli::from_str("accel").is_err());
7156        assert!(SmmuCli::from_str("oas=52").is_err());
7157
7158        // Empty rc= value.
7159        assert!(SmmuCli::from_str("rc=").is_err());
7160
7161        // Duplicate rc= key.
7162        assert!(SmmuCli::from_str("rc=pcie0,rc=pcie1").is_err());
7163
7164        // Non-numeric oas value.
7165        assert!(SmmuCli::from_str("rc=pcie0,oas=big").is_err());
7166
7167        // Unknown key.
7168        assert!(SmmuCli::from_str("rc=pcie0,foo=bar").is_err());
7169
7170        // Unknown flag.
7171        assert!(SmmuCli::from_str("rc=pcie0,turbo").is_err());
7172    }
7173
7174    #[cfg(guest_arch = "aarch64")]
7175    #[test]
7176    fn test_smmu_cli_ssidsize() {
7177        for accel in ["", ",accel"] {
7178            let s = SmmuCli::from_str(&format!("rc=pcie0,ssidsize=auto{accel}")).unwrap();
7179            assert!(matches!(s.ssidsize, SmmuSsidSizeCli::Auto));
7180
7181            // Device configuration validates supported widths, not the parser.
7182            for bits in [0, 14, 20, 21, 255] {
7183                let s = SmmuCli::from_str(&format!("rc=pcie0,ssidsize={bits}{accel}")).unwrap();
7184                assert!(matches!(s.ssidsize, SmmuSsidSizeCli::Fixed(n) if n == bits));
7185            }
7186        }
7187
7188        for value in ["256", "-1", "1.5", "", "big", "AUTO"] {
7189            assert!(
7190                SmmuCli::from_str(&format!("rc=pcie0,ssidsize={value}")).is_err(),
7191                "accepted invalid ssidsize={value}"
7192            );
7193        }
7194        assert!(SmmuCli::from_str("ssidsize=12").is_err());
7195        assert!(SmmuCli::from_str("rc=pcie0,ssidsize=auto,ssidsize=12").is_err());
7196    }
7197}