blob: ae8388a3fcd8ebfb50e70c3752d6427ddfec9787 [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 Walbran02b8ec02021-06-22 13:07:02 +000024use std::os::unix::io::{AsRawFd, RawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000025use std::path::PathBuf;
Andrew Walbrandae07162021-03-12 17:05:20 +000026use std::process::Command;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::sync::Arc;
29use std::thread;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000030
31const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
32
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000033/// Configuration for a VM to run with crosvm.
34#[derive(Debug)]
35pub struct CrosvmConfig<'a> {
36 pub cid: Cid,
37 pub bootloader: Option<&'a File>,
38 pub kernel: Option<&'a File>,
39 pub initrd: Option<&'a File>,
40 pub disks: Vec<DiskFile>,
41 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000042 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000043}
44
45/// A disk image to pass to crosvm for a VM.
46#[derive(Debug)]
47pub struct DiskFile {
48 pub image: File,
49 pub writable: bool,
50}
51
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000052/// Information about a particular instance of a VM which is running.
53#[derive(Debug)]
54pub struct VmInstance {
55 /// The crosvm child process.
Andrew Walbrandae07162021-03-12 17:05:20 +000056 child: SharedChild,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000057 /// The CID assigned to the VM for vsock communication.
58 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000059 /// Whether the VM is a protected VM.
60 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000061 /// Directory of temporary files used by the VM while it is running.
62 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000063 /// The UID of the process which requested the VM.
64 pub requester_uid: u32,
65 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +000066 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000067 /// The PID of the process which requested the VM. Note that this process may no longer exist
68 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +000069 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000070 /// Whether the VM is still running.
71 running: AtomicBool,
72 /// Callbacks to clients of the VM.
73 pub callbacks: VirtualMachineCallbacks,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000074}
75
76impl VmInstance {
77 /// Create a new `VmInstance` for the given process.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000078 fn new(
Andrew Walbrandae07162021-03-12 17:05:20 +000079 child: SharedChild,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000080 cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000081 protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000082 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000083 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +000084 requester_sid: String,
85 requester_debug_pid: i32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000086 ) -> VmInstance {
Andrew Walbrandae07162021-03-12 17:05:20 +000087 VmInstance {
88 child,
89 cid,
Andrew Walbranf8650422021-06-09 15:54:09 +000090 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091 temporary_directory,
Andrew Walbrandae07162021-03-12 17:05:20 +000092 requester_uid,
93 requester_sid,
Andrew Walbran02034492021-04-13 15:05:07 +000094 requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +000095 running: AtomicBool::new(true),
96 callbacks: Default::default(),
97 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000098 }
99
100 /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
101 /// the `VmInstance` is dropped.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000102 pub fn start(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000103 config: &CrosvmConfig,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000104 log_fd: Option<File>,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000105 composite_disk_fds: &[RawFd],
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000107 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000108 requester_sid: String,
109 requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000110 ) -> Result<Arc<VmInstance>, Error> {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000111 let child = run_vm(config, log_fd, composite_disk_fds)?;
Andrew Walbran02034492021-04-13 15:05:07 +0000112 let instance = Arc::new(VmInstance::new(
113 child,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000114 config.cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000115 config.protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000116 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000117 requester_uid,
118 requester_sid,
119 requester_debug_pid,
120 ));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000121
Andrew Walbrandae07162021-03-12 17:05:20 +0000122 let instance_clone = instance.clone();
123 thread::spawn(move || {
124 instance_clone.monitor();
125 });
126
127 Ok(instance)
128 }
129
130 /// Wait for the crosvm child process to finish, then mark the VM as no longer running and call
131 /// any callbacks.
132 fn monitor(&self) {
133 match self.child.wait() {
134 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
135 Ok(status) => info!("crosvm exited with status {}", status),
136 }
137 self.running.store(false, Ordering::Release);
138 self.callbacks.callback_on_died(self.cid);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000139
140 // Delete temporary files.
141 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000142 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000143 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000144 }
145
146 /// Return whether `crosvm` is still running the VM.
147 pub fn running(&self) -> bool {
148 self.running.load(Ordering::Acquire)
149 }
150
151 /// Kill the crosvm instance.
152 pub fn kill(&self) {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000153 // TODO: Talk to crosvm to shutdown cleanly.
154 if let Err(e) = self.child.kill() {
155 error!("Error killing crosvm instance: {}", e);
156 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000157 }
158}
159
160/// Start an instance of `crosvm` to manage a new VM.
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000161fn run_vm(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000162 config: &CrosvmConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000163 log_fd: Option<File>,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000164 composite_disk_fds: &[RawFd],
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000165) -> Result<SharedChild, Error> {
166 validate_config(config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000167
168 let mut command = Command::new(CROSVM_PATH);
169 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000170 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000171
Andrew Walbranf8650422021-06-09 15:54:09 +0000172 if config.protected {
173 command.arg("--protected-vm");
174 }
175
Andrew Walbrana89fc132021-03-17 17:08:36 +0000176 if let Some(log_fd) = log_fd {
177 command.stdout(log_fd);
178 } else {
179 // Ignore console output.
180 command.arg("--serial=type=sink");
181 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000182
183 // Keep track of what file descriptors should be mapped to the crosvm process.
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000184 let mut preserved_fds = composite_disk_fds.to_vec();
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000185
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000186 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000187 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000188 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000189
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000190 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000191 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000192 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000193
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000194 if let Some(params) = &config.params {
195 command.arg("--params").arg(params);
196 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000197
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000198 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000199 command
200 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000201 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000202 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000203
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000204 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000205 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000206 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000207
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000208 debug!("Preserving FDs {:?}", preserved_fds);
209 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000210
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000211 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000212 let result = SharedChild::spawn(&mut command)?;
213 Ok(result)
214}
215
216/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000217fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000218 if config.bootloader.is_none() && config.kernel.is_none() {
219 bail!("VM must have either a bootloader or a kernel image.");
220 }
221 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
222 bail!("Can't have both bootloader and kernel/initrd image.");
223 }
224 Ok(())
225}
226
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000227/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
228/// "/proc/self/fd/N" where N is the file descriptor.
229fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000230 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000231 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000232 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000233}