blob: 8bdfa9d1def6467df85bf538f92420474810fd5f [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 Han9900f3d2021-07-06 10:27:54 +090019use crate::payload::make_payload_disk;
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 Han35edb8f2021-07-01 16:17:16 +090037use anyhow::{bail, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000038use disk::QcowFile;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000039use log::{debug, error, warn};
Jooyung Hanadfb76c2021-06-28 17:29:30 +090040use microdroid_payload_config::{ApexConfig, 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};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000044use std::num::NonZeroU32;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000045use std::os::unix::io::AsRawFd;
46use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000047use std::sync::{Arc, Mutex, Weak};
Jiyong Park23601142021-07-05 13:15:32 +090048use vmconfig::{VmConfig, Partition};
Jooyung Han35edb8f2021-07-01 16:17:16 +090049use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050
Andrew Walbranf6bf6862021-05-21 12:41:13 +000051pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000052
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000053/// Directory in which to write disk image files used while running VMs.
54const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
55
Andrew Walbran320b5602021-03-04 16:11:12 +000056// TODO(qwandor): Use PermissionController once it is available to Rust.
57/// Only processes running with one of these UIDs are allowed to call debug methods.
58const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
59
Jooyung Han35edb8f2021-07-01 16:17:16 +090060/// The list of APEXes which microdroid requires.
61/// TODO(b/192200378) move this to microdroid.json?
Jooyung Han1a72c6f2021-07-09 13:47:10 +090062const MICRODROID_REQUIRED_APEXES: [&str; 3] =
63 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
Jooyung Han35edb8f2021-07-01 16:17:16 +090064
Andrew Walbranf6bf6862021-05-21 12:41:13 +000065/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090066#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000067pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000068 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000069}
70
Andrew Walbranf6bf6862021-05-21 12:41:13 +000071impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000072
Andrew Walbranf6bf6862021-05-21 12:41:13 +000073impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000074 /// Create and start a new VM with the given configuration, assigning it the next available CID.
75 ///
76 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000077 fn startVm(
78 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000079 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000080 log_fd: Option<&ParcelFileDescriptor>,
81 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000082 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000083 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000084 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000085 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000086 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000087 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000088
89 // Counter to generate unique IDs for temporary image files.
90 let mut next_temporary_image_id = 0;
91 // Files which are referred to from composite images. These must be mapped to the crosvm
92 // child process, and not closed before it is started.
93 let mut indirect_files = vec![];
94
95 // Make directory for temporary files.
96 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
97 create_dir(&temporary_directory).map_err(|e| {
98 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +000099 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100 temporary_directory, e
101 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000102 new_binder_exception(
103 ExceptionCode::SERVICE_SPECIFIC,
104 format!(
105 "Failed to create temporary directory {:?} for VM files: {}",
106 temporary_directory, e
107 ),
108 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109 })?;
110
Jooyung Han21e9b922021-06-26 04:14:16 +0900111 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900112 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900113 load_app_config(config, &temporary_directory).map_err(|e| {
114 error!("Failed to load app config from {}: {}", &config.configPath, e);
115 new_binder_exception(
116 ExceptionCode::SERVICE_SPECIFIC,
117 format!("Failed to load app config from {}: {}", &config.configPath, e),
118 )
119 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900120 ),
121 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900122 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900123 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900124
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000125 // Assemble disk images if needed.
126 let disks = config
127 .disks
128 .iter()
129 .map(|disk| {
130 assemble_disk_image(
131 disk,
132 &temporary_directory,
133 &mut next_temporary_image_id,
134 &mut indirect_files,
135 )
136 })
137 .collect::<Result<Vec<DiskFile>, _>>()?;
138
139 // Actually start the VM.
140 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000141 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000142 bootloader: as_asref(&config.bootloader),
143 kernel: as_asref(&config.kernel),
144 initrd: as_asref(&config.initrd),
145 disks,
146 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000147 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000148 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000149 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000150 let composite_disk_fds: Vec<_> =
151 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000152 let instance = VmInstance::start(
153 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000154 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000155 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000157 requester_uid,
158 requester_sid,
159 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000160 )
161 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000162 error!("Failed to start VM with config {:?}: {}", config, e);
163 new_binder_exception(
164 ExceptionCode::SERVICE_SPECIFIC,
165 format!("Failed to start VM: {}", e),
166 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000167 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000168 state.add_vm(Arc::downgrade(&instance));
169 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000170 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000171
Andrew Walbrandff3b942021-06-09 15:20:36 +0000172 /// Initialise an empty partition image of the given size to be used as a writable partition.
173 fn initializeWritablePartition(
174 &self,
175 image_fd: &ParcelFileDescriptor,
176 size: i64,
177 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000178 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000179 new_binder_exception(
180 ExceptionCode::ILLEGAL_ARGUMENT,
181 format!("Invalid size {}: {}", size, e),
182 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000183 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000184 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000185
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000186 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000187 new_binder_exception(
188 ExceptionCode::SERVICE_SPECIFIC,
189 format!("Failed to create QCOW2 image: {}", e),
190 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000191 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000192
193 Ok(())
194 }
195
Andrew Walbran320b5602021-03-04 16:11:12 +0000196 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
197 /// and as such is only permitted from the shell user.
198 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000199 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000200
201 let state = &mut *self.state.lock().unwrap();
202 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000203 let cids = vms
204 .into_iter()
205 .map(|vm| VirtualMachineDebugInfo {
206 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000207 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000208 requesterUid: vm.requester_uid as i32,
209 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000210 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000211 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000212 })
213 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000214 Ok(cids)
215 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000216
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000217 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
218 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000219 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000220 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000221
David Brazdil3c2ddef2021-03-18 13:09:57 +0000222 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000223 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000224 Ok(())
225 }
226
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000227 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
228 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
229 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000230 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000231 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000232
233 let state = &mut *self.state.lock().unwrap();
234 Ok(state.debug_drop_vm(cid))
235 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000236}
237
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000238/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
239///
240/// This may involve assembling a composite disk from a set of partition images.
241fn assemble_disk_image(
242 disk: &DiskImage,
243 temporary_directory: &Path,
244 next_temporary_image_id: &mut u64,
245 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000246) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000247 let image = if !disk.partitions.is_empty() {
248 if disk.image.is_some() {
249 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000250 return Err(new_binder_exception(
251 ExceptionCode::ILLEGAL_ARGUMENT,
252 "DiskImage contains both image and partitions.",
253 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000254 }
255
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000256 let composite_image_filenames =
257 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
258 let (image, partition_files) = make_composite_image(
259 &disk.partitions,
260 &composite_image_filenames.composite,
261 &composite_image_filenames.header,
262 &composite_image_filenames.footer,
263 )
264 .map_err(|e| {
265 error!("Failed to make composite image with config {:?}: {}", disk, e);
266 new_binder_exception(
267 ExceptionCode::SERVICE_SPECIFIC,
268 format!("Failed to make composite image: {}", e),
269 )
270 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000271
272 // Pass the file descriptors for the various partition files to crosvm when it
273 // is run.
274 indirect_files.extend(partition_files);
275
276 image
277 } else if let Some(image) = &disk.image {
278 clone_file(image)?
279 } else {
280 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000281 return Err(new_binder_exception(
282 ExceptionCode::ILLEGAL_ARGUMENT,
283 "DiskImage didn't contain image or partitions.",
284 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000285 };
286
287 Ok(DiskFile { image, writable: disk.writable })
288}
289
Jooyung Han21e9b922021-06-26 04:14:16 +0900290fn load_app_config(
291 config: &VirtualMachineAppConfig,
292 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900293) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900294 let apk_file = config.apk.as_ref().unwrap().as_ref();
295 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
296 let config_path = &config.configPath;
297
Jooyung Han35edb8f2021-07-01 16:17:16 +0900298 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900299 let config_file = apk_zip.by_name(config_path)?;
300 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
301
302 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900303 // For now, the only supported "os" value is "microdroid"
304 if os_name != "microdroid" {
305 bail!("unknown os: {}", os_name);
306 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900307 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
308 let vm_config_file = File::open(vm_config_path)?;
309 let mut vm_config = VmConfig::load(&vm_config_file)?;
310
Jiyong Park23601142021-07-05 13:15:32 +0900311 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900312 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900313 let mut apexes = vm_payload_config.apexes.clone();
314 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900315 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900316 );
317 apexes.dedup_by(|a, b| a.name == b.name);
318
Jooyung Han73bac242021-07-02 10:25:49 +0900319 vm_config.disks.push(make_payload_disk(
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900320 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
321 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
322 config_path,
323 &apexes,
324 temporary_directory,
325 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900326
327 if config.debug {
328 vm_config.disks[1].partitions.push(Partition {
329 label: "bootconfig".to_owned(),
330 paths: vec![PathBuf::from(
331 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
332 )],
333 writable: false,
334 });
335 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900336 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900337
338 vm_config.to_parcelable()
339}
340
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000341/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000342fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000343 temporary_directory: &Path,
344 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000345) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000346 let id = *next_temporary_image_id;
347 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000348 CompositeImageFilenames {
349 composite: temporary_directory.join(format!("composite-{}.img", id)),
350 header: temporary_directory.join(format!("composite-{}-header.img", id)),
351 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
352 }
353}
354
355/// Filenames for a composite disk image, including header and footer partitions.
356#[derive(Clone, Debug, Eq, PartialEq)]
357struct CompositeImageFilenames {
358 /// The composite disk image itself.
359 composite: PathBuf,
360 /// The header partition image.
361 header: PathBuf,
362 /// The footer partition image.
363 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000364}
365
366/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000367fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000368 ThreadState::with_calling_sid(|sid| {
369 if let Some(sid) = sid {
370 match sid.to_str() {
371 Ok(sid) => Ok(sid.to_owned()),
372 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000373 error!("SID was not valid UTF-8: {}", e);
374 Err(new_binder_exception(
375 ExceptionCode::ILLEGAL_ARGUMENT,
376 format!("SID was not valid UTF-8: {}", e),
377 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000378 }
379 }
380 } else {
381 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000382 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000383 }
384 })
385}
386
Andrew Walbran320b5602021-03-04 16:11:12 +0000387/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000388fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000389 let uid = ThreadState::get_calling_uid();
390 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000391 if DEBUG_ALLOWED_UIDS.contains(&uid) {
392 Ok(())
393 } else {
394 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
395 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000396}
397
398/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
399#[derive(Debug)]
400struct VirtualMachine {
401 instance: Arc<VmInstance>,
402}
403
404impl VirtualMachine {
405 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
406 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000407 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000408 }
409}
410
411impl Interface for VirtualMachine {}
412
413impl IVirtualMachine for VirtualMachine {
414 fn getCid(&self) -> binder::Result<i32> {
415 Ok(self.instance.cid as i32)
416 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000417
418 fn isRunning(&self) -> binder::Result<bool> {
419 Ok(self.instance.running())
420 }
421
422 fn registerCallback(
423 &self,
424 callback: &Strong<dyn IVirtualMachineCallback>,
425 ) -> binder::Result<()> {
426 // TODO: Should this give an error if the VM is already dead?
427 self.instance.callbacks.add(callback.clone());
428 Ok(())
429 }
430}
431
432impl Drop for VirtualMachine {
433 fn drop(&mut self) {
434 debug!("Dropping {:?}", self);
435 self.instance.kill();
436 }
437}
438
439/// A set of Binders to be called back in response to various events on the VM, such as when it
440/// dies.
441#[derive(Debug, Default)]
442pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
443
444impl VirtualMachineCallbacks {
445 /// Call all registered callbacks to say that the VM has died.
446 pub fn callback_on_died(&self, cid: Cid) {
447 let callbacks = &*self.0.lock().unwrap();
448 for callback in callbacks {
449 if let Err(e) = callback.onDied(cid as i32) {
450 error!("Error calling callback: {}", e);
451 }
452 }
453 }
454
455 /// Add a new callback to the set.
456 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
457 self.0.lock().unwrap().push(callback);
458 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000459}
460
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000461/// The mutable state of the VirtualizationService. There should only be one instance of this
462/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000463#[derive(Debug)]
464struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000465 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000466 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000467
468 /// The VMs which have been started. When VMs are started a weak reference is added to this list
469 /// while a strong reference is returned to the caller over Binder. Once all copies of the
470 /// Binder client are dropped the weak reference here will become invalid, and will be removed
471 /// from the list opportunistically the next time `add_vm` is called.
472 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000473
474 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
475 /// This is only used for debugging purposes.
476 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000477}
478
479impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000480 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000481 fn vms(&self) -> Vec<Arc<VmInstance>> {
482 // Attempt to upgrade the weak pointers to strong pointers.
483 self.vms.iter().filter_map(Weak::upgrade).collect()
484 }
485
486 /// Add a new VM to the list.
487 fn add_vm(&mut self, vm: Weak<VmInstance>) {
488 // Garbage collect any entries from the stored list which no longer exist.
489 self.vms.retain(|vm| vm.strong_count() > 0);
490
491 // Actually add the new VM.
492 self.vms.push(vm);
493 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000494
495 /// Store a strong VM reference.
496 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
497 self.debug_held_vms.push(vm);
498 }
499
500 /// Retrieve and remove a strong VM reference.
501 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
502 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
503 Some(self.debug_held_vms.swap_remove(pos))
504 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000505
506 /// Get the next available CID, or an error if we have run out.
507 fn allocate_cid(&mut self) -> binder::Result<Cid> {
508 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
509 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000510 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000511 Ok(cid)
512 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000513}
514
515impl Default for State {
516 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000517 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000518 }
519}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000520
521/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
522fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
523 option.as_ref().map(|t| t.as_ref())
524}
525
526/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000527fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
528 file.as_ref().try_clone().map_err(|e| {
529 new_binder_exception(
530 ExceptionCode::BAD_PARCELABLE,
531 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
532 )
533 })
534}
535
536/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
537fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
538 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000539}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900540
541/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
542/// it doesn't require that T implements Clone.
543enum BorrowedOrOwned<'a, T> {
544 Borrowed(&'a T),
545 Owned(T),
546}
547
548impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
549 fn as_ref(&self) -> &T {
550 match self {
551 Self::Borrowed(b) => b,
552 Self::Owned(o) => &o,
553 }
554 }
555}