blob: e5352589f8e014f0673cfb335f3880ea37b72b91 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// 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
David Brazdil41d1a872022-10-05 14:44:19 +010017use crate::aidl::{Cid, VirtualMachineCallbacks};
Seungjae Yoob4c07ba2022-08-12 04:44:52 +000018use crate::atom::write_vm_exited_stats;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090019use anyhow::{anyhow, bail, Context, Error, Result};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090021use lazy_static::lazy_static;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090022use libc::{sysconf, _SC_CLK_TCK};
Andrew Walbran3a5a9212021-05-04 17:09:08 +000023use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090024use semver::{Version, VersionReq};
Andrew Walbranb27681f2022-02-23 15:11:52 +000025use nix::{fcntl::OFlag, unistd::pipe2};
Jiyong Park2d736562022-10-24 22:40:12 +090026use regex::{Captures, Regex};
Keir Fraserf25cb922022-11-23 14:26:00 +000027use rustutils::system_properties;
Andrew Walbrandae07162021-03-12 17:05:20 +000028use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090029use std::borrow::Cow;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090030use std::cmp::max;
31use std::fs::{read_to_string, remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000032use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000033use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000034use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000035use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Jiyong Park1612b902022-08-22 14:47:39 +090036use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000037use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090038use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090039use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000040use std::thread;
Keir Frasercdd4b112022-11-24 14:02:25 +000041use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
42 DeathReason::DeathReason,
43 MemoryTrimLevel::MemoryTrimLevel,
44};
David Brazdil528e0472022-10-10 15:06:02 +010045use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010046use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000047use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090048use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
David Brazdil73988ea2022-11-11 15:10:32 +000049use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050
Keir Fraser13a956a2022-07-14 14:20:46 +000051/// external/crosvm
52use base::UnixSeqpacketListener;
Keir Frasercdd4b112022-11-24 14:02:25 +000053use vm_control::{BalloonControlCommand, VmRequest, VmResponse};
Keir Fraser13a956a2022-07-14 14:20:46 +000054
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000055const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
56
Jiyong Parkdcf17412022-02-08 15:07:23 +090057/// Version of the platform that crosvm currently implements. The format follows SemVer. This
58/// should be updated when there is a platform change in the crosvm side. Having this value here is
59/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
60/// APEX.
61const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
62
Andrew Walbrand15c5632022-02-03 13:38:31 +000063/// The exit status which crosvm returns when it has an error starting a VM.
64const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000065/// The exit status which crosvm returns when a VM requests a reboot.
66const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000067/// The exit status which crosvm returns when it crashes due to an error.
68const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000069/// The exit status which crosvm returns when vcpu is stalled.
70const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000071
Seungjae Yoo6d265d92022-11-15 10:51:33 +090072const MILLIS_PER_SEC: i64 = 1000;
73
Jaewan Kim46422812022-11-25 10:59:39 +090074const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path";
75
Jiyong Parke6ed0f92022-06-22 00:13:00 +090076lazy_static! {
77 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
78 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010079 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090080 // Nested virtualization is slow, so we need a longer timeout.
81 Duration::from_secs(100)
82 } else {
83 Duration::from_secs(10)
84 };
85}
86
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087/// Configuration for a VM to run with crosvm.
88#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000089pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000091 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000092 pub bootloader: Option<File>,
93 pub kernel: Option<File>,
94 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000095 pub disks: Vec<DiskFile>,
96 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000097 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000098 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090099 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900100 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900101 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000102 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +0900103 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000104 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900105 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900106 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000107}
108
109/// A disk image to pass to crosvm for a VM.
110#[derive(Debug)]
111pub struct DiskFile {
112 pub image: File,
113 pub writable: bool,
114}
115
Andrew Walbran6b650662021-09-07 13:13:23 +0000116/// The lifecycle state which the payload in the VM has reported itself to be in.
117///
118/// Note that the order of enum variants is significant; only forward transitions are allowed by
119/// [`VmInstance::update_payload_state`].
120#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
121pub enum PayloadState {
122 Starting,
123 Started,
124 Ready,
125 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900126 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000127}
128
Andrew Walbranf8d94112021-09-07 11:45:36 +0000129/// The current state of the VM itself.
130#[derive(Debug)]
131pub enum VmState {
132 /// The VM has not yet tried to start.
133 NotStarted {
134 ///The configuration needed to start the VM, if it has not yet been started.
135 config: CrosvmConfig,
136 },
137 /// The VM has been started.
138 Running {
139 /// The crosvm child process.
140 child: Arc<SharedChild>,
141 },
142 /// The VM died or was killed.
143 Dead,
144 /// The VM failed to start.
145 Failed,
146}
147
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900148/// RSS values of VM and CrosVM process itself.
149#[derive(Copy, Clone, Debug, Default)]
150pub struct Rss {
151 pub vm: i64,
152 pub crosvm: i64,
153}
154
155/// Metrics regarding the VM.
156#[derive(Debug, Default)]
157pub struct VmMetric {
158 /// Recorded timestamp when the VM is started.
159 pub start_timestamp: Option<SystemTime>,
160 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
161 pub cpu_guest_time: Option<i64>,
162 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
163 pub rss: Option<Rss>,
164}
165
Andrew Walbranf8d94112021-09-07 11:45:36 +0000166impl VmState {
167 /// Tries to start the VM, if it is in the `NotStarted` state.
168 ///
169 /// Returns an error if the VM is in the wrong state, or fails to start.
170 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
171 let state = mem::replace(self, VmState::Failed);
172 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900173 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000174 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
175
Andrew Walbranf8d94112021-09-07 11:45:36 +0000176 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000177 let child =
Keir Frasercdd4b112022-11-24 14:02:25 +0000178 Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000179
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900180 let instance_monitor_status = instance.clone();
181 let child_monitor_status = child.clone();
182 thread::spawn(move || {
183 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
184 });
185
Andrew Walbranf8d94112021-09-07 11:45:36 +0000186 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900187 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000188 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900189 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000190 });
191
Jiyong Parka4eebde2022-07-12 18:01:12 +0900192 if detect_hangup {
193 let child_clone = child.clone();
194 thread::spawn(move || {
195 instance.monitor_payload_hangup(child_clone);
196 });
197 }
198
Andrew Walbranf8d94112021-09-07 11:45:36 +0000199 // If it started correctly, update the state.
200 *self = VmState::Running { child };
201 Ok(())
202 } else {
203 *self = state;
204 bail!("VM already started or failed")
205 }
206 }
207}
208
David Brazdil8cf8f482022-11-23 14:21:26 +0000209/// Internal struct that holds the handles to globally unique resources of a VM.
210#[derive(Debug)]
211pub struct VmContext {
212 #[allow(dead_code)] // Keeps the global context alive
213 global_context: Strong<dyn IGlobalVmContext>,
214 #[allow(dead_code)] // Keeps the server alive
215 vm_server: RpcServer,
216}
217
218impl VmContext {
219 /// Construct new VmContext.
220 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
221 VmContext { global_context, vm_server }
222 }
223}
224
Andrew Walbranf8d94112021-09-07 11:45:36 +0000225/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000226#[derive(Debug)]
227pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000228 /// The current state of the VM.
229 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000230 /// Global resources allocated for this VM.
231 #[allow(dead_code)] // Keeps the context alive
232 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000233 /// The CID assigned to the VM for vsock communication.
234 pub cid: Cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000235 /// Path to crosvm control socket
236 crosvm_control_socket_path: PathBuf,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000237 /// The name of the VM.
238 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000239 /// Whether the VM is a protected VM.
240 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000241 /// Directory of temporary files used by the VM while it is running.
242 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000243 /// The UID of the process which requested the VM.
244 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000245 /// The PID of the process which requested the VM. Note that this process may no longer exist
246 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000247 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000248 /// Callbacks to clients of the VM.
249 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000250 /// VirtualMachineService binder object for the VM.
251 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900252 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
253 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000254 /// The latest lifecycle state which the payload reported itself to be in.
255 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900256 /// Represents the condition that payload_state was updated
257 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000258}
259
260impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000261 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
262 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000263 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000264 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000265 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000266 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000267 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000268 ) -> Result<VmInstance, Error> {
269 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000270 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000271 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000272 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000273 Ok(VmInstance {
274 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100275 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000276 cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000277 crosvm_control_socket_path: temporary_directory.join("crosvm.sock"),
Seungjae Yoo62085c02022-08-12 04:44:52 +0000278 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000279 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000280 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000281 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000282 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000283 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000284 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900285 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000286 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900287 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000288 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000289 }
290
Andrew Walbranf8d94112021-09-07 11:45:36 +0000291 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
292 /// the `VmInstance` is dropped.
293 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900294 let mut vm_metric = self.vm_metric.lock().unwrap();
295 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000296 self.vm_state.lock().unwrap().start(self.clone())
297 }
298
Jiyong Parka4eebde2022-07-12 18:01:12 +0900299 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
300 /// handles the event by updating the state, noityfing the event to clients by calling
301 /// callbacks, and removing temporary files for the VM.
302 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000303 let result = child.wait();
304 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900305 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000306 Ok(status) => {
307 info!("crosvm({}) exited with status {}", child.id(), status);
308 if let Some(exit_status_code) = status.code() {
309 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
310 info!("detected vcpu stall on crosvm");
311 }
312 }
313 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000314 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000315
316 let mut vm_state = self.vm_state.lock().unwrap();
317 *vm_state = VmState::Dead;
318 // Ensure that the mutex is released before calling the callbacks.
319 drop(vm_state);
320
Jiyong Parka4eebde2022-07-12 18:01:12 +0900321 // Read the pipe to see if any failure reason is written
322 let mut failure_reason = String::new();
323 match failure_pipe_read.read_to_string(&mut failure_reason) {
324 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
325 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
326 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900327 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000328
Jiyong Parka4eebde2022-07-12 18:01:12 +0900329 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
330 // detected on the VM side (otherwise, it isn't a hangup), but in the
331 // monitor_payload_hangup function below which updates the payload state to Hangup.
332 let failure_reason =
333 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
334 Cow::from("HANGUP")
335 } else {
336 Cow::from(failure_reason)
337 };
338
Jiyong Parke558ab12022-07-07 20:18:55 +0900339 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000340
341 let death_reason = death_reason(&result, &failure_reason);
342 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900343
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900344 let vm_metric = self.vm_metric.lock().unwrap();
345 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000346
347 // Delete temporary files.
348 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000349 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000350 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000351 }
352
Jiyong Parka4eebde2022-07-12 18:01:12 +0900353 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
354 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
355 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
356 debug!("Starting to monitor hangup for Microdroid({})", child.id());
357 let (_, result) = self
358 .payload_state_updated
359 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
360 *s < PayloadState::Started
361 })
362 .unwrap();
363 let child_still_running = child.try_wait().ok() == Some(None);
364 if result.timed_out() && child_still_running {
365 error!(
366 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
367 child.id(),
368 BOOT_HANGUP_TIMEOUT.as_secs()
369 );
370 self.update_payload_state(PayloadState::Hangup).unwrap();
371 if let Err(e) = self.kill() {
372 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
373 }
374 }
375 }
376
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900377 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
378 let pid = child.id();
379
380 loop {
381 {
382 // Check VM state
383 let vm_state = &*self.vm_state.lock().unwrap();
384 if let VmState::Dead = vm_state {
385 break;
386 }
387
388 let mut vm_metric = self.vm_metric.lock().unwrap();
389
390 // Get CPU Information
391 // TODO: Collect it once right before VM dies using SIGCHLD
392 if let Ok(guest_time) = get_guest_time(pid) {
393 vm_metric.cpu_guest_time = Some(guest_time);
394 } else {
395 error!("Failed to parse /proc/[pid]/stat");
396 }
397
398 // Get Memory Information
399 if let Ok(rss) = get_rss(pid) {
400 vm_metric.rss = match &vm_metric.rss {
401 Some(x) => Some(Rss::extract_max(x, &rss)),
402 None => Some(rss),
403 }
404 } else {
405 error!("Failed to parse /proc/[pid]/smaps");
406 }
407 }
408
409 thread::sleep(Duration::from_secs(1));
410 }
411 }
412
Andrew Walbran6b650662021-09-07 13:13:23 +0000413 /// Returns the last reported state of the VM payload.
414 pub fn payload_state(&self) -> PayloadState {
415 *self.payload_state.lock().unwrap()
416 }
417
418 /// Updates the payload state to the given value, if it is a valid state transition.
419 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
420 let mut state_locked = self.payload_state.lock().unwrap();
421 // Only allow forward transitions, e.g. from starting to started or finished, not back in
422 // the other direction.
423 if new_state > *state_locked {
424 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900425 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000426 Ok(())
427 } else {
428 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
429 }
430 }
431
Andrew Walbranf8d94112021-09-07 11:45:36 +0000432 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900433 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000434 let vm_state = &*self.vm_state.lock().unwrap();
435 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900436 let id = child.id();
437 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000438 // TODO: Talk to crosvm to shutdown cleanly.
439 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900440 bail!("Error killing crosvm({}) instance: {}", id, e);
441 } else {
442 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000443 }
Inseob Kima446f802022-07-11 19:46:37 +0900444 } else {
445 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000446 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000447 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900448
Keir Frasercdd4b112022-11-24 14:02:25 +0000449 /// Responds to memory-trimming notifications by inflating the virtio
450 /// balloon to reclaim guest memory.
451 pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> {
452 let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {});
453 match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) {
454 Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => {
455 if let Some(total_memory) = stats.total_memory {
456 // Reclaim up to 50% of total memory assuming worst case
457 // most memory is anonymous and must be swapped to zram
458 // with an approximate 2:1 compression ratio.
459 let pct = match level {
460 MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50,
461 MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30,
462 MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10,
463 _ => bail!("Invalid memory trim level {:?}", level),
464 };
465 let command =
466 BalloonControlCommand::Adjust { num_bytes: total_memory * pct / 100 };
467 if let Err(e) = vm_control::client::handle_request(
468 &VmRequest::BalloonCommand(command),
469 &self.crosvm_control_socket_path,
470 ) {
471 bail!("Error sending balloon adjustment: {:?}", e);
472 }
473 }
474 }
475 Ok(VmResponse::Err(e)) => {
476 // ENOTSUP is returned when the balloon protocol is not initialised. This
477 // can occur for numerous reasons: Guest is still booting, guest doesn't
478 // support ballooning, host doesn't support ballooning. We don't log or
479 // raise an error in this case: trim is just a hint and we can ignore it.
480 if e.errno() != libc::ENOTSUP {
481 bail!("Errno return when requesting balloon stats: {}", e.errno())
482 }
483 }
484 e => bail!("Error requesting balloon stats: {:?}", e),
485 }
486 Ok(())
487 }
488
Jiyong Parke558ab12022-07-07 20:18:55 +0900489 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
490 /// to read the ramdump.
491 fn handle_ramdump(&self) -> Result<(), Error> {
492 let ramdump_path = self.temporary_directory.join("ramdump");
493 if std::fs::metadata(&ramdump_path)?.len() > 0 {
494 let ramdump = File::open(&ramdump_path)
495 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
496 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900497
498 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900499 }
500 Ok(())
501 }
Jiyong Park1612b902022-08-22 14:47:39 +0900502
503 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
504 let mut input = File::open(ramdump_path)
505 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
506
507 let pid = std::process::id() as i32;
508 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
509 .context("Failed to connect to tombstoned")?;
510 let mut output = conn
511 .text_output
512 .as_ref()
513 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
514
515 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
516 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
517
518 conn.notify_completion()?;
519 Ok(())
520 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000521}
522
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900523impl Rss {
524 fn extract_max(x: &Rss, y: &Rss) -> Rss {
525 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
526 }
527}
528
529// Get guest time from /proc/[crosvm pid]/stat
530fn get_guest_time(pid: u32) -> Result<i64> {
531 let file = read_to_string(format!("/proc/{}/stat", pid))?;
532 let data_list: Vec<_> = file.split_whitespace().collect();
533
534 // Information about guest_time is at 43th place of the file split with the whitespace.
535 // Example of /proc/[pid]/stat :
536 // 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
537 // 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
538 if data_list.len() < 43 {
539 bail!("Failed to parse command result for getting guest time : {}", file);
540 }
541
542 let guest_time_ticks = data_list[42].parse::<i64>()?;
543 // SAFETY : It just returns an integer about CPU tick information.
544 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
545 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
546}
547
548// Get rss from /proc/[crosvm pid]/smaps
549fn get_rss(pid: u32) -> Result<Rss> {
550 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
551 let lines: Vec<_> = file.split('\n').collect();
552
553 let mut rss_vm_total = 0i64;
554 let mut rss_crosvm_total = 0i64;
555 let mut is_vm = false;
556 for line in lines {
557 if line.contains("crosvm_guest") {
558 is_vm = true;
559 } else if line.contains("Rss:") {
560 let data_list: Vec<_> = line.split_whitespace().collect();
561 if data_list.len() < 2 {
562 bail!("Failed to parse command result for getting rss :\n{}", line);
563 }
564 let rss = data_list[1].parse::<i64>()?;
565
566 if is_vm {
567 rss_vm_total += rss;
568 is_vm = false;
569 }
570 rss_crosvm_total += rss;
571 }
572 }
573
574 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
575}
576
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100577fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
578 if let Some(position) = failure_reason.find('|') {
579 // Separator indicates extra context information is present after the failure name.
580 error!("Failure info: {}", &failure_reason[(position + 1)..]);
581 failure_reason = &failure_reason[..position];
582 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000583 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000584 match failure_reason {
585 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
586 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
587 }
588 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
589 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
590 }
591 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
592 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
593 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
594 }
Inseob Kim272f5722022-06-13 17:14:51 +0900595 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
596 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
597 }
598 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
599 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
600 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
601 }
602 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
603 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
604 }
605 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
606 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
607 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900608 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000609 _ => {}
610 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000611 match status.code() {
612 None => DeathReason::KILLED,
613 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000614 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000615 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000616 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000617 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000618 Some(_) => DeathReason::UNKNOWN,
619 }
620 } else {
621 DeathReason::INFRASTRUCTURE_ERROR
622 }
623}
624
Andrew Walbrand3a84182021-09-07 14:48:52 +0000625/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000626fn run_vm(
627 config: CrosvmConfig,
Keir Frasercdd4b112022-11-24 14:02:25 +0000628 crosvm_control_socket_path: &Path,
Keir Fraser13a956a2022-07-14 14:20:46 +0000629 failure_pipe_write: File,
630) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000631 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000632
633 let mut command = Command::new(CROSVM_PATH);
634 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000635 command
636 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900637 // Configure the logger for the crosvm process to silence logs from the disk crate which
638 // don't provide much information to us (but do spamming us).
639 .arg("--log-level")
640 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000641 .arg("run")
642 .arg("--disable-sandbox")
643 .arg("--cid")
644 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000645
Keir Fraserf25cb922022-11-23 14:26:00 +0000646 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
647 command.arg("--balloon-page-reporting");
648 } else {
649 command.arg("--no-balloon");
650 }
651
Andrew Walbranf8650422021-06-09 15:54:09 +0000652 if config.protected {
Jaewan Kim46422812022-11-25 10:59:39 +0900653 match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? {
654 Some(pvmfw_path) if !pvmfw_path.is_empty() => {
655 command.arg("--protected-vm-with-firmware").arg(pvmfw_path)
656 }
657 _ => command.arg("--protected-vm"),
658 };
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000659
660 // 3 virtio-console devices + vsock = 4.
661 let virtio_pci_device_count = 4 + config.disks.len();
662 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
663 // enough.
664 let swiotlb_size_mib = 2 * virtio_pci_device_count;
665 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000666 }
667
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000668 if let Some(memory_mib) = config.memory_mib {
669 command.arg("--mem").arg(memory_mib.to_string());
670 }
671
Jiyong Park032615f2022-01-10 13:55:34 +0900672 if let Some(cpus) = config.cpus {
673 command.arg("--cpus").arg(cpus.to_string());
674 }
675
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900676 if !config.task_profiles.is_empty() {
677 command.arg("--task-profiles").arg(config.task_profiles.join(","));
678 }
679
Jiyong Parkfa91d702021-10-18 23:51:39 +0900680 // Keep track of what file descriptors should be mapped to the crosvm process.
681 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
682
Jiyong Park747d6362021-10-19 17:12:52 +0900683 // Setup the serial devices.
684 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000685 // 2. uart device: used to report the reason for the VM failing.
686 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900687 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000688 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900689 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900690 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
691 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000692 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
693 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
694 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900695 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900696
Jiyong Park747d6362021-10-19 17:12:52 +0900697 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
698 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
699 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
700 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900701 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000702 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
703 // /dev/ttyS1
704 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900705 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900706 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900707 // /dev/hvc1
708 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900709 // /dev/hvc2
710 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000711
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000712 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000713 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000714 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000715
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000716 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000717 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000718 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000719
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000720 if let Some(params) = &config.params {
721 command.arg("--params").arg(params);
722 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000723
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000724 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000725 command
726 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000727 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000728 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000729
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000730 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000731 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000732 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000733
Keir Frasercdd4b112022-11-24 14:02:25 +0000734 let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path)
735 .context("failed to create control server")?;
Keir Fraser13a956a2022-07-14 14:20:46 +0000736 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
737
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000738 debug!("Preserving FDs {:?}", preserved_fds);
739 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000740
Jaewan Kimb2814062022-11-14 13:21:40 +0900741 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900742 print_crosvm_args(&command);
743
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000744 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900745 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000746 Ok(result)
747}
748
749/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000750fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000751 if config.bootloader.is_none() && config.kernel.is_none() {
752 bail!("VM must have either a bootloader or a kernel image.");
753 }
754 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
755 bail!("Can't have both bootloader and kernel/initrd image.");
756 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900757 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
758 if !config.platform_version.matches(&version) {
759 bail!(
760 "Incompatible platform version. The config is compatible with platform version(s) \
761 {}, but the actual platform version is {}",
762 config.platform_version,
763 version
764 );
765 }
766
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000767 Ok(())
768}
769
Jiyong Park2d736562022-10-24 22:40:12 +0900770/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
771/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
772/// unmodified.
773fn print_crosvm_args(command: &Command) {
774 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
775 info!(
776 "Running crosvm with args: {:?}",
777 command
778 .get_args()
779 .map(|s| s.to_string_lossy())
780 .map(|s| {
781 re.replace_all(&s, |caps: &Captures| {
782 let path = &caps[0];
783 if let Ok(realpath) = std::fs::canonicalize(path) {
784 format!("{} ({})", path, realpath.to_string_lossy())
785 } else {
786 path.to_owned()
787 }
788 })
789 .into_owned()
790 })
791 .collect::<Vec<_>>()
792 );
793}
794
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000795/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
796/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000797fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000798 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000799 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000800 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000801}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000802
803/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
804/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
805fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
806 if let Some(file) = file {
807 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
808 } else {
809 "type=sink".to_string()
810 }
811}
812
813/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
814fn create_pipe() -> Result<(File, File), Error> {
815 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
816 // SAFETY: We are the sole owners of these fds as they were just created.
817 let read_fd = unsafe { File::from_raw_fd(raw_read) };
818 let write_fd = unsafe { File::from_raw_fd(raw_write) };
819 Ok((read_fd, write_fd))
820}