blob: f1b179e6106ad01c4376a185dc7899be17624f51 [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
Andrew Walbrandae07162021-03-12 17:05:20 +000017use crate::aidl::VirtualMachineCallbacks;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000018use crate::Cid;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use anyhow::{bail, Error};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000021use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090022use semver::{Version, VersionReq};
Andrew Walbranb27681f2022-02-23 15:11:52 +000023use nix::{fcntl::OFlag, unistd::pipe2};
Andrew Walbrandae07162021-03-12 17:05:20 +000024use shared_child::SharedChild;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000025use std::fs::{remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000026use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000027use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000028use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000029use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000030use std::path::PathBuf;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000031use std::process::{Command, ExitStatus};
Inseob Kim7f61fe72021-08-20 20:50:47 +090032use std::sync::{Arc, Mutex};
Andrew Walbrandae07162021-03-12 17:05:20 +000033use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090034use vsock::VsockStream;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000035use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
Inseob Kimc7d28c72021-10-25 14:28:10 +000036use android_system_virtualmachineservice::binder::Strong;
37use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000038
39const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
40
Jiyong Parkdcf17412022-02-08 15:07:23 +090041/// Version of the platform that crosvm currently implements. The format follows SemVer. This
42/// should be updated when there is a platform change in the crosvm side. Having this value here is
43/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
44/// APEX.
45const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
46
Andrew Walbrand15c5632022-02-03 13:38:31 +000047/// The exit status which crosvm returns when it has an error starting a VM.
48const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000049/// The exit status which crosvm returns when a VM requests a reboot.
50const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000051/// The exit status which crosvm returns when it crashes due to an error.
52const CROSVM_CRASH_STATUS: i32 = 33;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000053
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000054/// Configuration for a VM to run with crosvm.
55#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000056pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000057 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000058 pub bootloader: Option<File>,
59 pub kernel: Option<File>,
60 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000061 pub disks: Vec<DiskFile>,
62 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000063 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000064 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090065 pub cpus: Option<NonZeroU32>,
66 pub cpu_affinity: Option<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090067 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000068 pub log_fd: Option<File>,
69 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090070 pub platform_version: VersionReq,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071}
72
73/// A disk image to pass to crosvm for a VM.
74#[derive(Debug)]
75pub struct DiskFile {
76 pub image: File,
77 pub writable: bool,
78}
79
Andrew Walbran6b650662021-09-07 13:13:23 +000080/// The lifecycle state which the payload in the VM has reported itself to be in.
81///
82/// Note that the order of enum variants is significant; only forward transitions are allowed by
83/// [`VmInstance::update_payload_state`].
84#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
85pub enum PayloadState {
86 Starting,
87 Started,
88 Ready,
89 Finished,
90}
91
Andrew Walbranf8d94112021-09-07 11:45:36 +000092/// The current state of the VM itself.
93#[derive(Debug)]
94pub enum VmState {
95 /// The VM has not yet tried to start.
96 NotStarted {
97 ///The configuration needed to start the VM, if it has not yet been started.
98 config: CrosvmConfig,
99 },
100 /// The VM has been started.
101 Running {
102 /// The crosvm child process.
103 child: Arc<SharedChild>,
104 },
105 /// The VM died or was killed.
106 Dead,
107 /// The VM failed to start.
108 Failed,
109}
110
111impl VmState {
112 /// Tries to start the VM, if it is in the `NotStarted` state.
113 ///
114 /// Returns an error if the VM is in the wrong state, or fails to start.
115 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
116 let state = mem::replace(self, VmState::Failed);
117 if let VmState::NotStarted { config } = state {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000118 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
119
Andrew Walbranf8d94112021-09-07 11:45:36 +0000120 // If this fails and returns an error, `self` will be left in the `Failed` state.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000121 let child = Arc::new(run_vm(config, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122
123 let child_clone = child.clone();
124 thread::spawn(move || {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000125 instance.monitor(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 });
127
128 // If it started correctly, update the state.
129 *self = VmState::Running { child };
130 Ok(())
131 } else {
132 *self = state;
133 bail!("VM already started or failed")
134 }
135 }
136}
137
138/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000139#[derive(Debug)]
140pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000141 /// The current state of the VM.
142 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000143 /// The CID assigned to the VM for vsock communication.
144 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000145 /// Whether the VM is a protected VM.
146 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000147 /// Directory of temporary files used by the VM while it is running.
148 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000149 /// The UID of the process which requested the VM.
150 pub requester_uid: u32,
151 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000152 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000153 /// The PID of the process which requested the VM. Note that this process may no longer exist
154 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000155 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000156 /// Callbacks to clients of the VM.
157 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900158 /// Input/output stream of the payload run in the VM.
159 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000160 /// VirtualMachineService binder object for the VM.
161 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000162 /// The latest lifecycle state which the payload reported itself to be in.
163 payload_state: Mutex<PayloadState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000164}
165
166impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000167 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
168 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000169 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000170 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000171 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000172 requester_sid: String,
173 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000174 ) -> Result<VmInstance, Error> {
175 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000176 let cid = config.cid;
177 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000178 Ok(VmInstance {
179 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000180 cid,
181 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000182 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000183 requester_uid,
184 requester_sid,
185 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000186 callbacks: Default::default(),
187 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000188 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000189 payload_state: Mutex::new(PayloadState::Starting),
190 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000191 }
192
Andrew Walbranf8d94112021-09-07 11:45:36 +0000193 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
194 /// the `VmInstance` is dropped.
195 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
196 self.vm_state.lock().unwrap().start(self.clone())
197 }
198
199 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
200 /// calls any callbacks.
201 ///
202 /// This takes a separate reference to the `SharedChild` rather than using the one in
203 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000204 fn monitor(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000205 let result = child.wait();
206 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900207 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
208 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000209 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000210
211 let mut vm_state = self.vm_state.lock().unwrap();
212 *vm_state = VmState::Dead;
213 // Ensure that the mutex is released before calling the callbacks.
214 drop(vm_state);
215
Andrew Walbranb27681f2022-02-23 15:11:52 +0000216 let mut failure_string = String::new();
217 let failure_read_result = failure_pipe_read.read_to_string(&mut failure_string);
218 if let Err(e) = &failure_read_result {
219 error!("Error reading VM failure reason from pipe: {}", e);
220 }
221 if !failure_string.is_empty() {
222 info!("VM returned failure reason '{}'", failure_string);
223 }
224
225 self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_string));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000226
227 // Delete temporary files.
228 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000229 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000230 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000231 }
232
Andrew Walbran6b650662021-09-07 13:13:23 +0000233 /// Returns the last reported state of the VM payload.
234 pub fn payload_state(&self) -> PayloadState {
235 *self.payload_state.lock().unwrap()
236 }
237
238 /// Updates the payload state to the given value, if it is a valid state transition.
239 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
240 let mut state_locked = self.payload_state.lock().unwrap();
241 // Only allow forward transitions, e.g. from starting to started or finished, not back in
242 // the other direction.
243 if new_state > *state_locked {
244 *state_locked = new_state;
245 Ok(())
246 } else {
247 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
248 }
249 }
250
Andrew Walbranf8d94112021-09-07 11:45:36 +0000251 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000252 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000253 let vm_state = &*self.vm_state.lock().unwrap();
254 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900255 let id = child.id();
256 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000257 // TODO: Talk to crosvm to shutdown cleanly.
258 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900259 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000260 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000261 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000262 }
263}
264
Andrew Walbranb27681f2022-02-23 15:11:52 +0000265fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000266 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000267 match failure_reason {
268 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
269 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
270 }
271 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
272 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
273 }
274 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
275 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
276 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
277 }
278 _ => {}
279 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000280 match status.code() {
281 None => DeathReason::KILLED,
282 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000283 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000284 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000285 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000286 Some(_) => DeathReason::UNKNOWN,
287 }
288 } else {
289 DeathReason::INFRASTRUCTURE_ERROR
290 }
291}
292
Andrew Walbrand3a84182021-09-07 14:48:52 +0000293/// Starts an instance of `crosvm` to manage a new VM.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000294fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000295 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000296
297 let mut command = Command::new(CROSVM_PATH);
298 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000299 command
300 .arg("--extended-status")
301 .arg("run")
302 .arg("--disable-sandbox")
303 .arg("--cid")
304 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000305
Andrew Walbranf8650422021-06-09 15:54:09 +0000306 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000307 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000308
309 // 3 virtio-console devices + vsock = 4.
310 let virtio_pci_device_count = 4 + config.disks.len();
311 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
312 // enough.
313 let swiotlb_size_mib = 2 * virtio_pci_device_count;
314 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000315 }
316
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000317 if let Some(memory_mib) = config.memory_mib {
318 command.arg("--mem").arg(memory_mib.to_string());
319 }
320
Jiyong Park032615f2022-01-10 13:55:34 +0900321 if let Some(cpus) = config.cpus {
322 command.arg("--cpus").arg(cpus.to_string());
323 }
324
325 if let Some(cpu_affinity) = config.cpu_affinity {
326 command.arg("--cpu-affinity").arg(cpu_affinity);
327 }
328
Jiyong Parkfa91d702021-10-18 23:51:39 +0900329 // Keep track of what file descriptors should be mapped to the crosvm process.
330 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
331
Jiyong Park747d6362021-10-19 17:12:52 +0900332 // Setup the serial devices.
333 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000334 // 2. uart device: used to report the reason for the VM failing.
335 // 3. virtio-console device: used as the console device where kmsg is redirected to
336 // 4. virtio-console device: used as the androidboot.console device (not used currently)
337 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900338 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900339 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
340 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000341 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
342 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
343 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900344
Jiyong Park747d6362021-10-19 17:12:52 +0900345 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
346 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
347 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
348 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900349 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000350 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
351 // /dev/ttyS1
352 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900353 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900354 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900355 // /dev/hvc1 (not used currently)
356 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
357 // /dev/hvc2
358 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000359
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000360 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000361 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000362 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000363
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000364 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000365 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000366 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000367
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000368 if let Some(params) = &config.params {
369 command.arg("--params").arg(params);
370 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000371
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000372 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000373 command
374 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000375 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000376 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000377
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000378 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000379 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000380 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000381
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000382 debug!("Preserving FDs {:?}", preserved_fds);
383 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000384
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000385 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000386 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900387 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000388 Ok(result)
389}
390
391/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000393 if config.bootloader.is_none() && config.kernel.is_none() {
394 bail!("VM must have either a bootloader or a kernel image.");
395 }
396 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
397 bail!("Can't have both bootloader and kernel/initrd image.");
398 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900399 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
400 if !config.platform_version.matches(&version) {
401 bail!(
402 "Incompatible platform version. The config is compatible with platform version(s) \
403 {}, but the actual platform version is {}",
404 config.platform_version,
405 version
406 );
407 }
408
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000409 Ok(())
410}
411
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000412/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
413/// "/proc/self/fd/N" where N is the file descriptor.
414fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000415 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000416 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000417 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000418}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000419
420/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
421/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
422fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
423 if let Some(file) = file {
424 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
425 } else {
426 "type=sink".to_string()
427 }
428}
429
430/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
431fn create_pipe() -> Result<(File, File), Error> {
432 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
433 // SAFETY: We are the sole owners of these fds as they were just created.
434 let read_fd = unsafe { File::from_raw_fd(raw_read) };
435 let write_fd = unsafe { File::from_raw_fd(raw_write) };
436 Ok((read_fd, write_fd))
437}