blob: 6f646b72702d3e7a144bf8ee91cd86c9492f94cb [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;
Jiyong Park1612b902022-08-22 14:47:39 +090019use anyhow::{anyhow, bail, Context, Error};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090021use lazy_static::lazy_static;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000022use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090023use semver::{Version, VersionReq};
Andrew Walbranb27681f2022-02-23 15:11:52 +000024use nix::{fcntl::OFlag, unistd::pipe2};
Jiyong Park2d736562022-10-24 22:40:12 +090025use regex::{Captures, Regex};
Andrew Walbrandae07162021-03-12 17:05:20 +000026use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090027use std::borrow::Cow;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000028use std::fs::{remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000029use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000030use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000031use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000032use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Jiyong Park1612b902022-08-22 14:47:39 +090033use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000034use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090035use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090036use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000037use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090038use vsock::VsockStream;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000039use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
Alan Stokes0e82b502022-08-08 14:44:48 +010040use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090042use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000043
Keir Fraser13a956a2022-07-14 14:20:46 +000044/// external/crosvm
45use base::UnixSeqpacketListener;
46
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000047const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
48
Jiyong Parkdcf17412022-02-08 15:07:23 +090049/// Version of the platform that crosvm currently implements. The format follows SemVer. This
50/// should be updated when there is a platform change in the crosvm side. Having this value here is
51/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
52/// APEX.
53const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
54
Andrew Walbrand15c5632022-02-03 13:38:31 +000055/// The exit status which crosvm returns when it has an error starting a VM.
56const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000057/// The exit status which crosvm returns when a VM requests a reboot.
58const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000059/// The exit status which crosvm returns when it crashes due to an error.
60const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000061/// The exit status which crosvm returns when vcpu is stalled.
62const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000063
Jiyong Parke6ed0f92022-06-22 00:13:00 +090064lazy_static! {
65 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
66 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010067 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090068 // Nested virtualization is slow, so we need a longer timeout.
69 Duration::from_secs(100)
70 } else {
71 Duration::from_secs(10)
72 };
73}
74
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075/// Configuration for a VM to run with crosvm.
76#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000077pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000079 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000080 pub bootloader: Option<File>,
81 pub kernel: Option<File>,
82 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000083 pub disks: Vec<DiskFile>,
84 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000085 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000086 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090087 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090088 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090089 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000090 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090091 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000092 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090093 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090094 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000095}
96
97/// A disk image to pass to crosvm for a VM.
98#[derive(Debug)]
99pub struct DiskFile {
100 pub image: File,
101 pub writable: bool,
102}
103
Andrew Walbran6b650662021-09-07 13:13:23 +0000104/// The lifecycle state which the payload in the VM has reported itself to be in.
105///
106/// Note that the order of enum variants is significant; only forward transitions are allowed by
107/// [`VmInstance::update_payload_state`].
108#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
109pub enum PayloadState {
110 Starting,
111 Started,
112 Ready,
113 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900114 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000115}
116
Andrew Walbranf8d94112021-09-07 11:45:36 +0000117/// The current state of the VM itself.
118#[derive(Debug)]
119pub enum VmState {
120 /// The VM has not yet tried to start.
121 NotStarted {
122 ///The configuration needed to start the VM, if it has not yet been started.
123 config: CrosvmConfig,
124 },
125 /// The VM has been started.
126 Running {
127 /// The crosvm child process.
128 child: Arc<SharedChild>,
129 },
130 /// The VM died or was killed.
131 Dead,
132 /// The VM failed to start.
133 Failed,
134}
135
136impl VmState {
137 /// Tries to start the VM, if it is in the `NotStarted` state.
138 ///
139 /// Returns an error if the VM is in the wrong state, or fails to start.
140 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
141 let state = mem::replace(self, VmState::Failed);
142 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900143 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000144 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
145
Andrew Walbranf8d94112021-09-07 11:45:36 +0000146 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000147 let child =
148 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000149
150 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900151 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000152 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900153 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000154 });
155
Jiyong Parka4eebde2022-07-12 18:01:12 +0900156 if detect_hangup {
157 let child_clone = child.clone();
158 thread::spawn(move || {
159 instance.monitor_payload_hangup(child_clone);
160 });
161 }
162
Andrew Walbranf8d94112021-09-07 11:45:36 +0000163 // If it started correctly, update the state.
164 *self = VmState::Running { child };
165 Ok(())
166 } else {
167 *self = state;
168 bail!("VM already started or failed")
169 }
170 }
171}
172
173/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000174#[derive(Debug)]
175pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000176 /// The current state of the VM.
177 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000178 /// The CID assigned to the VM for vsock communication.
179 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000180 /// The name of the VM.
181 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000182 /// Whether the VM is a protected VM.
183 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000184 /// Directory of temporary files used by the VM while it is running.
185 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000186 /// The UID of the process which requested the VM.
187 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000188 /// The PID of the process which requested the VM. Note that this process may no longer exist
189 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000190 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000191 /// Callbacks to clients of the VM.
192 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900193 /// Input/output stream of the payload run in the VM.
194 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000195 /// VirtualMachineService binder object for the VM.
196 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900197 /// Recorded timestamp when the VM is started.
198 pub vm_start_timestamp: Mutex<Option<SystemTime>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000199 /// The latest lifecycle state which the payload reported itself to be in.
200 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900201 /// Represents the condition that payload_state was updated
202 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000203}
204
205impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000206 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
207 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000208 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000209 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000210 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000211 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000212 ) -> Result<VmInstance, Error> {
213 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000214 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000215 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000216 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000217 Ok(VmInstance {
218 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000219 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000220 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000221 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000222 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000223 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000224 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000225 callbacks: Default::default(),
226 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000227 vm_service: Mutex::new(None),
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900228 vm_start_timestamp: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000229 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900230 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000231 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000232 }
233
Andrew Walbranf8d94112021-09-07 11:45:36 +0000234 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
235 /// the `VmInstance` is dropped.
236 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900237 *self.vm_start_timestamp.lock().unwrap() = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000238 self.vm_state.lock().unwrap().start(self.clone())
239 }
240
Jiyong Parka4eebde2022-07-12 18:01:12 +0900241 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
242 /// handles the event by updating the state, noityfing the event to clients by calling
243 /// callbacks, and removing temporary files for the VM.
244 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000245 let result = child.wait();
246 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900247 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000248 Ok(status) => {
249 info!("crosvm({}) exited with status {}", child.id(), status);
250 if let Some(exit_status_code) = status.code() {
251 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
252 info!("detected vcpu stall on crosvm");
253 }
254 }
255 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000256 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000257
258 let mut vm_state = self.vm_state.lock().unwrap();
259 *vm_state = VmState::Dead;
260 // Ensure that the mutex is released before calling the callbacks.
261 drop(vm_state);
262
Jiyong Parka4eebde2022-07-12 18:01:12 +0900263 // Read the pipe to see if any failure reason is written
264 let mut failure_reason = String::new();
265 match failure_pipe_read.read_to_string(&mut failure_reason) {
266 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
267 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
268 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900269 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000270
Jiyong Parka4eebde2022-07-12 18:01:12 +0900271 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
272 // detected on the VM side (otherwise, it isn't a hangup), but in the
273 // monitor_payload_hangup function below which updates the payload state to Hangup.
274 let failure_reason =
275 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
276 Cow::from("HANGUP")
277 } else {
278 Cow::from(failure_reason)
279 };
280
Jiyong Parke558ab12022-07-07 20:18:55 +0900281 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000282
283 let death_reason = death_reason(&result, &failure_reason);
284 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900285
286 let vm_start_timestamp = self.vm_start_timestamp.lock().unwrap();
287 write_vm_exited_stats(
288 self.requester_uid as i32,
289 &self.name,
290 death_reason,
291 *vm_start_timestamp,
292 );
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000293
294 // Delete temporary files.
295 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000296 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000297 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000298 }
299
Jiyong Parka4eebde2022-07-12 18:01:12 +0900300 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
301 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
302 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
303 debug!("Starting to monitor hangup for Microdroid({})", child.id());
304 let (_, result) = self
305 .payload_state_updated
306 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
307 *s < PayloadState::Started
308 })
309 .unwrap();
310 let child_still_running = child.try_wait().ok() == Some(None);
311 if result.timed_out() && child_still_running {
312 error!(
313 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
314 child.id(),
315 BOOT_HANGUP_TIMEOUT.as_secs()
316 );
317 self.update_payload_state(PayloadState::Hangup).unwrap();
318 if let Err(e) = self.kill() {
319 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
320 }
321 }
322 }
323
Andrew Walbran6b650662021-09-07 13:13:23 +0000324 /// Returns the last reported state of the VM payload.
325 pub fn payload_state(&self) -> PayloadState {
326 *self.payload_state.lock().unwrap()
327 }
328
329 /// Updates the payload state to the given value, if it is a valid state transition.
330 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
331 let mut state_locked = self.payload_state.lock().unwrap();
332 // Only allow forward transitions, e.g. from starting to started or finished, not back in
333 // the other direction.
334 if new_state > *state_locked {
335 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900336 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000337 Ok(())
338 } else {
339 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
340 }
341 }
342
Andrew Walbranf8d94112021-09-07 11:45:36 +0000343 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900344 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000345 let vm_state = &*self.vm_state.lock().unwrap();
346 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900347 let id = child.id();
348 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000349 // TODO: Talk to crosvm to shutdown cleanly.
350 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900351 bail!("Error killing crosvm({}) instance: {}", id, e);
352 } else {
353 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000354 }
Inseob Kima446f802022-07-11 19:46:37 +0900355 } else {
356 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000357 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000358 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900359
360 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
361 /// to read the ramdump.
362 fn handle_ramdump(&self) -> Result<(), Error> {
363 let ramdump_path = self.temporary_directory.join("ramdump");
364 if std::fs::metadata(&ramdump_path)?.len() > 0 {
365 let ramdump = File::open(&ramdump_path)
366 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
367 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900368
369 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900370 }
371 Ok(())
372 }
Jiyong Park1612b902022-08-22 14:47:39 +0900373
374 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
375 let mut input = File::open(ramdump_path)
376 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
377
378 let pid = std::process::id() as i32;
379 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
380 .context("Failed to connect to tombstoned")?;
381 let mut output = conn
382 .text_output
383 .as_ref()
384 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
385
386 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
387 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
388
389 conn.notify_completion()?;
390 Ok(())
391 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000392}
393
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100394fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
395 if let Some(position) = failure_reason.find('|') {
396 // Separator indicates extra context information is present after the failure name.
397 error!("Failure info: {}", &failure_reason[(position + 1)..]);
398 failure_reason = &failure_reason[..position];
399 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000400 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000401 match failure_reason {
402 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
403 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
404 }
405 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
406 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
407 }
408 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
409 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
410 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
411 }
Inseob Kim272f5722022-06-13 17:14:51 +0900412 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
413 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
414 }
415 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
416 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
417 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
418 }
419 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
420 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
421 }
422 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
423 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
424 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900425 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000426 _ => {}
427 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000428 match status.code() {
429 None => DeathReason::KILLED,
430 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000431 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000432 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000433 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000434 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000435 Some(_) => DeathReason::UNKNOWN,
436 }
437 } else {
438 DeathReason::INFRASTRUCTURE_ERROR
439 }
440}
441
Andrew Walbrand3a84182021-09-07 14:48:52 +0000442/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000443fn run_vm(
444 config: CrosvmConfig,
445 temporary_directory: &Path,
446 failure_pipe_write: File,
447) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000448 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000449
450 let mut command = Command::new(CROSVM_PATH);
451 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000452 command
453 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900454 // Configure the logger for the crosvm process to silence logs from the disk crate which
455 // don't provide much information to us (but do spamming us).
456 .arg("--log-level")
457 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000458 .arg("run")
459 .arg("--disable-sandbox")
Keir Fraser72762722022-09-30 16:12:06 +0000460 .arg("--no-balloon")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000461 .arg("--cid")
462 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000463
Andrew Walbranf8650422021-06-09 15:54:09 +0000464 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000465 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000466
467 // 3 virtio-console devices + vsock = 4.
468 let virtio_pci_device_count = 4 + config.disks.len();
469 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
470 // enough.
471 let swiotlb_size_mib = 2 * virtio_pci_device_count;
472 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000473 }
474
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000475 if let Some(memory_mib) = config.memory_mib {
476 command.arg("--mem").arg(memory_mib.to_string());
477 }
478
Jiyong Park032615f2022-01-10 13:55:34 +0900479 if let Some(cpus) = config.cpus {
480 command.arg("--cpus").arg(cpus.to_string());
481 }
482
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900483 if !config.task_profiles.is_empty() {
484 command.arg("--task-profiles").arg(config.task_profiles.join(","));
485 }
486
Jiyong Parkfa91d702021-10-18 23:51:39 +0900487 // Keep track of what file descriptors should be mapped to the crosvm process.
488 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
489
Jiyong Park747d6362021-10-19 17:12:52 +0900490 // Setup the serial devices.
491 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000492 // 2. uart device: used to report the reason for the VM failing.
493 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900494 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000495 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900496 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900497 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
498 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000499 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
500 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
501 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900502 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900503
Jiyong Park747d6362021-10-19 17:12:52 +0900504 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
505 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
506 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
507 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900508 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000509 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
510 // /dev/ttyS1
511 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900512 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900513 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900514 // /dev/hvc1
515 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900516 // /dev/hvc2
517 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000518
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000519 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000520 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000521 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000522
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000523 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000524 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000525 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000526
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000527 if let Some(params) = &config.params {
528 command.arg("--params").arg(params);
529 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000530
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000531 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000532 command
533 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000534 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000535 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000536
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000537 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000538 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000539 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000540
Keir Fraser13a956a2022-07-14 14:20:46 +0000541 let control_server_socket =
542 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
543 .context("failed to create control server")?;
544 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
545
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000546 debug!("Preserving FDs {:?}", preserved_fds);
547 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000548
Jiyong Park2d736562022-10-24 22:40:12 +0900549 print_crosvm_args(&command);
550
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000551 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900552 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000553 Ok(result)
554}
555
556/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000557fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000558 if config.bootloader.is_none() && config.kernel.is_none() {
559 bail!("VM must have either a bootloader or a kernel image.");
560 }
561 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
562 bail!("Can't have both bootloader and kernel/initrd image.");
563 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900564 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
565 if !config.platform_version.matches(&version) {
566 bail!(
567 "Incompatible platform version. The config is compatible with platform version(s) \
568 {}, but the actual platform version is {}",
569 config.platform_version,
570 version
571 );
572 }
573
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000574 Ok(())
575}
576
Jiyong Park2d736562022-10-24 22:40:12 +0900577/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
578/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
579/// unmodified.
580fn print_crosvm_args(command: &Command) {
581 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
582 info!(
583 "Running crosvm with args: {:?}",
584 command
585 .get_args()
586 .map(|s| s.to_string_lossy())
587 .map(|s| {
588 re.replace_all(&s, |caps: &Captures| {
589 let path = &caps[0];
590 if let Ok(realpath) = std::fs::canonicalize(path) {
591 format!("{} ({})", path, realpath.to_string_lossy())
592 } else {
593 path.to_owned()
594 }
595 })
596 .into_owned()
597 })
598 .collect::<Vec<_>>()
599 );
600}
601
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000602/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
603/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000604fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000605 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000606 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000607 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000608}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000609
610/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
611/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
612fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
613 if let Some(file) = file {
614 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
615 } else {
616 "type=sink".to_string()
617 }
618}
619
620/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
621fn create_pipe() -> Result<(File, File), Error> {
622 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
623 // SAFETY: We are the sole owners of these fds as they were just created.
624 let read_fd = unsafe { File::from_raw_fd(raw_read) };
625 let write_fd = unsafe { File::from_raw_fd(raw_write) };
626 Ok((read_fd, write_fd))
627}