blob: fcc09c66dd04a9acda9f86ba02671fed9f0c636d [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 Parkdfe16d62022-04-20 17:32:12 +090067 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090068 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000069 pub log_fd: Option<File>,
70 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090071 pub platform_version: VersionReq,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072}
73
74/// A disk image to pass to crosvm for a VM.
75#[derive(Debug)]
76pub struct DiskFile {
77 pub image: File,
78 pub writable: bool,
79}
80
Andrew Walbran6b650662021-09-07 13:13:23 +000081/// The lifecycle state which the payload in the VM has reported itself to be in.
82///
83/// Note that the order of enum variants is significant; only forward transitions are allowed by
84/// [`VmInstance::update_payload_state`].
85#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
86pub enum PayloadState {
87 Starting,
88 Started,
89 Ready,
90 Finished,
91}
92
Andrew Walbranf8d94112021-09-07 11:45:36 +000093/// The current state of the VM itself.
94#[derive(Debug)]
95pub enum VmState {
96 /// The VM has not yet tried to start.
97 NotStarted {
98 ///The configuration needed to start the VM, if it has not yet been started.
99 config: CrosvmConfig,
100 },
101 /// The VM has been started.
102 Running {
103 /// The crosvm child process.
104 child: Arc<SharedChild>,
105 },
106 /// The VM died or was killed.
107 Dead,
108 /// The VM failed to start.
109 Failed,
110}
111
112impl VmState {
113 /// Tries to start the VM, if it is in the `NotStarted` state.
114 ///
115 /// Returns an error if the VM is in the wrong state, or fails to start.
116 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
117 let state = mem::replace(self, VmState::Failed);
118 if let VmState::NotStarted { config } = state {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000119 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
120
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121 // If this fails and returns an error, `self` will be left in the `Failed` state.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000122 let child = Arc::new(run_vm(config, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000123
124 let child_clone = child.clone();
125 thread::spawn(move || {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000126 instance.monitor(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000127 });
128
129 // If it started correctly, update the state.
130 *self = VmState::Running { child };
131 Ok(())
132 } else {
133 *self = state;
134 bail!("VM already started or failed")
135 }
136 }
137}
138
139/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000140#[derive(Debug)]
141pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000142 /// The current state of the VM.
143 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000144 /// The CID assigned to the VM for vsock communication.
145 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000146 /// Whether the VM is a protected VM.
147 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 /// Directory of temporary files used by the VM while it is running.
149 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000150 /// The UID of the process which requested the VM.
151 pub requester_uid: u32,
152 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000153 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000154 /// The PID of the process which requested the VM. Note that this process may no longer exist
155 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000156 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000157 /// Callbacks to clients of the VM.
158 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900159 /// Input/output stream of the payload run in the VM.
160 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000161 /// VirtualMachineService binder object for the VM.
162 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000163 /// The latest lifecycle state which the payload reported itself to be in.
164 payload_state: Mutex<PayloadState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000165}
166
167impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000168 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
169 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000170 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000171 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000172 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000173 requester_sid: String,
174 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000175 ) -> Result<VmInstance, Error> {
176 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000177 let cid = config.cid;
178 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000179 Ok(VmInstance {
180 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000181 cid,
182 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000183 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000184 requester_uid,
185 requester_sid,
186 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000187 callbacks: Default::default(),
188 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000189 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000190 payload_state: Mutex::new(PayloadState::Starting),
191 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000192 }
193
Andrew Walbranf8d94112021-09-07 11:45:36 +0000194 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
195 /// the `VmInstance` is dropped.
196 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
197 self.vm_state.lock().unwrap().start(self.clone())
198 }
199
200 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
201 /// calls any callbacks.
202 ///
203 /// This takes a separate reference to the `SharedChild` rather than using the one in
204 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000205 fn monitor(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000206 let result = child.wait();
207 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900208 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
209 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000210 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000211
212 let mut vm_state = self.vm_state.lock().unwrap();
213 *vm_state = VmState::Dead;
214 // Ensure that the mutex is released before calling the callbacks.
215 drop(vm_state);
216
Andrew Walbranb27681f2022-02-23 15:11:52 +0000217 let mut failure_string = String::new();
218 let failure_read_result = failure_pipe_read.read_to_string(&mut failure_string);
219 if let Err(e) = &failure_read_result {
220 error!("Error reading VM failure reason from pipe: {}", e);
221 }
222 if !failure_string.is_empty() {
223 info!("VM returned failure reason '{}'", failure_string);
224 }
225
226 self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_string));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000227
228 // Delete temporary files.
229 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000230 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000231 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000232 }
233
Andrew Walbran6b650662021-09-07 13:13:23 +0000234 /// Returns the last reported state of the VM payload.
235 pub fn payload_state(&self) -> PayloadState {
236 *self.payload_state.lock().unwrap()
237 }
238
239 /// Updates the payload state to the given value, if it is a valid state transition.
240 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
241 let mut state_locked = self.payload_state.lock().unwrap();
242 // Only allow forward transitions, e.g. from starting to started or finished, not back in
243 // the other direction.
244 if new_state > *state_locked {
245 *state_locked = new_state;
246 Ok(())
247 } else {
248 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
249 }
250 }
251
Andrew Walbranf8d94112021-09-07 11:45:36 +0000252 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000253 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000254 let vm_state = &*self.vm_state.lock().unwrap();
255 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900256 let id = child.id();
257 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000258 // TODO: Talk to crosvm to shutdown cleanly.
259 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900260 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000261 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000262 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000263 }
264}
265
Andrew Walbranb27681f2022-02-23 15:11:52 +0000266fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000267 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000268 match failure_reason {
269 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
270 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
271 }
272 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
273 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
274 }
275 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
276 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
277 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
278 }
Inseob Kim272f5722022-06-13 17:14:51 +0900279 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
280 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
281 }
282 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
283 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
284 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
285 }
286 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
287 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
288 }
289 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
290 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
291 }
Andrew Walbranb27681f2022-02-23 15:11:52 +0000292 _ => {}
293 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000294 match status.code() {
295 None => DeathReason::KILLED,
296 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000297 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000298 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000299 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000300 Some(_) => DeathReason::UNKNOWN,
301 }
302 } else {
303 DeathReason::INFRASTRUCTURE_ERROR
304 }
305}
306
Andrew Walbrand3a84182021-09-07 14:48:52 +0000307/// Starts an instance of `crosvm` to manage a new VM.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000308fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000309 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000310
311 let mut command = Command::new(CROSVM_PATH);
312 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000313 command
314 .arg("--extended-status")
315 .arg("run")
316 .arg("--disable-sandbox")
317 .arg("--cid")
318 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000319
Andrew Walbranf8650422021-06-09 15:54:09 +0000320 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000321 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000322
323 // 3 virtio-console devices + vsock = 4.
324 let virtio_pci_device_count = 4 + config.disks.len();
325 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
326 // enough.
327 let swiotlb_size_mib = 2 * virtio_pci_device_count;
328 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000329 }
330
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000331 if let Some(memory_mib) = config.memory_mib {
332 command.arg("--mem").arg(memory_mib.to_string());
333 }
334
Jiyong Park032615f2022-01-10 13:55:34 +0900335 if let Some(cpus) = config.cpus {
336 command.arg("--cpus").arg(cpus.to_string());
337 }
338
339 if let Some(cpu_affinity) = config.cpu_affinity {
340 command.arg("--cpu-affinity").arg(cpu_affinity);
341 }
342
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900343 if !config.task_profiles.is_empty() {
344 command.arg("--task-profiles").arg(config.task_profiles.join(","));
345 }
346
Jiyong Parkfa91d702021-10-18 23:51:39 +0900347 // Keep track of what file descriptors should be mapped to the crosvm process.
348 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
349
Jiyong Park747d6362021-10-19 17:12:52 +0900350 // Setup the serial devices.
351 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000352 // 2. uart device: used to report the reason for the VM failing.
353 // 3. virtio-console device: used as the console device where kmsg is redirected to
354 // 4. virtio-console device: used as the androidboot.console device (not used currently)
355 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900356 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900357 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
358 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000359 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
360 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
361 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900362
Jiyong Park747d6362021-10-19 17:12:52 +0900363 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
364 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
365 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
366 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900367 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000368 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
369 // /dev/ttyS1
370 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900371 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900372 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900373 // /dev/hvc1 (not used currently)
374 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
375 // /dev/hvc2
376 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000377
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000378 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000379 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000380 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000381
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000382 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000383 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000384 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000385
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000386 if let Some(params) = &config.params {
387 command.arg("--params").arg(params);
388 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000389
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000390 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000391 command
392 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000393 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000394 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000395
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000396 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000397 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000398 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000399
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000400 debug!("Preserving FDs {:?}", preserved_fds);
401 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000402
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000403 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000404 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900405 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000406 Ok(result)
407}
408
409/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000410fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000411 if config.bootloader.is_none() && config.kernel.is_none() {
412 bail!("VM must have either a bootloader or a kernel image.");
413 }
414 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
415 bail!("Can't have both bootloader and kernel/initrd image.");
416 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900417 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
418 if !config.platform_version.matches(&version) {
419 bail!(
420 "Incompatible platform version. The config is compatible with platform version(s) \
421 {}, but the actual platform version is {}",
422 config.platform_version,
423 version
424 );
425 }
426
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000427 Ok(())
428}
429
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000430/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
431/// "/proc/self/fd/N" where N is the file descriptor.
432fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000433 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000434 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000435 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000436}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000437
438/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
439/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
440fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
441 if let Some(file) = file {
442 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
443 } else {
444 "type=sink".to_string()
445 }
446}
447
448/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
449fn create_pipe() -> Result<(File, File), Error> {
450 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
451 // SAFETY: We are the sole owners of these fds as they were just created.
452 let read_fd = unsafe { File::from_raw_fd(raw_read) };
453 let write_fd = unsafe { File::from_raw_fd(raw_write) };
454 Ok((read_fd, write_fd))
455}