blob: 3f1660e6e7d4f7f9b48e2880ffa601e55eb31d98 [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
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000017use crate::composite::make_composite_image;
18use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
Jooyung Han21e9b922021-06-26 04:14:16 +090019use crate::payload;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000020use crate::{Cid, FIRST_GUEST_CID};
Jooyung Han21e9b922021-06-26 04:14:16 +090021
Andrew Walbranf6bf6862021-05-21 12:41:13 +000022use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000025 BnVirtualMachine, IVirtualMachine,
26};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000027use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
Jooyung Han21e9b922021-06-26 04:14:16 +090028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
29 VirtualMachineAppConfig::VirtualMachineAppConfig,
30 VirtualMachineConfig::VirtualMachineConfig,
31 VirtualMachineRawConfig::VirtualMachineRawConfig,
32};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000033use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
34use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000035 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000036};
Jooyung Han21e9b922021-06-26 04:14:16 +090037use anyhow::Error;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000038use disk::QcowFile;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000039use log::{debug, error, warn};
Jooyung Han21e9b922021-06-26 04:14:16 +090040use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000041use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000042use std::ffi::CString;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000043use std::fs::{File, create_dir};
44use std::os::unix::io::AsRawFd;
45use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000046use std::sync::{Arc, Mutex, Weak};
Jooyung Han21e9b922021-06-26 04:14:16 +090047use vmconfig::VmConfig;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000048
Andrew Walbranf6bf6862021-05-21 12:41:13 +000049pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000051/// Directory in which to write disk image files used while running VMs.
52const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
53
Andrew Walbran320b5602021-03-04 16:11:12 +000054// TODO(qwandor): Use PermissionController once it is available to Rust.
55/// Only processes running with one of these UIDs are allowed to call debug methods.
56const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
57
Andrew Walbranf6bf6862021-05-21 12:41:13 +000058/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000059#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000060pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000061 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000062}
63
Andrew Walbranf6bf6862021-05-21 12:41:13 +000064impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000065
Andrew Walbranf6bf6862021-05-21 12:41:13 +000066impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000067 /// Create and start a new VM with the given configuration, assigning it the next available CID.
68 ///
69 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000070 fn startVm(
71 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000072 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000073 log_fd: Option<&ParcelFileDescriptor>,
74 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000075 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000077 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000079 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000080 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081
82 // Counter to generate unique IDs for temporary image files.
83 let mut next_temporary_image_id = 0;
84 // Files which are referred to from composite images. These must be mapped to the crosvm
85 // child process, and not closed before it is started.
86 let mut indirect_files = vec![];
87
88 // Make directory for temporary files.
89 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
90 create_dir(&temporary_directory).map_err(|e| {
91 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +000092 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 temporary_directory, e
94 );
Andrew Walbran806f1542021-06-10 14:07:12 +000095 new_binder_exception(
96 ExceptionCode::SERVICE_SPECIFIC,
97 format!(
98 "Failed to create temporary directory {:?} for VM files: {}",
99 temporary_directory, e
100 ),
101 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102 })?;
103
Jooyung Han21e9b922021-06-26 04:14:16 +0900104 let mut opt_raw_config = None;
105 let config = match config {
106 VirtualMachineConfig::AppConfig(config) => {
107 let raw_config = load_app_config(config, &temporary_directory).map_err(|e| {
108 error!("Failed to load app config from {}: {}", &config.configPath, e);
109 new_binder_exception(
110 ExceptionCode::SERVICE_SPECIFIC,
111 format!("Failed to load app config from {}: {}", &config.configPath, e),
112 )
113 })?;
114 opt_raw_config.replace(raw_config);
115 opt_raw_config.as_ref().unwrap()
116 }
117 VirtualMachineConfig::RawConfig(config) => config,
118 };
119
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000120 // Assemble disk images if needed.
121 let disks = config
122 .disks
123 .iter()
124 .map(|disk| {
125 assemble_disk_image(
126 disk,
127 &temporary_directory,
128 &mut next_temporary_image_id,
129 &mut indirect_files,
130 )
131 })
132 .collect::<Result<Vec<DiskFile>, _>>()?;
133
134 // Actually start the VM.
135 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000136 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000137 bootloader: as_asref(&config.bootloader),
138 kernel: as_asref(&config.kernel),
139 initrd: as_asref(&config.initrd),
140 disks,
141 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000142 protected: config.protected_vm,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000143 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000144 let composite_disk_fds: Vec<_> =
145 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000146 let instance = VmInstance::start(
147 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000148 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000149 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000150 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000151 requester_uid,
152 requester_sid,
153 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000154 )
155 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000156 error!("Failed to start VM with config {:?}: {}", config, e);
157 new_binder_exception(
158 ExceptionCode::SERVICE_SPECIFIC,
159 format!("Failed to start VM: {}", e),
160 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000161 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000162 state.add_vm(Arc::downgrade(&instance));
163 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000164 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000165
Andrew Walbrandff3b942021-06-09 15:20:36 +0000166 /// Initialise an empty partition image of the given size to be used as a writable partition.
167 fn initializeWritablePartition(
168 &self,
169 image_fd: &ParcelFileDescriptor,
170 size: i64,
171 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000172 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000173 new_binder_exception(
174 ExceptionCode::ILLEGAL_ARGUMENT,
175 format!("Invalid size {}: {}", size, e),
176 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000177 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000178 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000179
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000180 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000181 new_binder_exception(
182 ExceptionCode::SERVICE_SPECIFIC,
183 format!("Failed to create QCOW2 image: {}", e),
184 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000185 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000186
187 Ok(())
188 }
189
Andrew Walbran320b5602021-03-04 16:11:12 +0000190 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
191 /// and as such is only permitted from the shell user.
192 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000193 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000194
195 let state = &mut *self.state.lock().unwrap();
196 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000197 let cids = vms
198 .into_iter()
199 .map(|vm| VirtualMachineDebugInfo {
200 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000201 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000202 requesterUid: vm.requester_uid as i32,
203 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000204 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000205 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000206 })
207 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000208 Ok(cids)
209 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000210
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000211 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
212 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000213 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000214 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000215
David Brazdil3c2ddef2021-03-18 13:09:57 +0000216 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000217 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000218 Ok(())
219 }
220
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000221 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
222 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
223 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000224 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000225 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000226
227 let state = &mut *self.state.lock().unwrap();
228 Ok(state.debug_drop_vm(cid))
229 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000230}
231
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000232/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
233///
234/// This may involve assembling a composite disk from a set of partition images.
235fn assemble_disk_image(
236 disk: &DiskImage,
237 temporary_directory: &Path,
238 next_temporary_image_id: &mut u64,
239 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000240) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000241 let image = if !disk.partitions.is_empty() {
242 if disk.image.is_some() {
243 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000244 return Err(new_binder_exception(
245 ExceptionCode::ILLEGAL_ARGUMENT,
246 "DiskImage contains both image and partitions.",
247 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000248 }
249
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000250 let composite_image_filenames =
251 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
252 let (image, partition_files) = make_composite_image(
253 &disk.partitions,
254 &composite_image_filenames.composite,
255 &composite_image_filenames.header,
256 &composite_image_filenames.footer,
257 )
258 .map_err(|e| {
259 error!("Failed to make composite image with config {:?}: {}", disk, e);
260 new_binder_exception(
261 ExceptionCode::SERVICE_SPECIFIC,
262 format!("Failed to make composite image: {}", e),
263 )
264 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000265
266 // Pass the file descriptors for the various partition files to crosvm when it
267 // is run.
268 indirect_files.extend(partition_files);
269
270 image
271 } else if let Some(image) = &disk.image {
272 clone_file(image)?
273 } else {
274 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000275 return Err(new_binder_exception(
276 ExceptionCode::ILLEGAL_ARGUMENT,
277 "DiskImage didn't contain image or partitions.",
278 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000279 };
280
281 Ok(DiskFile { image, writable: disk.writable })
282}
283
Jooyung Han21e9b922021-06-26 04:14:16 +0900284fn load_app_config(
285 config: &VirtualMachineAppConfig,
286 temporary_directory: &Path,
287) -> Result<VirtualMachineRawConfig, Error> {
288 let apk_file = config.apk.as_ref().unwrap().as_ref();
289 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
290 let config_path = &config.configPath;
291
292 let mut apk_zip = zip::ZipArchive::new(apk_file)?;
293 let config_file = apk_zip.by_name(config_path)?;
294 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
295
296 let os_name = &vm_payload_config.os.name;
297 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
298 let vm_config_file = File::open(vm_config_path)?;
299 let mut vm_config = VmConfig::load(&vm_config_file)?;
300
301 vm_config.disks.push(payload::make_disk_image(
302 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
303 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
304 config_path,
305 &vm_payload_config.apexes,
306 temporary_directory,
307 )?);
308
309 vm_config.to_parcelable()
310}
311
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000312/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000313fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000314 temporary_directory: &Path,
315 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000316) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000317 let id = *next_temporary_image_id;
318 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000319 CompositeImageFilenames {
320 composite: temporary_directory.join(format!("composite-{}.img", id)),
321 header: temporary_directory.join(format!("composite-{}-header.img", id)),
322 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
323 }
324}
325
326/// Filenames for a composite disk image, including header and footer partitions.
327#[derive(Clone, Debug, Eq, PartialEq)]
328struct CompositeImageFilenames {
329 /// The composite disk image itself.
330 composite: PathBuf,
331 /// The header partition image.
332 header: PathBuf,
333 /// The footer partition image.
334 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000335}
336
337/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000338fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000339 ThreadState::with_calling_sid(|sid| {
340 if let Some(sid) = sid {
341 match sid.to_str() {
342 Ok(sid) => Ok(sid.to_owned()),
343 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000344 error!("SID was not valid UTF-8: {}", e);
345 Err(new_binder_exception(
346 ExceptionCode::ILLEGAL_ARGUMENT,
347 format!("SID was not valid UTF-8: {}", e),
348 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000349 }
350 }
351 } else {
352 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000353 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000354 }
355 })
356}
357
Andrew Walbran320b5602021-03-04 16:11:12 +0000358/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000359fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000360 let uid = ThreadState::get_calling_uid();
361 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000362 if DEBUG_ALLOWED_UIDS.contains(&uid) {
363 Ok(())
364 } else {
365 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
366 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000367}
368
369/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
370#[derive(Debug)]
371struct VirtualMachine {
372 instance: Arc<VmInstance>,
373}
374
375impl VirtualMachine {
376 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
377 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000378 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000379 }
380}
381
382impl Interface for VirtualMachine {}
383
384impl IVirtualMachine for VirtualMachine {
385 fn getCid(&self) -> binder::Result<i32> {
386 Ok(self.instance.cid as i32)
387 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000388
389 fn isRunning(&self) -> binder::Result<bool> {
390 Ok(self.instance.running())
391 }
392
393 fn registerCallback(
394 &self,
395 callback: &Strong<dyn IVirtualMachineCallback>,
396 ) -> binder::Result<()> {
397 // TODO: Should this give an error if the VM is already dead?
398 self.instance.callbacks.add(callback.clone());
399 Ok(())
400 }
401}
402
403impl Drop for VirtualMachine {
404 fn drop(&mut self) {
405 debug!("Dropping {:?}", self);
406 self.instance.kill();
407 }
408}
409
410/// A set of Binders to be called back in response to various events on the VM, such as when it
411/// dies.
412#[derive(Debug, Default)]
413pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
414
415impl VirtualMachineCallbacks {
416 /// Call all registered callbacks to say that the VM has died.
417 pub fn callback_on_died(&self, cid: Cid) {
418 let callbacks = &*self.0.lock().unwrap();
419 for callback in callbacks {
420 if let Err(e) = callback.onDied(cid as i32) {
421 error!("Error calling callback: {}", e);
422 }
423 }
424 }
425
426 /// Add a new callback to the set.
427 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
428 self.0.lock().unwrap().push(callback);
429 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000430}
431
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000432/// The mutable state of the VirtualizationService. There should only be one instance of this
433/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000434#[derive(Debug)]
435struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000436 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000437 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000438
439 /// The VMs which have been started. When VMs are started a weak reference is added to this list
440 /// while a strong reference is returned to the caller over Binder. Once all copies of the
441 /// Binder client are dropped the weak reference here will become invalid, and will be removed
442 /// from the list opportunistically the next time `add_vm` is called.
443 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000444
445 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
446 /// This is only used for debugging purposes.
447 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000448}
449
450impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000451 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000452 fn vms(&self) -> Vec<Arc<VmInstance>> {
453 // Attempt to upgrade the weak pointers to strong pointers.
454 self.vms.iter().filter_map(Weak::upgrade).collect()
455 }
456
457 /// Add a new VM to the list.
458 fn add_vm(&mut self, vm: Weak<VmInstance>) {
459 // Garbage collect any entries from the stored list which no longer exist.
460 self.vms.retain(|vm| vm.strong_count() > 0);
461
462 // Actually add the new VM.
463 self.vms.push(vm);
464 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000465
466 /// Store a strong VM reference.
467 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
468 self.debug_held_vms.push(vm);
469 }
470
471 /// Retrieve and remove a strong VM reference.
472 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
473 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
474 Some(self.debug_held_vms.swap_remove(pos))
475 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000476
477 /// Get the next available CID, or an error if we have run out.
478 fn allocate_cid(&mut self) -> binder::Result<Cid> {
479 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
480 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000481 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000482 Ok(cid)
483 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000484}
485
486impl Default for State {
487 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000488 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000489 }
490}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000491
492/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
493fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
494 option.as_ref().map(|t| t.as_ref())
495}
496
497/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000498fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
499 file.as_ref().try_clone().map_err(|e| {
500 new_binder_exception(
501 ExceptionCode::BAD_PARCELABLE,
502 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
503 )
504 })
505}
506
507/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
508fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
509 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000510}