1 // Copyright 2021, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Functions for running instances of `crosvm`.
16 
17 use crate::aidl::{remove_temporary_files, Cid, GLOBAL_SERVICE, VirtualMachineCallbacks};
18 use crate::atom::{get_num_cpus, write_vm_exited_stats_sync};
19 use crate::debug_config::DebugConfig;
20 use anyhow::{anyhow, bail, Context, Error, Result};
21 use binder::ParcelFileDescriptor;
22 use command_fds::CommandFdExt;
23 use lazy_static::lazy_static;
24 use libc::{sysconf, _SC_CLK_TCK};
25 use log::{debug, error, info};
26 use semver::{Version, VersionReq};
27 use nix::{fcntl::OFlag, unistd::pipe2, unistd::Uid, unistd::User};
28 use regex::{Captures, Regex};
29 use rustutils::system_properties;
30 use shared_child::SharedChild;
31 use std::borrow::Cow;
32 use std::cmp::max;
33 use std::fmt;
34 use std::fs::{read_to_string, File};
35 use std::io::{self, Read};
36 use std::mem;
37 use std::num::{NonZeroU16, NonZeroU32};
38 use std::os::unix::io::{AsRawFd, OwnedFd, RawFd};
39 use std::os::unix::process::ExitStatusExt;
40 use std::path::{Path, PathBuf};
41 use std::process::{Command, ExitStatus};
42 use std::sync::{Arc, Condvar, Mutex};
43 use std::time::{Duration, SystemTime};
44 use std::thread::{self, JoinHandle};
45 use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
46 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
47     MemoryTrimLevel::MemoryTrimLevel,
48     VirtualMachineAppConfig::DebugLevel::DebugLevel,
49     DisplayConfig::DisplayConfig as DisplayConfigParcelable,
50     GpuConfig::GpuConfig as GpuConfigParcelable,
51 };
52 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
53 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IBoundDevice::IBoundDevice;
54 use binder::Strong;
55 use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
56 use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
57 use rpcbinder::RpcServer;
58 
59 /// external/crosvm
60 use base::AsRawDescriptor;
61 use base::UnixSeqpacketListener;
62 use vm_control::{BalloonControlCommand, VmRequest, VmResponse};
63 
64 const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
65 
66 /// Version of the platform that crosvm currently implements. The format follows SemVer. This
67 /// should be updated when there is a platform change in the crosvm side. Having this value here is
68 /// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
69 /// APEX.
70 const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
71 
72 /// The exit status which crosvm returns when it has an error starting a VM.
73 const CROSVM_START_ERROR_STATUS: i32 = 1;
74 /// The exit status which crosvm returns when a VM requests a reboot.
75 const CROSVM_REBOOT_STATUS: i32 = 32;
76 /// The exit status which crosvm returns when it crashes due to an error.
77 const CROSVM_CRASH_STATUS: i32 = 33;
78 /// The exit status which crosvm returns when vcpu is stalled.
79 const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
80 /// The size of memory (in MiB) reserved for ramdump
81 const RAMDUMP_RESERVED_MIB: u32 = 17;
82 
83 const MILLIS_PER_SEC: i64 = 1000;
84 
85 const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path";
86 
87 /// Serial device for VM console input.
88 /// Hypervisor (virtio-console)
89 const CONSOLE_HVC0: &str = "hvc0";
90 /// Serial (emulated uart)
91 const CONSOLE_TTYS0: &str = "ttyS0";
92 
93 lazy_static! {
94     /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
95     /// triggered.
96     static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
97         // Nested virtualization is slow, so we need a longer timeout.
98         Duration::from_secs(300)
99     } else {
100         Duration::from_secs(30)
101     };
102 }
103 
104 /// Configuration for a VM to run with crosvm.
105 #[derive(Debug)]
106 pub struct CrosvmConfig {
107     pub cid: Cid,
108     pub name: String,
109     pub bootloader: Option<File>,
110     pub kernel: Option<File>,
111     pub initrd: Option<File>,
112     pub disks: Vec<DiskFile>,
113     pub params: Option<String>,
114     pub protected: bool,
115     pub debug_config: DebugConfig,
116     pub memory_mib: Option<NonZeroU32>,
117     pub cpus: Option<NonZeroU32>,
118     pub host_cpu_topology: bool,
119     pub console_out_fd: Option<File>,
120     pub console_in_fd: Option<File>,
121     pub log_fd: Option<File>,
122     pub ramdump: Option<File>,
123     pub indirect_files: Vec<File>,
124     pub platform_version: VersionReq,
125     pub detect_hangup: bool,
126     pub gdb_port: Option<NonZeroU16>,
127     pub vfio_devices: Vec<VfioDevice>,
128     pub dtbo: Option<File>,
129     pub device_tree_overlay: Option<File>,
130     pub display_config: Option<DisplayConfig>,
131     pub input_device_options: Vec<InputDeviceOption>,
132     pub hugepages: bool,
133     pub tap: Option<File>,
134     pub virtio_snd_backend: Option<String>,
135     pub console_input_device: Option<String>,
136     pub boost_uclamp: bool,
137     pub gpu_config: Option<GpuConfig>,
138 }
139 
140 #[derive(Debug)]
141 pub struct DisplayConfig {
142     pub width: NonZeroU32,
143     pub height: NonZeroU32,
144     pub horizontal_dpi: NonZeroU32,
145     pub vertical_dpi: NonZeroU32,
146     pub refresh_rate: NonZeroU32,
147 }
148 
149 impl DisplayConfig {
new(raw_config: &DisplayConfigParcelable) -> Result<DisplayConfig>150     pub fn new(raw_config: &DisplayConfigParcelable) -> Result<DisplayConfig> {
151         let width = try_into_non_zero_u32(raw_config.width)?;
152         let height = try_into_non_zero_u32(raw_config.height)?;
153         let horizontal_dpi = try_into_non_zero_u32(raw_config.horizontalDpi)?;
154         let vertical_dpi = try_into_non_zero_u32(raw_config.verticalDpi)?;
155         let refresh_rate = try_into_non_zero_u32(raw_config.refreshRate)?;
156         Ok(DisplayConfig { width, height, horizontal_dpi, vertical_dpi, refresh_rate })
157     }
158 }
159 
160 #[derive(Debug)]
161 pub struct GpuConfig {
162     pub backend: Option<String>,
163     pub context_types: Option<Vec<String>>,
164     pub pci_address: Option<String>,
165     pub renderer_features: Option<String>,
166     pub renderer_use_egl: Option<bool>,
167     pub renderer_use_gles: Option<bool>,
168     pub renderer_use_glx: Option<bool>,
169     pub renderer_use_surfaceless: Option<bool>,
170     pub renderer_use_vulkan: Option<bool>,
171 }
172 
173 impl GpuConfig {
new(raw_config: &GpuConfigParcelable) -> Result<GpuConfig>174     pub fn new(raw_config: &GpuConfigParcelable) -> Result<GpuConfig> {
175         Ok(GpuConfig {
176             backend: raw_config.backend.clone(),
177             context_types: raw_config.contextTypes.clone().map(|context_types| {
178                 context_types.iter().filter_map(|context_type| context_type.clone()).collect()
179             }),
180             pci_address: raw_config.pciAddress.clone(),
181             renderer_features: raw_config.rendererFeatures.clone(),
182             renderer_use_egl: Some(raw_config.rendererUseEgl),
183             renderer_use_gles: Some(raw_config.rendererUseGles),
184             renderer_use_glx: Some(raw_config.rendererUseGlx),
185             renderer_use_surfaceless: Some(raw_config.rendererUseSurfaceless),
186             renderer_use_vulkan: Some(raw_config.rendererUseVulkan),
187         })
188     }
189 }
190 
try_into_non_zero_u32(value: i32) -> Result<NonZeroU32>191 fn try_into_non_zero_u32(value: i32) -> Result<NonZeroU32> {
192     let u32_value = value.try_into()?;
193     NonZeroU32::new(u32_value).ok_or(anyhow!("value should be greater than 0"))
194 }
195 
196 /// A disk image to pass to crosvm for a VM.
197 #[derive(Debug)]
198 pub struct DiskFile {
199     pub image: File,
200     pub writable: bool,
201 }
202 
203 /// virtio-input device configuration from `external/crosvm/src/crosvm/config.rs`
204 #[derive(Debug)]
205 #[allow(dead_code)]
206 pub enum InputDeviceOption {
207     EvDev(File),
208     SingleTouch { file: File, width: u32, height: u32, name: Option<String> },
209     Keyboard(File),
210     Mouse(File),
211 }
212 
213 type VfioDevice = Strong<dyn IBoundDevice>;
214 
215 /// The lifecycle state which the payload in the VM has reported itself to be in.
216 ///
217 /// Note that the order of enum variants is significant; only forward transitions are allowed by
218 /// [`VmInstance::update_payload_state`].
219 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
220 pub enum PayloadState {
221     Starting,
222     Started,
223     Ready,
224     Finished,
225     Hangup, // Hasn't reached to Ready before timeout expires
226 }
227 
228 /// The current state of the VM itself.
229 #[derive(Debug)]
230 pub enum VmState {
231     /// The VM has not yet tried to start.
232     NotStarted {
233         ///The configuration needed to start the VM, if it has not yet been started.
234         config: Box<CrosvmConfig>,
235     },
236     /// The VM has been started.
237     Running {
238         /// The crosvm child process.
239         child: Arc<SharedChild>,
240         /// The thread waiting for crosvm to finish.
241         monitor_vm_exit_thread: Option<JoinHandle<()>>,
242     },
243     /// The VM died or was killed.
244     Dead,
245     /// The VM failed to start.
246     Failed,
247 }
248 
249 /// RSS values of VM and CrosVM process itself.
250 #[derive(Copy, Clone, Debug, Default)]
251 pub struct Rss {
252     pub vm: i64,
253     pub crosvm: i64,
254 }
255 
256 /// Metrics regarding the VM.
257 #[derive(Debug, Default)]
258 pub struct VmMetric {
259     /// Recorded timestamp when the VM is started.
260     pub start_timestamp: Option<SystemTime>,
261     /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is
262     /// running.
263     pub cpu_guest_time: Option<i64>,
264     /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
265     pub rss: Option<Rss>,
266 }
267 
268 impl VmState {
269     /// Tries to start the VM, if it is in the `NotStarted` state.
270     ///
271     /// Returns an error if the VM is in the wrong state, or fails to start.
start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error>272     fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
273         let state = mem::replace(self, VmState::Failed);
274         if let VmState::NotStarted { config } = state {
275             let config = *config;
276             let detect_hangup = config.detect_hangup;
277             let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
278             let vfio_devices = config.vfio_devices.clone();
279             let tap =
280                 if let Some(tap_file) = &config.tap { Some(tap_file.try_clone()?) } else { None };
281 
282             // If this fails and returns an error, `self` will be left in the `Failed` state.
283             let child =
284                 Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?);
285 
286             let instance_monitor_status = instance.clone();
287             let child_monitor_status = child.clone();
288             thread::spawn(move || {
289                 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
290             });
291 
292             let child_clone = child.clone();
293             let instance_clone = instance.clone();
294             let monitor_vm_exit_thread = Some(thread::spawn(move || {
295                 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read, vfio_devices, tap);
296             }));
297 
298             if detect_hangup {
299                 let child_clone = child.clone();
300                 thread::spawn(move || {
301                     instance.monitor_payload_hangup(child_clone);
302                 });
303             }
304 
305             // If it started correctly, update the state.
306             *self = VmState::Running { child, monitor_vm_exit_thread };
307             Ok(())
308         } else {
309             *self = state;
310             bail!("VM already started or failed")
311         }
312     }
313 }
314 
315 /// Internal struct that holds the handles to globally unique resources of a VM.
316 #[derive(Debug)]
317 pub struct VmContext {
318     #[allow(dead_code)] // Keeps the global context alive
319     global_context: Strong<dyn IGlobalVmContext>,
320     #[allow(dead_code)] // Keeps the server alive
321     vm_server: RpcServer,
322 }
323 
324 impl VmContext {
325     /// Construct new VmContext.
new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext326     pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
327         VmContext { global_context, vm_server }
328     }
329 }
330 
331 /// Information about a particular instance of a VM which may be running.
332 #[derive(Debug)]
333 pub struct VmInstance {
334     /// The current state of the VM.
335     pub vm_state: Mutex<VmState>,
336     /// Global resources allocated for this VM.
337     #[allow(dead_code)] // Keeps the context alive
338     vm_context: VmContext,
339     /// The CID assigned to the VM for vsock communication.
340     pub cid: Cid,
341     /// Path to crosvm control socket
342     crosvm_control_socket_path: PathBuf,
343     /// The name of the VM.
344     pub name: String,
345     /// Whether the VM is a protected VM.
346     pub protected: bool,
347     /// Directory of temporary files used by the VM while it is running.
348     pub temporary_directory: PathBuf,
349     /// The UID of the process which requested the VM.
350     pub requester_uid: u32,
351     /// The PID of the process which requested the VM. Note that this process may no longer exist
352     /// and the PID may have been reused for a different process, so this should not be trusted.
353     pub requester_debug_pid: i32,
354     /// Callbacks to clients of the VM.
355     pub callbacks: VirtualMachineCallbacks,
356     /// VirtualMachineService binder object for the VM.
357     pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
358     /// Recorded metrics of VM such as timestamp or cpu / memory usage.
359     pub vm_metric: Mutex<VmMetric>,
360     /// The latest lifecycle state which the payload reported itself to be in.
361     payload_state: Mutex<PayloadState>,
362     /// Represents the condition that payload_state was updated
363     payload_state_updated: Condvar,
364     /// The human readable name of requester_uid
365     requester_uid_name: String,
366 }
367 
368 impl fmt::Display for VmInstance {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result369     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370         let adj = if self.protected { "Protected" } else { "Non-protected" };
371         write!(
372             f,
373             "{} virtual machine \"{}\" (owner: {}, cid: {})",
374             adj, self.name, self.requester_uid_name, self.cid
375         )
376     }
377 }
378 
379 impl VmInstance {
380     /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
new( config: CrosvmConfig, temporary_directory: PathBuf, requester_uid: u32, requester_debug_pid: i32, vm_context: VmContext, ) -> Result<VmInstance, Error>381     pub fn new(
382         config: CrosvmConfig,
383         temporary_directory: PathBuf,
384         requester_uid: u32,
385         requester_debug_pid: i32,
386         vm_context: VmContext,
387     ) -> Result<VmInstance, Error> {
388         validate_config(&config)?;
389         let cid = config.cid;
390         let name = config.name.clone();
391         let protected = config.protected;
392         let requester_uid_name = User::from_uid(Uid::from_raw(requester_uid))
393             .ok()
394             .flatten()
395             .map_or_else(|| format!("{}", requester_uid), |u| u.name);
396         let instance = VmInstance {
397             vm_state: Mutex::new(VmState::NotStarted { config: Box::new(config) }),
398             vm_context,
399             cid,
400             crosvm_control_socket_path: temporary_directory.join("crosvm.sock"),
401             name,
402             protected,
403             temporary_directory,
404             requester_uid,
405             requester_debug_pid,
406             callbacks: Default::default(),
407             vm_service: Mutex::new(None),
408             vm_metric: Mutex::new(Default::default()),
409             payload_state: Mutex::new(PayloadState::Starting),
410             payload_state_updated: Condvar::new(),
411             requester_uid_name,
412         };
413         info!("{} created", &instance);
414         Ok(instance)
415     }
416 
417     /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
418     /// the `VmInstance` is dropped.
start(self: &Arc<Self>) -> Result<(), Error>419     pub fn start(self: &Arc<Self>) -> Result<(), Error> {
420         let mut vm_metric = self.vm_metric.lock().unwrap();
421         vm_metric.start_timestamp = Some(SystemTime::now());
422         let ret = self.vm_state.lock().unwrap().start(self.clone());
423         if ret.is_ok() {
424             info!("{} started", &self);
425         }
426         ret.with_context(|| format!("{} failed to start", &self))
427     }
428 
429     /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
430     /// handles the event by updating the state, noityfing the event to clients by calling
431     /// callbacks, and removing temporary files for the VM.
monitor_vm_exit( &self, child: Arc<SharedChild>, mut failure_pipe_read: File, vfio_devices: Vec<VfioDevice>, tap: Option<File>, )432     fn monitor_vm_exit(
433         &self,
434         child: Arc<SharedChild>,
435         mut failure_pipe_read: File,
436         vfio_devices: Vec<VfioDevice>,
437         tap: Option<File>,
438     ) {
439         let result = child.wait();
440         match &result {
441             Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
442             Ok(status) => {
443                 info!("crosvm({}) exited with status {}", child.id(), status);
444                 if let Some(exit_status_code) = status.code() {
445                     if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
446                         info!("detected vcpu stall on crosvm");
447                     }
448                 }
449             }
450         }
451 
452         let mut vm_state = self.vm_state.lock().unwrap();
453         *vm_state = VmState::Dead;
454         // Ensure that the mutex is released before calling the callbacks.
455         drop(vm_state);
456         info!("{} exited", &self);
457 
458         // Read the pipe to see if any failure reason is written
459         let mut failure_reason = String::new();
460         match failure_pipe_read.read_to_string(&mut failure_reason) {
461             Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
462             Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
463             _ => (),
464         };
465 
466         // In case of hangup, the pipe doesn't give us any information because the hangup can't be
467         // detected on the VM side (otherwise, it isn't a hangup), but in the
468         // monitor_payload_hangup function below which updates the payload state to Hangup.
469         let failure_reason =
470             if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
471                 Cow::from("HANGUP")
472             } else {
473                 Cow::from(failure_reason)
474             };
475 
476         self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
477 
478         let death_reason = death_reason(&result, &failure_reason);
479         let exit_signal = exit_signal(&result);
480 
481         self.callbacks.callback_on_died(self.cid, death_reason);
482 
483         let vm_metric = self.vm_metric.lock().unwrap();
484         write_vm_exited_stats_sync(
485             self.requester_uid as i32,
486             &self.name,
487             death_reason,
488             exit_signal,
489             &vm_metric,
490         );
491 
492         // Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
493         remove_temporary_files(&self.temporary_directory).unwrap_or_else(|e| {
494             error!("Error removing temporary files from {:?}: {}", self.temporary_directory, e);
495         });
496 
497         if let Some(tap_file) = tap {
498             GLOBAL_SERVICE
499                 .deleteTapInterface(&ParcelFileDescriptor::new(OwnedFd::from(tap_file)))
500                 .unwrap_or_else(|e| {
501                     error!("Error deleting TAP interface: {e:?}");
502                 });
503         }
504 
505         drop(vfio_devices); // Cleanup devices.
506     }
507 
508     /// Waits until payload is started, or timeout expires. When timeout occurs, kill
509     /// the VM to prevent indefinite hangup and update the payload_state accordingly.
monitor_payload_hangup(&self, child: Arc<SharedChild>)510     fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
511         debug!("Starting to monitor hangup for Microdroid({})", child.id());
512         let (state, result) = self
513             .payload_state_updated
514             .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
515                 *s < PayloadState::Started
516             })
517             .unwrap();
518         drop(state); // we are not interested in state
519         let child_still_running = child.try_wait().ok() == Some(None);
520         if result.timed_out() && child_still_running {
521             error!(
522                 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
523                 child.id(),
524                 BOOT_HANGUP_TIMEOUT.as_secs()
525             );
526             self.update_payload_state(PayloadState::Hangup).unwrap();
527             if let Err(e) = self.kill() {
528                 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
529             }
530         }
531     }
532 
monitor_vm_status(&self, child: Arc<SharedChild>)533     fn monitor_vm_status(&self, child: Arc<SharedChild>) {
534         let pid = child.id();
535 
536         loop {
537             {
538                 // Check VM state
539                 let vm_state = &*self.vm_state.lock().unwrap();
540                 if let VmState::Dead = vm_state {
541                     break;
542                 }
543 
544                 let mut vm_metric = self.vm_metric.lock().unwrap();
545 
546                 // Get CPU Information
547                 match get_guest_time(pid) {
548                     Ok(guest_time) => vm_metric.cpu_guest_time = Some(guest_time),
549                     Err(e) => error!("Failed to get guest CPU time: {e:?}"),
550                 }
551 
552                 // Get Memory Information
553                 match get_rss(pid) {
554                     Ok(rss) => {
555                         vm_metric.rss = match &vm_metric.rss {
556                             Some(x) => Some(Rss::extract_max(x, &rss)),
557                             None => Some(rss),
558                         }
559                     }
560                     Err(e) => error!("Failed to get guest RSS: {}", e),
561                 }
562             }
563 
564             thread::sleep(Duration::from_secs(1));
565         }
566     }
567 
568     /// Returns the last reported state of the VM payload.
payload_state(&self) -> PayloadState569     pub fn payload_state(&self) -> PayloadState {
570         *self.payload_state.lock().unwrap()
571     }
572 
573     /// Updates the payload state to the given value, if it is a valid state transition.
update_payload_state(&self, new_state: PayloadState) -> Result<(), Error>574     pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
575         let mut state_locked = self.payload_state.lock().unwrap();
576         // Only allow forward transitions, e.g. from starting to started or finished, not back in
577         // the other direction.
578         if new_state > *state_locked {
579             *state_locked = new_state;
580             self.payload_state_updated.notify_all();
581             Ok(())
582         } else {
583             bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
584         }
585     }
586 
587     /// Kills the crosvm instance, if it is running.
kill(&self) -> Result<(), Error>588     pub fn kill(&self) -> Result<(), Error> {
589         let monitor_vm_exit_thread = {
590             let vm_state = &mut *self.vm_state.lock().unwrap();
591             if let VmState::Running { child, monitor_vm_exit_thread } = vm_state {
592                 let id = child.id();
593                 debug!("Killing crosvm({})", id);
594                 // TODO: Talk to crosvm to shutdown cleanly.
595                 child.kill().with_context(|| format!("Error killing crosvm({id}) instance"))?;
596                 monitor_vm_exit_thread.take()
597             } else {
598                 bail!("VM is not running")
599             }
600         };
601 
602         // Wait for monitor_vm_exit() to finish. Must release vm_state lock
603         // first, as monitor_vm_exit() takes it as well.
604         monitor_vm_exit_thread.map(JoinHandle::join);
605 
606         // Now that the VM has been killed, shut down the VirtualMachineService
607         // server to eagerly free up the server threads.
608         self.vm_context.vm_server.shutdown()?;
609 
610         Ok(())
611     }
612 
613     /// Responds to memory-trimming notifications by inflating the virtio
614     /// balloon to reclaim guest memory.
trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error>615     pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> {
616         let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {});
617         match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) {
618             Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => {
619                 if let Some(total_memory) = stats.total_memory {
620                     // Reclaim up to 50% of total memory assuming worst case
621                     // most memory is anonymous and must be swapped to zram
622                     // with an approximate 2:1 compression ratio.
623                     let pct = match level {
624                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50,
625                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30,
626                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10,
627                         _ => bail!("Invalid memory trim level {:?}", level),
628                     };
629                     let command = BalloonControlCommand::Adjust {
630                         num_bytes: total_memory * pct / 100,
631                         wait_for_success: false,
632                     };
633                     if let Err(e) = vm_control::client::handle_request(
634                         &VmRequest::BalloonCommand(command),
635                         &self.crosvm_control_socket_path,
636                     ) {
637                         bail!("Error sending balloon adjustment: {:?}", e);
638                     }
639                 }
640             }
641             Ok(VmResponse::Err(e)) => {
642                 // ENOTSUP is returned when the balloon protocol is not initialized. This
643                 // can occur for numerous reasons: Guest is still booting, guest doesn't
644                 // support ballooning, host doesn't support ballooning. We don't log or
645                 // raise an error in this case: trim is just a hint and we can ignore it.
646                 if e.errno() != libc::ENOTSUP {
647                     bail!("Errno return when requesting balloon stats: {}", e.errno())
648                 }
649             }
650             e => bail!("Error requesting balloon stats: {:?}", e),
651         }
652         Ok(())
653     }
654 
655     /// Checks if ramdump has been created. If so, send it to tombstoned.
handle_ramdump(&self) -> Result<(), Error>656     fn handle_ramdump(&self) -> Result<(), Error> {
657         let ramdump_path = self.temporary_directory.join("ramdump");
658         if !ramdump_path.as_path().try_exists()? {
659             return Ok(());
660         }
661         if std::fs::metadata(&ramdump_path)?.len() > 0 {
662             Self::send_ramdump_to_tombstoned(&ramdump_path)?;
663         }
664         Ok(())
665     }
666 
send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error>667     fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
668         let mut input = File::open(ramdump_path)
669             .context(format!("Failed to open ramdump {:?} for reading", ramdump_path))?;
670 
671         let pid = std::process::id() as i32;
672         let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
673             .context("Failed to connect to tombstoned")?;
674         let mut output = conn
675             .text_output
676             .as_ref()
677             .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
678 
679         std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
680         info!("Ramdump {:?} sent to tombstoned", ramdump_path);
681 
682         conn.notify_completion()?;
683         Ok(())
684     }
685 }
686 
687 impl Rss {
extract_max(x: &Rss, y: &Rss) -> Rss688     fn extract_max(x: &Rss, y: &Rss) -> Rss {
689         Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
690     }
691 }
692 
693 // Get Cpus_allowed mask
check_if_all_cpus_allowed() -> Result<bool>694 fn check_if_all_cpus_allowed() -> Result<bool> {
695     let file = read_to_string("/proc/self/status")?;
696     let lines: Vec<_> = file.split('\n').collect();
697 
698     for line in lines {
699         if line.contains("Cpus_allowed_list") {
700             let prop: Vec<_> = line.split_whitespace().collect();
701             if prop.len() != 2 {
702                 return Ok(false);
703             }
704             let cpu_list: Vec<_> = prop[1].split('-').collect();
705             //Only contiguous Cpu list allowed
706             if cpu_list.len() != 2 {
707                 return Ok(false);
708             }
709             if let Some(cpus) = get_num_cpus() {
710                 let max_cpu = cpu_list[1].parse::<usize>()?;
711                 if max_cpu == cpus - 1 {
712                     return Ok(true);
713                 } else {
714                     return Ok(false);
715                 }
716             }
717         }
718     }
719     Ok(false)
720 }
721 
722 // Get guest time from /proc/[crosvm pid]/stat
get_guest_time(pid: u32) -> Result<i64>723 fn get_guest_time(pid: u32) -> Result<i64> {
724     let file = read_to_string(format!("/proc/{}/stat", pid))?;
725     let data_list: Vec<_> = file.split_whitespace().collect();
726 
727     // Information about guest_time is at 43th place of the file split with the whitespace.
728     // Example of /proc/[pid]/stat :
729     // 6603 (kworker/104:1H-kblockd) I 2 0 0 0 -1 69238880 0 0 0 0 0 88 0 0 0 -20 1 0 1845 0 0
730     // 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 0 0 0 17 104 0 0 0 0 0 0 0 0 0 0 0 0 0
731     if data_list.len() < 43 {
732         bail!("Failed to parse command result for getting guest time : {}", file);
733     }
734 
735     let guest_time_ticks = data_list[42].parse::<i64>()?;
736     // SAFETY: It just returns an integer about CPU tick information.
737     let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) };
738     Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
739 }
740 
741 // Get rss from /proc/[crosvm pid]/smaps
get_rss(pid: u32) -> Result<Rss>742 fn get_rss(pid: u32) -> Result<Rss> {
743     let file = read_to_string(format!("/proc/{}/smaps", pid))?;
744     let lines: Vec<_> = file.split('\n').collect();
745 
746     let mut rss_vm_total = 0i64;
747     let mut rss_crosvm_total = 0i64;
748     let mut is_vm = false;
749     for line in lines {
750         if line.contains("crosvm_guest") {
751             is_vm = true;
752         } else if line.contains("Rss:") {
753             let data_list: Vec<_> = line.split_whitespace().collect();
754             if data_list.len() < 2 {
755                 bail!("Failed to parse command result for getting rss :\n{}", line);
756             }
757             let rss = data_list[1].parse::<i64>()?;
758 
759             if is_vm {
760                 rss_vm_total += rss;
761                 is_vm = false;
762             }
763             rss_crosvm_total += rss;
764         }
765     }
766 
767     Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
768 }
769 
death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason770 fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
771     if let Some((reason, info)) = failure_reason.split_once('|') {
772         // Separator indicates extra context information is present after the failure name.
773         error!("Failure info: {info}");
774         failure_reason = reason;
775     }
776     if let Ok(status) = result {
777         match failure_reason {
778             "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
779                 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
780             }
781             "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
782                 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
783             }
784             "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
785                 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
786             }
787             "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
788             "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
789                 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
790             }
791             "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
792                 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
793             }
794             "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
795                 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
796             }
797             "HANGUP" => return DeathReason::HANGUP,
798             _ => {}
799         }
800         match status.code() {
801             None => DeathReason::KILLED,
802             Some(0) => DeathReason::SHUTDOWN,
803             Some(CROSVM_START_ERROR_STATUS) => DeathReason::START_FAILED,
804             Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
805             Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
806             Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
807             Some(_) => DeathReason::UNKNOWN,
808         }
809     } else {
810         DeathReason::INFRASTRUCTURE_ERROR
811     }
812 }
813 
exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32>814 fn exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32> {
815     match result {
816         Ok(status) => status.signal(),
817         Err(_) => None,
818     }
819 }
820 
821 const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
822 const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
823 
vfio_argument_for_platform_device(device: &VfioDevice) -> Result<String, Error>824 fn vfio_argument_for_platform_device(device: &VfioDevice) -> Result<String, Error> {
825     // Check platform device exists
826     let path = Path::new(&device.getSysfsPath()?).canonicalize()?;
827     if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
828         bail!("{path:?} is not a platform device");
829     }
830 
831     // Check platform device is bound to VFIO driver
832     let dev_driver_path = path.join("driver").canonicalize()?;
833     if dev_driver_path != Path::new(VFIO_PLATFORM_DRIVER_PATH) {
834         bail!("{path:?} is not bound to VFIO-platform driver");
835     }
836 
837     if let Some(p) = path.to_str() {
838         Ok(format!("--vfio={p},iommu=pkvm-iommu,dt-symbol={0}", device.getDtboLabel()?))
839     } else {
840         bail!("invalid path {path:?}");
841     }
842 }
843 
append_platform_devices( command: &mut Command, preserved_fds: &mut Vec<RawFd>, config: &CrosvmConfig, ) -> Result<(), Error>844 fn append_platform_devices(
845     command: &mut Command,
846     preserved_fds: &mut Vec<RawFd>,
847     config: &CrosvmConfig,
848 ) -> Result<(), Error> {
849     if config.vfio_devices.is_empty() {
850         return Ok(());
851     }
852 
853     let Some(dtbo) = &config.dtbo else {
854         bail!("VFIO devices assigned but no DTBO available");
855     };
856     command.arg(format!("--device-tree-overlay={},filter", add_preserved_fd(preserved_fds, dtbo)));
857 
858     for device in &config.vfio_devices {
859         command.arg(vfio_argument_for_platform_device(device)?);
860     }
861     Ok(())
862 }
863 
864 /// Starts an instance of `crosvm` to manage a new VM.
run_vm( config: CrosvmConfig, crosvm_control_socket_path: &Path, failure_pipe_write: File, ) -> Result<SharedChild, Error>865 fn run_vm(
866     config: CrosvmConfig,
867     crosvm_control_socket_path: &Path,
868     failure_pipe_write: File,
869 ) -> Result<SharedChild, Error> {
870     validate_config(&config)?;
871 
872     let mut command = Command::new(CROSVM_PATH);
873     // TODO(qwandor): Remove --disable-sandbox.
874     command
875         .arg("--extended-status")
876         // Configure the logger for the crosvm process to silence logs from the disk crate which
877         // don't provide much information to us (but do spamming us).
878         .arg("--log-level")
879         .arg("info,disk=warn")
880         .arg("run")
881         .arg("--disable-sandbox")
882         .arg("--cid")
883         .arg(config.cid.to_string());
884 
885     if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
886         command.arg("--balloon-page-reporting");
887     } else {
888         command.arg("--no-balloon");
889     }
890 
891     let mut memory_mib = config.memory_mib;
892 
893     if config.protected {
894         match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? {
895             Some(pvmfw_path) if !pvmfw_path.is_empty() => {
896                 command.arg("--protected-vm-with-firmware").arg(pvmfw_path)
897             }
898             _ => command.arg("--protected-vm"),
899         };
900 
901         // 3 virtio-console devices + vsock = 4.
902         let virtio_pci_device_count = 4 + config.disks.len();
903         // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
904         // enough.
905         let swiotlb_size_mib = 2 * virtio_pci_device_count as u32;
906         command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
907 
908         // b/346770542 for consistent "usable" memory across protected and non-protected VMs under
909         // pKVM.
910         if hypervisor_props::is_pkvm()? {
911             memory_mib = memory_mib.map(|m| m.saturating_add(swiotlb_size_mib));
912         }
913 
914         // Workaround to keep crash_dump from trying to read protected guest memory.
915         // Context in b/238324526.
916         command.arg("--unmap-guest-memory-on-fork");
917 
918         if config.ramdump.is_some() {
919             // Protected VM needs to reserve memory for ramdump here. Note that we reserve more
920             // memory for the restricted dma pool.
921             let ramdump_reserve = RAMDUMP_RESERVED_MIB + swiotlb_size_mib;
922             command.arg("--params").arg(format!("crashkernel={ramdump_reserve}M"));
923         }
924     } else if config.ramdump.is_some() {
925         command.arg("--params").arg(format!("crashkernel={RAMDUMP_RESERVED_MIB}M"));
926     }
927     if config.debug_config.debug_level == DebugLevel::NONE
928         && config.debug_config.should_prepare_console_output()
929     {
930         // bootconfig.normal will be used, but we need log.
931         command.arg("--params").arg("printk.devkmsg=on");
932         command.arg("--params").arg("console=hvc0");
933     }
934 
935     if let Some(memory_mib) = memory_mib {
936         command.arg("--mem").arg(memory_mib.to_string());
937     }
938 
939     if let Some(cpus) = config.cpus {
940         command.arg("--cpus").arg(cpus.to_string());
941     }
942 
943     if config.host_cpu_topology {
944         if cfg!(virt_cpufreq) && check_if_all_cpus_allowed()? {
945             command.arg("--host-cpu-topology");
946             cfg_if::cfg_if! {
947                 if #[cfg(any(target_arch = "aarch64"))] {
948                     command.arg("--virt-cpufreq");
949                 }
950             }
951         } else if let Some(cpus) = get_num_cpus() {
952             command.arg("--cpus").arg(cpus.to_string());
953         } else {
954             bail!("Could not determine the number of CPUs in the system");
955         }
956     }
957 
958     if let Some(gdb_port) = config.gdb_port {
959         command.arg("--gdb").arg(gdb_port.to_string());
960     }
961 
962     // Keep track of what file descriptors should be mapped to the crosvm process.
963     let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
964 
965     // Setup the serial devices.
966     // 1. uart device: used as the output device by bootloaders and as early console by linux
967     // 2. uart device: used to report the reason for the VM failing.
968     // 3. virtio-console device: used as the console device where kmsg is redirected to
969     // 4. virtio-console device: used as the ramdump output
970     // 5. virtio-console device: used as the logcat output
971     //
972     // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
973     // written there is discarded.
974     let console_out_arg = format_serial_out_arg(&mut preserved_fds, &config.console_out_fd);
975     let console_in_arg = config
976         .console_in_fd
977         .as_ref()
978         .map(|fd| format!(",input={}", add_preserved_fd(&mut preserved_fds, fd)))
979         .unwrap_or_default();
980     let log_arg = format_serial_out_arg(&mut preserved_fds, &config.log_fd);
981     let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
982     let ramdump_arg = format_serial_out_arg(&mut preserved_fds, &config.ramdump);
983     let console_input_device = config.console_input_device.as_deref().unwrap_or(CONSOLE_HVC0);
984     match console_input_device {
985         CONSOLE_HVC0 | CONSOLE_TTYS0 => {}
986         _ => bail!("Unsupported serial device {console_input_device}"),
987     };
988 
989     // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
990     // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
991     // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
992     // doesn't have the issue.
993     // /dev/ttyS0
994     command.arg(format!(
995         "--serial={}{},hardware=serial,num=1",
996         &console_out_arg,
997         if console_input_device == CONSOLE_TTYS0 { &console_in_arg } else { "" }
998     ));
999     // /dev/ttyS1
1000     command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
1001     // /dev/hvc0
1002     command.arg(format!(
1003         "--serial={}{},hardware=virtio-console,num=1",
1004         &console_out_arg,
1005         if console_input_device == CONSOLE_HVC0 { &console_in_arg } else { "" }
1006     ));
1007     // /dev/hvc1
1008     command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
1009     // /dev/hvc2
1010     command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
1011 
1012     if let Some(bootloader) = &config.bootloader {
1013         command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
1014     }
1015 
1016     if let Some(initrd) = &config.initrd {
1017         command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
1018     }
1019 
1020     if let Some(params) = &config.params {
1021         command.arg("--params").arg(params);
1022     }
1023 
1024     for disk in &config.disks {
1025         command
1026             .arg(if disk.writable { "--rwdisk" } else { "--disk" })
1027             .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
1028     }
1029 
1030     if let Some(kernel) = &config.kernel {
1031         command.arg(add_preserved_fd(&mut preserved_fds, kernel));
1032     }
1033 
1034     let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path)
1035         .context("failed to create control server")?;
1036     command
1037         .arg("--socket")
1038         .arg(add_preserved_fd(&mut preserved_fds, &control_server_socket.as_raw_descriptor()));
1039 
1040     if let Some(dt_overlay) = &config.device_tree_overlay {
1041         command.arg("--device-tree-overlay").arg(add_preserved_fd(&mut preserved_fds, dt_overlay));
1042     }
1043 
1044     if cfg!(paravirtualized_devices) {
1045         if let Some(gpu_config) = &config.gpu_config {
1046             let mut gpu_args = Vec::new();
1047             if let Some(backend) = &gpu_config.backend {
1048                 gpu_args.push(format!("backend={}", backend));
1049             }
1050             if let Some(context_types) = &gpu_config.context_types {
1051                 gpu_args.push(format!("context-types={}", context_types.join(":")));
1052             }
1053             if let Some(pci_address) = &gpu_config.pci_address {
1054                 gpu_args.push(format!("pci-address={}", pci_address));
1055             }
1056             if let Some(renderer_features) = &gpu_config.renderer_features {
1057                 gpu_args.push(format!("renderer-features={}", renderer_features));
1058             }
1059             if gpu_config.renderer_use_egl.unwrap_or(false) {
1060                 gpu_args.push("egl=true".to_string());
1061             }
1062             if gpu_config.renderer_use_gles.unwrap_or(false) {
1063                 gpu_args.push("gles=true".to_string());
1064             }
1065             if gpu_config.renderer_use_glx.unwrap_or(false) {
1066                 gpu_args.push("glx=true".to_string());
1067             }
1068             if gpu_config.renderer_use_surfaceless.unwrap_or(false) {
1069                 gpu_args.push("surfaceless=true".to_string());
1070             }
1071             if gpu_config.renderer_use_vulkan.unwrap_or(false) {
1072                 gpu_args.push("vulkan=true".to_string());
1073             }
1074             command.arg(format!("--gpu={}", gpu_args.join(",")));
1075         }
1076         if let Some(display_config) = &config.display_config {
1077             command
1078                 .arg(format!(
1079                     "--gpu-display=mode=windowed[{},{}],dpi=[{},{}],refresh-rate={}",
1080                     display_config.width,
1081                     display_config.height,
1082                     display_config.horizontal_dpi,
1083                     display_config.vertical_dpi,
1084                     display_config.refresh_rate
1085                 ))
1086                 .arg(format!("--android-display-service={}", config.name));
1087         }
1088     }
1089 
1090     if cfg!(paravirtualized_devices) {
1091         // TODO(b/340376951): Remove this after tap in CrosvmConfig is connected to tethering.
1092         if rustutils::system_properties::read_bool("ro.crosvm.network.setup.done", false)
1093             .unwrap_or(false)
1094         {
1095             command.arg("--net").arg("tap-name=crosvm_tap");
1096         }
1097     }
1098 
1099     if cfg!(network) {
1100         if let Some(tap) = &config.tap {
1101             let tap_fd = tap.as_raw_fd();
1102             preserved_fds.push(tap_fd);
1103             command.arg("--net").arg(format!("tap-fd={}", tap_fd));
1104         }
1105     }
1106 
1107     if cfg!(paravirtualized_devices) {
1108         for input_device_option in config.input_device_options.iter() {
1109             command.arg("--input");
1110             command.arg(match input_device_option {
1111                 InputDeviceOption::EvDev(file) => {
1112                     format!("evdev[path={}]", add_preserved_fd(&mut preserved_fds, file))
1113                 }
1114                 InputDeviceOption::Keyboard(file) => {
1115                     format!("keyboard[path={}]", add_preserved_fd(&mut preserved_fds, file))
1116                 }
1117                 InputDeviceOption::Mouse(file) => {
1118                     format!("mouse[path={}]", add_preserved_fd(&mut preserved_fds, file))
1119                 }
1120                 InputDeviceOption::SingleTouch { file, width, height, name } => format!(
1121                     "single-touch[path={},width={},height={}{}]",
1122                     add_preserved_fd(&mut preserved_fds, file),
1123                     width,
1124                     height,
1125                     name.as_ref().map_or("".into(), |n| format!(",name={}", n))
1126                 ),
1127             });
1128         }
1129     }
1130 
1131     if config.hugepages {
1132         command.arg("--hugepages");
1133     }
1134 
1135     if config.boost_uclamp {
1136         command.arg("--boost-uclamp");
1137     }
1138 
1139     append_platform_devices(&mut command, &mut preserved_fds, &config)?;
1140 
1141     debug!("Preserving FDs {:?}", preserved_fds);
1142     command.preserved_fds(preserved_fds);
1143 
1144     if cfg!(paravirtualized_devices) {
1145         if let Some(virtio_snd_backend) = &config.virtio_snd_backend {
1146             command.arg("--virtio-snd").arg(format!("backend={}", virtio_snd_backend));
1147         }
1148     }
1149 
1150     print_crosvm_args(&command);
1151 
1152     let result = SharedChild::spawn(&mut command)?;
1153     debug!("Spawned crosvm({}).", result.id());
1154     Ok(result)
1155 }
1156 
1157 /// Ensure that the configuration has a valid combination of fields set, or return an error if not.
validate_config(config: &CrosvmConfig) -> Result<(), Error>1158 fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
1159     if config.bootloader.is_none() && config.kernel.is_none() {
1160         bail!("VM must have either a bootloader or a kernel image.");
1161     }
1162     if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
1163         bail!("Can't have both bootloader and kernel/initrd image.");
1164     }
1165     let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
1166     if !config.platform_version.matches(&version) {
1167         bail!(
1168             "Incompatible platform version. The config is compatible with platform version(s) \
1169               {}, but the actual platform version is {}",
1170             config.platform_version,
1171             version
1172         );
1173     }
1174 
1175     Ok(())
1176 }
1177 
1178 /// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
1179 /// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
1180 /// unmodified.
print_crosvm_args(command: &Command)1181 fn print_crosvm_args(command: &Command) {
1182     let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
1183     info!(
1184         "Running crosvm with args: {:?}",
1185         command
1186             .get_args()
1187             .map(|s| s.to_string_lossy())
1188             .map(|s| {
1189                 re.replace_all(&s, |caps: &Captures| {
1190                     let path = &caps[0];
1191                     if let Ok(realpath) = std::fs::canonicalize(path) {
1192                         format!("{} ({})", path, realpath.to_string_lossy())
1193                     } else {
1194                         path.to_owned()
1195                     }
1196                 })
1197                 .into_owned()
1198             })
1199             .collect::<Vec<_>>()
1200     );
1201 }
1202 
1203 /// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
1204 /// "/proc/self/fd/N" where N is the file descriptor.
add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String1205 fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
1206     let fd = file.as_raw_fd();
1207     preserved_fds.push(fd);
1208     format!("/proc/self/fd/{}", fd)
1209 }
1210 
1211 /// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
1212 /// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
format_serial_out_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String1213 fn format_serial_out_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
1214     if let Some(file) = file {
1215         format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
1216     } else {
1217         "type=sink".to_string()
1218     }
1219 }
1220 
1221 /// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
create_pipe() -> Result<(File, File), Error>1222 fn create_pipe() -> Result<(File, File), Error> {
1223     let (read_fd, write_fd) = pipe2(OFlag::O_CLOEXEC)?;
1224     Ok((read_fd.into(), write_fd.into()))
1225 }
1226