blob: 5873cd9acbd869fafba1be226f4319ca6de04a4b [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};
Andrew Walbrandae07162021-03-12 17:05:20 +000022use shared_child::SharedChild;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use std::fs::{remove_dir_all, File};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000024use std::num::NonZeroU32;
Andrew Walbran02b8ec02021-06-22 13:07:02 +000025use std::os::unix::io::{AsRawFd, RawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000026use std::path::PathBuf;
Andrew Walbrandae07162021-03-12 17:05:20 +000027use std::process::Command;
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::sync::Arc;
30use std::thread;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000031
32const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
33
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000034/// Configuration for a VM to run with crosvm.
35#[derive(Debug)]
36pub struct CrosvmConfig<'a> {
37 pub cid: Cid,
38 pub bootloader: Option<&'a File>,
39 pub kernel: Option<&'a File>,
40 pub initrd: Option<&'a File>,
41 pub disks: Vec<DiskFile>,
42 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000043 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000044 pub memory_mib: Option<NonZeroU32>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000045}
46
47/// A disk image to pass to crosvm for a VM.
48#[derive(Debug)]
49pub struct DiskFile {
50 pub image: File,
51 pub writable: bool,
52}
53
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054/// Information about a particular instance of a VM which is running.
55#[derive(Debug)]
56pub struct VmInstance {
57 /// The crosvm child process.
Andrew Walbrandae07162021-03-12 17:05:20 +000058 child: SharedChild,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000059 /// The CID assigned to the VM for vsock communication.
60 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000061 /// Whether the VM is a protected VM.
62 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000063 /// Directory of temporary files used by the VM while it is running.
64 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000065 /// The UID of the process which requested the VM.
66 pub requester_uid: u32,
67 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +000068 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000069 /// The PID of the process which requested the VM. Note that this process may no longer exist
70 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +000071 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000072 /// Whether the VM is still running.
73 running: AtomicBool,
74 /// Callbacks to clients of the VM.
75 pub callbacks: VirtualMachineCallbacks,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000076}
77
78impl VmInstance {
79 /// Create a new `VmInstance` for the given process.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000080 fn new(
Andrew Walbrandae07162021-03-12 17:05:20 +000081 child: SharedChild,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000082 cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000083 protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000084 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000085 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +000086 requester_sid: String,
87 requester_debug_pid: i32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000088 ) -> VmInstance {
Andrew Walbrandae07162021-03-12 17:05:20 +000089 VmInstance {
90 child,
91 cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000092 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 temporary_directory,
Andrew Walbrandae07162021-03-12 17:05:20 +000094 requester_uid,
95 requester_sid,
Andrew Walbran02034492021-04-13 15:05:07 +000096 requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +000097 running: AtomicBool::new(true),
98 callbacks: Default::default(),
99 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000100 }
101
102 /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
103 /// the `VmInstance` is dropped.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000104 pub fn start(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105 config: &CrosvmConfig,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000106 log_fd: Option<File>,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000107 composite_disk_fds: &[RawFd],
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000108 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000109 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000110 requester_sid: String,
111 requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000112 ) -> Result<Arc<VmInstance>, Error> {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000113 let child = run_vm(config, log_fd, composite_disk_fds)?;
Andrew Walbran02034492021-04-13 15:05:07 +0000114 let instance = Arc::new(VmInstance::new(
115 child,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000116 config.cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000117 config.protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000118 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000119 requester_uid,
120 requester_sid,
121 requester_debug_pid,
122 ));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123
Andrew Walbrandae07162021-03-12 17:05:20 +0000124 let instance_clone = instance.clone();
125 thread::spawn(move || {
126 instance_clone.monitor();
127 });
128
129 Ok(instance)
130 }
131
132 /// Wait for the crosvm child process to finish, then mark the VM as no longer running and call
133 /// any callbacks.
134 fn monitor(&self) {
135 match self.child.wait() {
136 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
137 Ok(status) => info!("crosvm exited with status {}", status),
138 }
139 self.running.store(false, Ordering::Release);
140 self.callbacks.callback_on_died(self.cid);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000141
142 // Delete temporary files.
143 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000144 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000145 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000146 }
147
148 /// Return whether `crosvm` is still running the VM.
149 pub fn running(&self) -> bool {
150 self.running.load(Ordering::Acquire)
151 }
152
153 /// Kill the crosvm instance.
154 pub fn kill(&self) {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000155 // TODO: Talk to crosvm to shutdown cleanly.
156 if let Err(e) = self.child.kill() {
157 error!("Error killing crosvm instance: {}", e);
158 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000159 }
160}
161
162/// Start an instance of `crosvm` to manage a new VM.
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000163fn run_vm(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 config: &CrosvmConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000165 log_fd: Option<File>,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000166 composite_disk_fds: &[RawFd],
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000167) -> Result<SharedChild, Error> {
168 validate_config(config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000169
170 let mut command = Command::new(CROSVM_PATH);
171 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000173
Andrew Walbranf8650422021-06-09 15:54:09 +0000174 if config.protected {
175 command.arg("--protected-vm");
176 }
177
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000178 if let Some(memory_mib) = config.memory_mib {
179 command.arg("--mem").arg(memory_mib.to_string());
180 }
181
Andrew Walbrana89fc132021-03-17 17:08:36 +0000182 if let Some(log_fd) = log_fd {
183 command.stdout(log_fd);
184 } else {
185 // Ignore console output.
186 command.arg("--serial=type=sink");
187 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000188
189 // Keep track of what file descriptors should be mapped to the crosvm process.
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000190 let mut preserved_fds = composite_disk_fds.to_vec();
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000191
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000192 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000193 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000194 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000195
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000196 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000197 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000198 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000199
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000200 if let Some(params) = &config.params {
201 command.arg("--params").arg(params);
202 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000203
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000204 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000205 command
206 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000207 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000208 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000209
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000210 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000211 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000212 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000213
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000214 debug!("Preserving FDs {:?}", preserved_fds);
215 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000216
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000217 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000218 let result = SharedChild::spawn(&mut command)?;
219 Ok(result)
220}
221
222/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000223fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000224 if config.bootloader.is_none() && config.kernel.is_none() {
225 bail!("VM must have either a bootloader or a kernel image.");
226 }
227 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
228 bail!("Can't have both bootloader and kernel/initrd image.");
229 }
230 Ok(())
231}
232
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000233/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
234/// "/proc/self/fd/N" where N is the file descriptor.
235fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000236 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000237 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000238 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000239}