crosvm/
main.rs

1// Copyright 2017 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Runs a virtual machine
6//!
7//! ## Feature flags
8#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
9
10#[cfg(any(feature = "composite-disk", feature = "qcow"))]
11use std::fs::OpenOptions;
12#[cfg(feature = "composite-disk")]
13use std::io::Write;
14use std::path::Path;
15
16use anyhow::anyhow;
17use anyhow::Context;
18use anyhow::Result;
19use argh::FromArgs;
20use base::debug;
21use base::error;
22use base::info;
23use base::set_thread_name;
24use base::syslog;
25use base::syslog::LogArgs;
26use base::syslog::LogConfig;
27use cmdline::RunCommand;
28mod crosvm;
29use crosvm::cmdline;
30use crosvm::config::Config;
31use devices::virtio::vhost_user_backend::run_block_device;
32#[cfg(feature = "gpu")]
33use devices::virtio::vhost_user_backend::run_gpu_device;
34#[cfg(feature = "net")]
35use devices::virtio::vhost_user_backend::run_net_device;
36#[cfg(feature = "audio")]
37use devices::virtio::vhost_user_backend::run_snd_device;
38#[cfg(feature = "composite-disk")]
39use disk::create_composite_disk;
40#[cfg(feature = "composite-disk")]
41use disk::create_zero_filler;
42#[cfg(feature = "composite-disk")]
43use disk::open_disk_file;
44#[cfg(any(feature = "composite-disk", feature = "qcow"))]
45use disk::DiskFileParams;
46#[cfg(feature = "composite-disk")]
47use disk::ImagePartitionType;
48#[cfg(feature = "composite-disk")]
49use disk::PartitionInfo;
50#[cfg(feature = "qcow")]
51use disk::QcowFile;
52mod sys;
53use crosvm::cmdline::Command;
54use crosvm::cmdline::CrossPlatformCommands;
55use crosvm::cmdline::CrossPlatformDevicesCommands;
56#[cfg(windows)]
57use sys::windows::setup_metrics_reporting;
58#[cfg(feature = "composite-disk")]
59use uuid::Uuid;
60#[cfg(feature = "gpu")]
61use vm_control::client::do_gpu_display_add;
62#[cfg(feature = "gpu")]
63use vm_control::client::do_gpu_display_list;
64#[cfg(feature = "gpu")]
65use vm_control::client::do_gpu_display_remove;
66#[cfg(feature = "gpu")]
67use vm_control::client::do_gpu_set_display_mouse_mode;
68use vm_control::client::do_modify_battery;
69#[cfg(feature = "pci-hotplug")]
70use vm_control::client::do_net_add;
71#[cfg(feature = "pci-hotplug")]
72use vm_control::client::do_net_remove;
73use vm_control::client::do_security_key_attach;
74#[cfg(feature = "audio")]
75use vm_control::client::do_snd_mute_all;
76use vm_control::client::do_swap_status;
77use vm_control::client::do_usb_attach;
78use vm_control::client::do_usb_detach;
79use vm_control::client::do_usb_list;
80#[cfg(feature = "balloon")]
81use vm_control::client::handle_request;
82use vm_control::client::vms_request;
83#[cfg(feature = "gpu")]
84use vm_control::client::ModifyGpuResult;
85use vm_control::client::ModifyUsbResult;
86#[cfg(feature = "balloon")]
87use vm_control::BalloonControlCommand;
88use vm_control::DiskControlCommand;
89use vm_control::HotPlugDeviceInfo;
90use vm_control::HotPlugDeviceType;
91use vm_control::SnapshotCommand;
92use vm_control::SwapCommand;
93use vm_control::UsbControlResult;
94use vm_control::VmRequest;
95#[cfg(feature = "balloon")]
96use vm_control::VmResponse;
97
98use crate::sys::error_to_exit_code;
99use crate::sys::init_log;
100
101#[cfg(feature = "scudo")]
102#[global_allocator]
103static ALLOCATOR: scudo::GlobalScudoAllocator = scudo::GlobalScudoAllocator;
104
105#[repr(i32)]
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107/// Exit code from crosvm,
108enum CommandStatus {
109    /// Exit with success. Also used to mean VM stopped successfully.
110    SuccessOrVmStop = 0,
111    /// VM requested reset.
112    VmReset = 32,
113    /// VM crashed.
114    VmCrash = 33,
115    /// VM exit due to kernel panic in guest.
116    GuestPanic = 34,
117    /// Invalid argument was given to crosvm.
118    InvalidArgs = 35,
119    /// VM exit due to vcpu stall detection.
120    WatchdogReset = 36,
121}
122
123impl CommandStatus {
124    fn message(&self) -> &'static str {
125        match self {
126            Self::SuccessOrVmStop => "exiting with success",
127            Self::VmReset => "exiting with reset",
128            Self::VmCrash => "exiting with crash",
129            Self::GuestPanic => "exiting with guest panic",
130            Self::InvalidArgs => "invalid argument",
131            Self::WatchdogReset => "exiting with watchdog reset",
132        }
133    }
134}
135
136impl From<sys::ExitState> for CommandStatus {
137    fn from(result: sys::ExitState) -> CommandStatus {
138        match result {
139            sys::ExitState::Stop => CommandStatus::SuccessOrVmStop,
140            sys::ExitState::Reset => CommandStatus::VmReset,
141            sys::ExitState::Crash => CommandStatus::VmCrash,
142            sys::ExitState::GuestPanic => CommandStatus::GuestPanic,
143            sys::ExitState::WatchdogReset => CommandStatus::WatchdogReset,
144        }
145    }
146}
147
148fn run_vm(cmd: RunCommand, log_config: LogConfig) -> Result<CommandStatus> {
149    let cfg = match TryInto::<Config>::try_into(cmd) {
150        Ok(cfg) => cfg,
151        Err(e) => {
152            eprintln!("{e}");
153            return Err(anyhow!("{}", e));
154        }
155    };
156
157    if let Some(ref name) = cfg.name {
158        set_thread_name(name).context("Failed to set the name")?;
159    }
160
161    #[cfg(feature = "crash-report")]
162    crosvm::sys::setup_emulator_crash_reporting(&cfg)?;
163
164    #[cfg(windows)]
165    setup_metrics_reporting()?;
166
167    init_log(log_config, &cfg)?;
168    cros_tracing::init();
169
170    if let Some(async_executor) = cfg.async_executor {
171        cros_async::Executor::set_default_executor_kind(async_executor)
172            .context("Failed to set the default async executor")?;
173    }
174
175    let exit_state = crate::sys::run_config(cfg)?;
176    Ok(CommandStatus::from(exit_state))
177}
178
179fn stop_vms(cmd: cmdline::StopCommand) -> std::result::Result<(), ()> {
180    vms_request(&VmRequest::Exit, cmd.socket_path)
181}
182
183fn suspend_vms(cmd: cmdline::SuspendCommand) -> std::result::Result<(), ()> {
184    if cmd.full {
185        vms_request(&VmRequest::SuspendVm, cmd.socket_path)
186    } else {
187        vms_request(&VmRequest::SuspendVcpus, cmd.socket_path)
188    }
189}
190
191fn swap_vms(cmd: cmdline::SwapCommand) -> std::result::Result<(), ()> {
192    use cmdline::SwapSubcommands::*;
193    let (req, path) = match &cmd.nested {
194        Enable(params) => (VmRequest::Swap(SwapCommand::Enable), &params.socket_path),
195        Trim(params) => (VmRequest::Swap(SwapCommand::Trim), &params.socket_path),
196        SwapOut(params) => (VmRequest::Swap(SwapCommand::SwapOut), &params.socket_path),
197        Disable(params) => (
198            VmRequest::Swap(SwapCommand::Disable {
199                slow_file_cleanup: params.slow_file_cleanup,
200            }),
201            &params.socket_path,
202        ),
203        Status(params) => (VmRequest::Swap(SwapCommand::Status), &params.socket_path),
204    };
205    if let VmRequest::Swap(SwapCommand::Status) = req {
206        do_swap_status(path)
207    } else {
208        vms_request(&req, path)
209    }
210}
211
212fn resume_vms(cmd: cmdline::ResumeCommand) -> std::result::Result<(), ()> {
213    if cmd.full {
214        vms_request(&VmRequest::ResumeVm, cmd.socket_path)
215    } else {
216        vms_request(&VmRequest::ResumeVcpus, cmd.socket_path)
217    }
218}
219
220fn powerbtn_vms(cmd: cmdline::PowerbtnCommand) -> std::result::Result<(), ()> {
221    vms_request(&VmRequest::Powerbtn, cmd.socket_path)
222}
223
224fn sleepbtn_vms(cmd: cmdline::SleepCommand) -> std::result::Result<(), ()> {
225    vms_request(&VmRequest::Sleepbtn, cmd.socket_path)
226}
227
228fn inject_gpe(cmd: cmdline::GpeCommand) -> std::result::Result<(), ()> {
229    vms_request(
230        &VmRequest::Gpe {
231            gpe: cmd.gpe,
232            clear_evt: None,
233        },
234        cmd.socket_path,
235    )
236}
237
238#[cfg(feature = "balloon")]
239fn balloon_vms(cmd: cmdline::BalloonCommand) -> std::result::Result<(), ()> {
240    let command = BalloonControlCommand::Adjust {
241        num_bytes: cmd.num_bytes,
242        wait_for_success: cmd.wait,
243    };
244    vms_request(&VmRequest::BalloonCommand(command), cmd.socket_path)
245}
246
247#[cfg(feature = "balloon")]
248fn balloon_stats(cmd: cmdline::BalloonStatsCommand) -> std::result::Result<(), ()> {
249    let command = BalloonControlCommand::Stats {};
250    let request = &VmRequest::BalloonCommand(command);
251    let response = handle_request(request, cmd.socket_path)?;
252    match serde_json::to_string_pretty(&response) {
253        Ok(response_json) => println!("{response_json}"),
254        Err(e) => {
255            error!("Failed to serialize into JSON: {}", e);
256            return Err(());
257        }
258    }
259    match response {
260        VmResponse::BalloonStats { .. } => Ok(()),
261        _ => Err(()),
262    }
263}
264
265#[cfg(feature = "balloon")]
266fn balloon_ws(cmd: cmdline::BalloonWsCommand) -> std::result::Result<(), ()> {
267    let command = BalloonControlCommand::WorkingSet {};
268    let request = &VmRequest::BalloonCommand(command);
269    let response = handle_request(request, cmd.socket_path)?;
270    match serde_json::to_string_pretty(&response) {
271        Ok(response_json) => println!("{response_json}"),
272        Err(e) => {
273            error!("Failed to serialize into JSON: {e}");
274            return Err(());
275        }
276    }
277    match response {
278        VmResponse::BalloonWS { .. } => Ok(()),
279        _ => Err(()),
280    }
281}
282
283fn modify_battery(cmd: cmdline::BatteryCommand) -> std::result::Result<(), ()> {
284    do_modify_battery(
285        cmd.socket_path,
286        &cmd.battery_type,
287        &cmd.property,
288        &cmd.target,
289    )
290}
291
292fn modify_vfio(cmd: cmdline::VfioCrosvmCommand) -> std::result::Result<(), ()> {
293    let (request, socket_path, vfio_path) = match cmd.command {
294        cmdline::VfioSubCommand::Add(c) => {
295            let request = VmRequest::HotPlugVfioCommand {
296                device: HotPlugDeviceInfo {
297                    device_type: HotPlugDeviceType::EndPoint,
298                    path: c.vfio_path.clone(),
299                    hp_interrupt: true,
300                },
301                add: true,
302            };
303            (request, c.socket_path, c.vfio_path)
304        }
305        cmdline::VfioSubCommand::Remove(c) => {
306            let request = VmRequest::HotPlugVfioCommand {
307                device: HotPlugDeviceInfo {
308                    device_type: HotPlugDeviceType::EndPoint,
309                    path: c.vfio_path.clone(),
310                    hp_interrupt: false,
311                },
312                add: false,
313            };
314            (request, c.socket_path, c.vfio_path)
315        }
316    };
317    if !vfio_path.exists() || !vfio_path.is_dir() {
318        error!("Invalid host sysfs path: {:?}", vfio_path);
319        return Err(());
320    }
321
322    vms_request(&request, socket_path)?;
323    Ok(())
324}
325
326#[cfg(feature = "pci-hotplug")]
327fn modify_virtio_net(cmd: cmdline::VirtioNetCommand) -> std::result::Result<(), ()> {
328    match cmd.command {
329        cmdline::VirtioNetSubCommand::AddTap(c) => {
330            let bus_num = do_net_add(&c.tap_name, c.socket_path).map_err(|e| {
331                error!("{}", &e);
332            })?;
333            info!("Tap device {} plugged to PCI bus {}", &c.tap_name, bus_num);
334        }
335        cmdline::VirtioNetSubCommand::RemoveTap(c) => {
336            do_net_remove(c.bus, &c.socket_path).map_err(|e| {
337                error!("Tap device remove failed: {:?}", &e);
338            })?;
339            info!("Tap device removed from PCI bus {}", &c.bus);
340        }
341    };
342
343    Ok(())
344}
345
346#[cfg(feature = "composite-disk")]
347fn parse_composite_partition_arg(
348    partition_arg: &str,
349) -> std::result::Result<(String, String, bool, Option<Uuid>), ()> {
350    let mut partition_fields = partition_arg.split(':');
351
352    let label = partition_fields.next();
353    let path = partition_fields.next();
354    let opt = partition_fields.next();
355    let part_guid = partition_fields.next();
356
357    if let (Some(label), Some(path)) = (label, path) {
358        // By default, composite disk is read-only
359        let writable = match opt {
360            None => false,
361            Some("") => false,
362            Some("writable") => true,
363            Some(value) => {
364                error!(
365                    "Unrecognized option '{}'. Expected 'writable' or nothing.",
366                    value
367                );
368                return Err(());
369            }
370        };
371
372        let part_guid = part_guid
373            .map(Uuid::parse_str)
374            .transpose()
375            .map_err(|e| error!("Invalid partition GUID: {}", e))?;
376
377        Ok((label.to_owned(), path.to_owned(), writable, part_guid))
378    } else {
379        error!(
380            "Must specify label and path for partition '{}', like LABEL:PARTITION",
381            partition_arg
382        );
383        Err(())
384    }
385}
386
387#[cfg(feature = "composite-disk")]
388fn create_composite(cmd: cmdline::CreateCompositeCommand) -> std::result::Result<(), ()> {
389    use std::io::BufWriter;
390    use std::path::PathBuf;
391
392    let composite_image_path = &cmd.path;
393    let zero_filler_path = format!("{composite_image_path}.filler");
394    let header_path = format!("{composite_image_path}.header");
395    let footer_path = format!("{composite_image_path}.footer");
396
397    let mut composite_image_file = OpenOptions::new()
398        .create(true)
399        .read(true)
400        .write(true)
401        .truncate(true)
402        .open(composite_image_path)
403        .map_err(|e| {
404            error!(
405                "Failed opening composite disk image file at '{}': {}",
406                composite_image_path, e
407            );
408        })?;
409    create_zero_filler(&zero_filler_path).map_err(|e| {
410        error!(
411            "Failed to create zero filler file at '{}': {}",
412            &zero_filler_path, e
413        );
414    })?;
415    let header_file = OpenOptions::new()
416        .create(true)
417        .read(true)
418        .write(true)
419        .truncate(true)
420        .open(&header_path)
421        .map_err(|e| {
422            error!(
423                "Failed opening header image file at '{}': {}",
424                header_path, e
425            );
426        })?;
427    let mut header_buffer = BufWriter::new(header_file);
428    let footer_file = OpenOptions::new()
429        .create(true)
430        .read(true)
431        .write(true)
432        .truncate(true)
433        .open(&footer_path)
434        .map_err(|e| {
435            error!(
436                "Failed opening footer image file at '{}': {}",
437                footer_path, e
438            );
439        })?;
440    let mut footer_buffer = BufWriter::new(footer_file);
441
442    let partitions = cmd
443        .partitions
444        .into_iter()
445        .map(|partition_arg| {
446            let (label, path, writable, part_guid) = parse_composite_partition_arg(&partition_arg)?;
447
448            // Sparseness for composite disks is not user provided on Linux
449            // (e.g. via an option), and it has no runtime effect.
450            let size = open_disk_file(DiskFileParams {
451                path: PathBuf::from(&path),
452                is_read_only: !writable,
453                is_sparse_file: true,
454                ..Default::default()
455            })
456            .map_err(|e| error!("Failed to create DiskFile instance: {}", e))?
457            .get_len()
458            .map_err(|e| error!("Failed to get length of partition image: {}", e))?;
459
460            Ok(PartitionInfo {
461                label,
462                path: Path::new(&path).to_owned(),
463                partition_type: ImagePartitionType::LinuxFilesystem,
464                writable,
465                size,
466                part_guid,
467            })
468        })
469        .collect::<Result<Vec<PartitionInfo>, ()>>()?;
470
471    create_composite_disk(
472        &partitions,
473        &PathBuf::from(zero_filler_path),
474        &PathBuf::from(header_path),
475        &mut header_buffer,
476        &PathBuf::from(footer_path),
477        &mut footer_buffer,
478        &mut composite_image_file,
479    )
480    .map_err(|e| {
481        error!(
482            "Failed to create composite disk image at '{}': {}",
483            composite_image_path, e
484        );
485    })?;
486    header_buffer.flush().map_err(|e| {
487        error!("Failed to flush header buffer: {}", e);
488    })?;
489    footer_buffer.flush().map_err(|e| {
490        error!("Failed to flush footer buffer: {}", e);
491    })?;
492
493    Ok(())
494}
495
496#[cfg(feature = "qcow")]
497fn create_qcow2(cmd: cmdline::CreateQcow2Command) -> std::result::Result<(), ()> {
498    use std::path::PathBuf;
499
500    if !(cmd.size.is_some() ^ cmd.backing_file.is_some()) {
501        println!(
502            "Create a new QCOW2 image at `PATH` of either the specified `SIZE` in bytes or
503    with a '--backing_file'."
504        );
505        return Err(());
506    }
507
508    let file = OpenOptions::new()
509        .create(true)
510        .read(true)
511        .write(true)
512        .truncate(true)
513        .open(&cmd.file_path)
514        .map_err(|e| {
515            error!("Failed opening qcow file at '{}': {}", cmd.file_path, e);
516        })?;
517
518    let params = DiskFileParams {
519        path: PathBuf::from(&cmd.file_path),
520        ..Default::default()
521    };
522    match (cmd.size, cmd.backing_file) {
523        (Some(size), None) => QcowFile::new(file, params, size).map_err(|e| {
524            error!("Failed to create qcow file at '{}': {}", cmd.file_path, e);
525        })?,
526        (None, Some(backing_file)) => QcowFile::new_from_backing(file, params, &backing_file)
527            .map_err(|e| {
528                error!("Failed to create qcow file at '{}': {}", cmd.file_path, e);
529            })?,
530        _ => unreachable!(),
531    };
532    Ok(())
533}
534
535fn start_device(opts: cmdline::DeviceCommand) -> std::result::Result<(), ()> {
536    if let Some(async_executor) = opts.async_executor {
537        cros_async::Executor::set_default_executor_kind(async_executor)
538            .map_err(|e| error!("Failed to set the default async executor: {:#}", e))?;
539    }
540
541    let result = match opts.command {
542        cmdline::DeviceSubcommand::CrossPlatform(command) => match command {
543            CrossPlatformDevicesCommands::Block(cfg) => run_block_device(cfg),
544            #[cfg(feature = "gpu")]
545            CrossPlatformDevicesCommands::Gpu(cfg) => run_gpu_device(cfg),
546            #[cfg(feature = "net")]
547            CrossPlatformDevicesCommands::Net(cfg) => run_net_device(cfg),
548            #[cfg(feature = "audio")]
549            CrossPlatformDevicesCommands::Snd(cfg) => run_snd_device(cfg),
550        },
551        cmdline::DeviceSubcommand::Sys(command) => sys::start_device(command),
552    };
553
554    result.map_err(|e| {
555        error!("Failed to run device: {:#}", e);
556    })
557}
558
559fn disk_cmd(cmd: cmdline::DiskCommand) -> std::result::Result<(), ()> {
560    match cmd.command {
561        cmdline::DiskSubcommand::Resize(cmd) => {
562            let request = VmRequest::DiskCommand {
563                disk_index: cmd.disk_index,
564                command: DiskControlCommand::Resize {
565                    new_size: cmd.disk_size,
566                },
567            };
568            vms_request(&request, cmd.socket_path)
569        }
570    }
571}
572
573fn make_rt(cmd: cmdline::MakeRTCommand) -> std::result::Result<(), ()> {
574    vms_request(&VmRequest::MakeRT, cmd.socket_path)
575}
576
577#[cfg(feature = "gpu")]
578fn gpu_display_add(cmd: cmdline::GpuAddDisplaysCommand) -> ModifyGpuResult {
579    do_gpu_display_add(cmd.socket_path, cmd.gpu_display)
580}
581
582#[cfg(feature = "gpu")]
583fn gpu_display_list(cmd: cmdline::GpuListDisplaysCommand) -> ModifyGpuResult {
584    do_gpu_display_list(cmd.socket_path)
585}
586
587#[cfg(feature = "gpu")]
588fn gpu_display_remove(cmd: cmdline::GpuRemoveDisplaysCommand) -> ModifyGpuResult {
589    do_gpu_display_remove(cmd.socket_path, cmd.display_id)
590}
591
592#[cfg(feature = "gpu")]
593fn gpu_set_display_mouse_mode(cmd: cmdline::GpuSetDisplayMouseModeCommand) -> ModifyGpuResult {
594    do_gpu_set_display_mouse_mode(cmd.socket_path, cmd.display_id, cmd.mouse_mode)
595}
596
597#[cfg(feature = "gpu")]
598fn modify_gpu(cmd: cmdline::GpuCommand) -> std::result::Result<(), ()> {
599    let result = match cmd.command {
600        cmdline::GpuSubCommand::AddDisplays(cmd) => gpu_display_add(cmd),
601        cmdline::GpuSubCommand::ListDisplays(cmd) => gpu_display_list(cmd),
602        cmdline::GpuSubCommand::RemoveDisplays(cmd) => gpu_display_remove(cmd),
603        cmdline::GpuSubCommand::SetDisplayMouseMode(cmd) => gpu_set_display_mouse_mode(cmd),
604    };
605    match result {
606        Ok(response) => {
607            println!("{response}");
608            Ok(())
609        }
610        Err(e) => {
611            println!("error {e}");
612            Err(())
613        }
614    }
615}
616
617#[cfg(feature = "audio")]
618fn modify_snd(cmd: cmdline::SndCommand) -> std::result::Result<(), ()> {
619    match cmd.command {
620        cmdline::SndSubCommand::MuteAll(cmd) => do_snd_mute_all(cmd.socket_path, cmd.muted),
621    }
622}
623
624fn usb_attach(cmd: cmdline::UsbAttachCommand) -> ModifyUsbResult<UsbControlResult> {
625    let dev_path = Path::new(&cmd.dev_path);
626
627    do_usb_attach(cmd.socket_path, dev_path)
628}
629
630fn security_key_attach(cmd: cmdline::UsbAttachKeyCommand) -> ModifyUsbResult<UsbControlResult> {
631    let dev_path = Path::new(&cmd.dev_path);
632
633    do_security_key_attach(cmd.socket_path, dev_path)
634}
635
636fn usb_detach(cmd: cmdline::UsbDetachCommand) -> ModifyUsbResult<UsbControlResult> {
637    do_usb_detach(cmd.socket_path, cmd.port)
638}
639
640fn usb_list(cmd: cmdline::UsbListCommand) -> ModifyUsbResult<UsbControlResult> {
641    do_usb_list(cmd.socket_path)
642}
643
644fn modify_usb(cmd: cmdline::UsbCommand) -> std::result::Result<(), ()> {
645    let result = match cmd.command {
646        cmdline::UsbSubCommand::Attach(cmd) => usb_attach(cmd),
647        cmdline::UsbSubCommand::SecurityKeyAttach(cmd) => security_key_attach(cmd),
648        cmdline::UsbSubCommand::Detach(cmd) => usb_detach(cmd),
649        cmdline::UsbSubCommand::List(cmd) => usb_list(cmd),
650    };
651    match result {
652        Ok(response) => {
653            println!("{response}");
654            Ok(())
655        }
656        Err(e) => {
657            println!("error {e}");
658            Err(())
659        }
660    }
661}
662
663fn snapshot_vm(cmd: cmdline::SnapshotCommand) -> std::result::Result<(), ()> {
664    use cmdline::SnapshotSubCommands::*;
665    let (socket_path, request) = match cmd.snapshot_command {
666        Take(take_cmd) => {
667            let req = VmRequest::Snapshot(SnapshotCommand::Take {
668                snapshot_path: take_cmd.snapshot_path,
669                compress_memory: take_cmd.compress_memory,
670                encrypt: take_cmd.encrypt,
671            });
672            (take_cmd.socket_path, req)
673        }
674    };
675    let socket_path = Path::new(&socket_path);
676    vms_request(&request, socket_path)
677}
678
679#[allow(clippy::unnecessary_wraps)]
680fn pkg_version() -> std::result::Result<(), ()> {
681    const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
682    const PKG_VERSION: Option<&'static str> = option_env!("PKG_VERSION");
683
684    print!("crosvm {}", VERSION.unwrap_or("UNKNOWN"));
685    match PKG_VERSION {
686        Some(v) => println!("-{v}"),
687        None => println!(),
688    }
689    Ok(())
690}
691
692// Returns true if the argument is a flag (e.g. `-s` or `--long`).
693//
694// As a special case, `-` is not treated as a flag, since it is typically used to represent
695// `stdin`/`stdout`.
696fn is_flag(arg: &str) -> bool {
697    arg.len() > 1 && arg.starts_with('-')
698}
699
700// Perform transformations on `args_iter` to produce arguments suitable for parsing by `argh`.
701fn prepare_argh_args<I: IntoIterator<Item = String>>(args_iter: I) -> Vec<String> {
702    let mut args: Vec<String> = Vec::default();
703    // http://b/235882579
704    for arg in args_iter {
705        match arg.as_str() {
706            "--host_ip" => {
707                eprintln!("`--host_ip` option is deprecated!");
708                eprintln!("Please use `--host-ip` instead");
709                args.push("--host-ip".to_string());
710            }
711            "-h" => args.push("--help".to_string()),
712            arg if is_flag(arg) => {
713                // Split `--arg=val` into `--arg val`, since argh doesn't support the former.
714                if let Some((key, value)) = arg.split_once('=') {
715                    args.push(key.to_string());
716                    args.push(value.to_string());
717                } else {
718                    args.push(arg.to_string());
719                }
720            }
721            arg => args.push(arg.to_string()),
722        }
723    }
724
725    args
726}
727
728fn shorten_usage(help: &str) -> String {
729    let mut lines = help.lines().collect::<Vec<_>>();
730    let first_line = lines[0].split(char::is_whitespace).collect::<Vec<_>>();
731
732    // Shorten the usage line if it's for `crovm run` command that has so many options.
733    let run_usage = format!("Usage: {} run <options> KERNEL", first_line[1]);
734    if first_line[0] == "Usage:" && first_line[2] == "run" {
735        lines[0] = &run_usage;
736    }
737
738    lines.join("\n")
739}
740
741fn crosvm_main<I: IntoIterator<Item = String>>(args: I) -> Result<CommandStatus> {
742    // The following panic hook will stop our crashpad hook on windows.
743    // Only initialize when the crash-pad feature is off.
744    #[cfg(not(feature = "crash-report"))]
745    sys::set_panic_hook();
746
747    // Ensure all processes detach from metrics on exit.
748    #[cfg(windows)]
749    let _metrics_destructor = metrics::get_destructor();
750
751    let args = prepare_argh_args(args);
752    let args = args.iter().map(|s| s.as_str()).collect::<Vec<_>>();
753    let args = match crosvm::cmdline::CrosvmCmdlineArgs::from_args(&args[..1], &args[1..]) {
754        Ok(args) => args,
755        Err(e) if e.status.is_ok() => {
756            // If parsing succeeded and the user requested --help, print the usage message to stdout
757            // and exit with success.
758            let help = shorten_usage(&e.output);
759            println!("{help}");
760            return Ok(CommandStatus::SuccessOrVmStop);
761        }
762        Err(e) => {
763            error!("arg parsing failed: {}", e.output);
764            return Ok(CommandStatus::InvalidArgs);
765        }
766    };
767    let extended_status = args.extended_status;
768
769    debug!("CLI arguments parsed.");
770
771    let mut log_config = LogConfig {
772        log_args: LogArgs {
773            filter: args.log_level,
774            proc_name: args.syslog_tag.unwrap_or("crosvm".to_string()),
775            syslog: !args.no_syslog,
776            ..Default::default()
777        },
778
779        ..Default::default()
780    };
781
782    let ret = match args.command {
783        Command::CrossPlatform(command) => {
784            // Past this point, usage of exit is in danger of leaking zombie processes.
785            if let CrossPlatformCommands::Run(cmd) = command {
786                if let Some(syslog_tag) = &cmd.syslog_tag {
787                    base::warn!(
788                        "`crosvm run --syslog-tag` is deprecated; please use \
789                         `crosvm --syslog-tag=\"{}\" run` instead",
790                        syslog_tag
791                    );
792                    log_config.log_args.proc_name.clone_from(syslog_tag);
793                }
794                // We handle run_vm separately because it does not simply signal success/error
795                // but also indicates whether the guest requested reset or stop.
796                run_vm(cmd, log_config)
797            } else if let CrossPlatformCommands::Device(cmd) = command {
798                // On windows, the device command handles its own logging setup, so we can't handle
799                // it below otherwise logging will double init.
800                if cfg!(unix) {
801                    syslog::init_with(log_config).context("failed to initialize syslog")?;
802                }
803                start_device(cmd)
804                    .map_err(|_| anyhow!("start_device subcommand failed"))
805                    .map(|_| CommandStatus::SuccessOrVmStop)
806            } else {
807                syslog::init_with(log_config).context("failed to initialize syslog")?;
808
809                match command {
810                    #[cfg(feature = "balloon")]
811                    CrossPlatformCommands::Balloon(cmd) => {
812                        balloon_vms(cmd).map_err(|_| anyhow!("balloon subcommand failed"))
813                    }
814                    #[cfg(feature = "balloon")]
815                    CrossPlatformCommands::BalloonStats(cmd) => {
816                        balloon_stats(cmd).map_err(|_| anyhow!("balloon_stats subcommand failed"))
817                    }
818                    #[cfg(feature = "balloon")]
819                    CrossPlatformCommands::BalloonWs(cmd) => {
820                        balloon_ws(cmd).map_err(|_| anyhow!("balloon_ws subcommand failed"))
821                    }
822                    CrossPlatformCommands::Battery(cmd) => {
823                        modify_battery(cmd).map_err(|_| anyhow!("battery subcommand failed"))
824                    }
825                    #[cfg(feature = "composite-disk")]
826                    CrossPlatformCommands::CreateComposite(cmd) => create_composite(cmd)
827                        .map_err(|_| anyhow!("create_composite subcommand failed")),
828                    #[cfg(feature = "qcow")]
829                    CrossPlatformCommands::CreateQcow2(cmd) => {
830                        create_qcow2(cmd).map_err(|_| anyhow!("create_qcow2 subcommand failed"))
831                    }
832                    CrossPlatformCommands::Device(_) => unreachable!(),
833                    CrossPlatformCommands::Disk(cmd) => {
834                        disk_cmd(cmd).map_err(|_| anyhow!("disk subcommand failed"))
835                    }
836                    #[cfg(feature = "gpu")]
837                    CrossPlatformCommands::Gpu(cmd) => {
838                        modify_gpu(cmd).map_err(|_| anyhow!("gpu subcommand failed"))
839                    }
840                    #[cfg(feature = "audio")]
841                    CrossPlatformCommands::Snd(cmd) => {
842                        modify_snd(cmd).map_err(|_| anyhow!("snd command failed"))
843                    }
844                    CrossPlatformCommands::MakeRT(cmd) => {
845                        make_rt(cmd).map_err(|_| anyhow!("make_rt subcommand failed"))
846                    }
847                    CrossPlatformCommands::Resume(cmd) => {
848                        resume_vms(cmd).map_err(|_| anyhow!("resume subcommand failed"))
849                    }
850                    CrossPlatformCommands::Run(_) => unreachable!(),
851                    CrossPlatformCommands::Stop(cmd) => {
852                        stop_vms(cmd).map_err(|_| anyhow!("stop subcommand failed"))
853                    }
854                    CrossPlatformCommands::Suspend(cmd) => {
855                        suspend_vms(cmd).map_err(|_| anyhow!("suspend subcommand failed"))
856                    }
857                    CrossPlatformCommands::Swap(cmd) => {
858                        swap_vms(cmd).map_err(|_| anyhow!("swap subcommand failed"))
859                    }
860                    CrossPlatformCommands::Powerbtn(cmd) => {
861                        powerbtn_vms(cmd).map_err(|_| anyhow!("powerbtn subcommand failed"))
862                    }
863                    CrossPlatformCommands::Sleepbtn(cmd) => {
864                        sleepbtn_vms(cmd).map_err(|_| anyhow!("sleepbtn subcommand failed"))
865                    }
866                    CrossPlatformCommands::Gpe(cmd) => {
867                        inject_gpe(cmd).map_err(|_| anyhow!("gpe subcommand failed"))
868                    }
869                    CrossPlatformCommands::Usb(cmd) => {
870                        modify_usb(cmd).map_err(|_| anyhow!("usb subcommand failed"))
871                    }
872                    CrossPlatformCommands::Version(_) => {
873                        pkg_version().map_err(|_| anyhow!("version subcommand failed"))
874                    }
875                    CrossPlatformCommands::Vfio(cmd) => {
876                        modify_vfio(cmd).map_err(|_| anyhow!("vfio subcommand failed"))
877                    }
878                    #[cfg(feature = "pci-hotplug")]
879                    CrossPlatformCommands::VirtioNet(cmd) => {
880                        modify_virtio_net(cmd).map_err(|_| anyhow!("virtio subcommand failed"))
881                    }
882                    CrossPlatformCommands::Snapshot(cmd) => {
883                        snapshot_vm(cmd).map_err(|_| anyhow!("snapshot subcommand failed"))
884                    }
885                }
886                .map(|_| CommandStatus::SuccessOrVmStop)
887            }
888        }
889        cmdline::Command::Sys(command) => {
890            let log_args = log_config.log_args.clone();
891            // On windows, the sys commands handle their own logging setup, so we can't handle it
892            // below otherwise logging will double init.
893            if cfg!(unix) {
894                syslog::init_with(log_config).context("failed to initialize syslog")?;
895            }
896            sys::run_command(command, log_args).map(|_| CommandStatus::SuccessOrVmStop)
897        }
898    };
899
900    sys::cleanup();
901
902    // WARNING: Any code added after this point is not guaranteed to run
903    // since we may forcibly kill this process (and its children) above.
904    ret.map(|s| {
905        if extended_status {
906            s
907        } else {
908            CommandStatus::SuccessOrVmStop
909        }
910    })
911}
912
913fn main() {
914    syslog::early_init();
915    debug!("crosvm started.");
916    let res = crosvm_main(std::env::args());
917
918    let exit_code = match &res {
919        Ok(code) => {
920            info!("{}", code.message());
921            *code as i32
922        }
923        Err(e) => {
924            let exit_code = error_to_exit_code(&res);
925            error!("exiting with error {}: {:?}", exit_code, e);
926            exit_code
927        }
928    };
929    std::process::exit(exit_code);
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935
936    #[test]
937    fn args_is_flag() {
938        assert!(is_flag("--test"));
939        assert!(is_flag("-s"));
940
941        assert!(!is_flag("-"));
942        assert!(!is_flag("no-leading-dash"));
943    }
944
945    #[test]
946    fn args_split_long() {
947        assert_eq!(
948            prepare_argh_args(
949                ["crosvm", "run", "--something=options", "vm_kernel"].map(|x| x.to_string())
950            ),
951            ["crosvm", "run", "--something", "options", "vm_kernel"]
952        );
953    }
954
955    #[test]
956    fn args_split_short() {
957        assert_eq!(
958            prepare_argh_args(
959                ["crosvm", "run", "-p=init=/bin/bash", "vm_kernel"].map(|x| x.to_string())
960            ),
961            ["crosvm", "run", "-p", "init=/bin/bash", "vm_kernel"]
962        );
963    }
964
965    #[test]
966    fn args_host_ip() {
967        assert_eq!(
968            prepare_argh_args(
969                ["crosvm", "run", "--host_ip", "1.2.3.4", "vm_kernel"].map(|x| x.to_string())
970            ),
971            ["crosvm", "run", "--host-ip", "1.2.3.4", "vm_kernel"]
972        );
973    }
974
975    #[test]
976    fn args_h() {
977        assert_eq!(
978            prepare_argh_args(["crosvm", "run", "-h"].map(|x| x.to_string())),
979            ["crosvm", "run", "--help"]
980        );
981    }
982
983    #[test]
984    fn args_battery_option() {
985        assert_eq!(
986            prepare_argh_args(
987                [
988                    "crosvm",
989                    "run",
990                    "--battery",
991                    "type=goldfish",
992                    "-p",
993                    "init=/bin/bash",
994                    "vm_kernel"
995                ]
996                .map(|x| x.to_string())
997            ),
998            [
999                "crosvm",
1000                "run",
1001                "--battery",
1002                "type=goldfish",
1003                "-p",
1004                "init=/bin/bash",
1005                "vm_kernel"
1006            ]
1007        );
1008    }
1009
1010    #[test]
1011    fn help_success() {
1012        let args = ["crosvm", "--help"];
1013        let res = crosvm_main(args.iter().map(|s| s.to_string()));
1014        let status = res.expect("arg parsing should succeed");
1015        assert_eq!(status, CommandStatus::SuccessOrVmStop);
1016    }
1017
1018    #[test]
1019    fn invalid_arg_failure() {
1020        let args = ["crosvm", "--heeeelp"];
1021        let res = crosvm_main(args.iter().map(|s| s.to_string()));
1022        let status = res.expect("arg parsing should succeed");
1023        assert_eq!(status, CommandStatus::InvalidArgs);
1024    }
1025
1026    #[test]
1027    #[cfg(feature = "composite-disk")]
1028    fn parse_composite_disk_arg() {
1029        let arg1 = String::from("LABEL1:/partition1.img:writable");
1030        let res1 = parse_composite_partition_arg(&arg1);
1031        assert_eq!(
1032            res1,
1033            Ok((
1034                String::from("LABEL1"),
1035                String::from("/partition1.img"),
1036                true,
1037                None
1038            ))
1039        );
1040
1041        let arg2 = String::from("LABEL2:/partition2.img");
1042        let res2 = parse_composite_partition_arg(&arg2);
1043        assert_eq!(
1044            res2,
1045            Ok((
1046                String::from("LABEL2"),
1047                String::from("/partition2.img"),
1048                false,
1049                None
1050            ))
1051        );
1052
1053        let arg3 =
1054            String::from("LABEL3:/partition3.img:writable:4049C8DC-6C2B-C740-A95A-BDAA629D4378");
1055        let res3 = parse_composite_partition_arg(&arg3);
1056        assert_eq!(
1057            res3,
1058            Ok((
1059                String::from("LABEL3"),
1060                String::from("/partition3.img"),
1061                true,
1062                Some(Uuid::from_u128(0x4049C8DC_6C2B_C740_A95A_BDAA629D4378))
1063            ))
1064        );
1065
1066        // third argument is an empty string. writable: false.
1067        let arg4 = String::from("LABEL4:/partition4.img::4049C8DC-6C2B-C740-A95A-BDAA629D4378");
1068        let res4 = parse_composite_partition_arg(&arg4);
1069        assert_eq!(
1070            res4,
1071            Ok((
1072                String::from("LABEL4"),
1073                String::from("/partition4.img"),
1074                false,
1075                Some(Uuid::from_u128(0x4049C8DC_6C2B_C740_A95A_BDAA629D4378))
1076            ))
1077        );
1078
1079        // third argument is not "writable" or an empty string
1080        let arg5 = String::from("LABEL5:/partition5.img:4049C8DC-6C2B-C740-A95A-BDAA629D4378");
1081        let res5 = parse_composite_partition_arg(&arg5);
1082        assert_eq!(res5, Err(()));
1083    }
1084
1085    #[test]
1086    fn test_shorten_run_usage() {
1087        let help = r"Usage: crosvm run [<KERNEL>] [options] <very long line>...
1088
1089Start a new crosvm instance";
1090        assert_eq!(
1091            shorten_usage(help),
1092            r"Usage: crosvm run <options> KERNEL
1093
1094Start a new crosvm instance"
1095        );
1096    }
1097}