blob: dc22e99bba7822a68ff0754d53243d0a844c0e12 [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 Han73bac242021-07-02 10:25:49 +090019use crate::payload::{make_payload_disk, ApexInfoList};
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};
44use std::os::unix::io::AsRawFd;
45use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000046use std::sync::{Arc, Mutex, Weak};
Jiyong Park23601142021-07-05 13:15:32 +090047use vmconfig::{VmConfig, Partition};
Jooyung Han35edb8f2021-07-01 16:17:16 +090048use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000049
Andrew Walbranf6bf6862021-05-21 12:41:13 +000050pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000052/// Directory in which to write disk image files used while running VMs.
53const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
54
Andrew Walbran320b5602021-03-04 16:11:12 +000055// TODO(qwandor): Use PermissionController once it is available to Rust.
56/// Only processes running with one of these UIDs are allowed to call debug methods.
57const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
58
Jooyung Han35edb8f2021-07-01 16:17:16 +090059/// The list of APEXes which microdroid requires.
60/// TODO(b/192200378) move this to microdroid.json?
61const MICRODROID_REQUIRED_APEXES: [&str; 4] =
62 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd", "com.android.sdkext"];
63
Andrew Walbranf6bf6862021-05-21 12:41:13 +000064/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han73bac242021-07-02 10:25:49 +090065#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000066pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000067 state: Mutex<State>,
Jooyung Han73bac242021-07-02 10:25:49 +090068 apex_info_list: ApexInfoList,
69}
70
71impl VirtualizationService {
72 pub fn new() -> Result<VirtualizationService> {
73 Ok(VirtualizationService {
74 state: Default::default(),
75 apex_info_list: ApexInfoList::load()?,
76 })
77 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000078}
79
Andrew Walbranf6bf6862021-05-21 12:41:13 +000080impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000081
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000083 /// Create and start a new VM with the given configuration, assigning it the next available CID.
84 ///
85 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000086 fn startVm(
87 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000088 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000089 log_fd: Option<&ParcelFileDescriptor>,
90 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000091 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000092 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000093 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000094 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000095 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000096 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000097
98 // Counter to generate unique IDs for temporary image files.
99 let mut next_temporary_image_id = 0;
100 // Files which are referred to from composite images. These must be mapped to the crosvm
101 // child process, and not closed before it is started.
102 let mut indirect_files = vec![];
103
104 // Make directory for temporary files.
105 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
106 create_dir(&temporary_directory).map_err(|e| {
107 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000108 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109 temporary_directory, e
110 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000111 new_binder_exception(
112 ExceptionCode::SERVICE_SPECIFIC,
113 format!(
114 "Failed to create temporary directory {:?} for VM files: {}",
115 temporary_directory, e
116 ),
117 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000118 })?;
119
Jooyung Han21e9b922021-06-26 04:14:16 +0900120 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900121 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han73bac242021-07-02 10:25:49 +0900122 load_app_config(&self.apex_info_list, config, &temporary_directory).map_err(
123 |e| {
124 error!("Failed to load app config from {}: {}", &config.configPath, e);
125 new_binder_exception(
126 ExceptionCode::SERVICE_SPECIFIC,
127 format!("Failed to load app config from {}: {}", &config.configPath, e),
128 )
129 },
130 )?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900131 ),
132 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900133 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900134 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900135
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000136 // Assemble disk images if needed.
137 let disks = config
138 .disks
139 .iter()
140 .map(|disk| {
141 assemble_disk_image(
142 disk,
143 &temporary_directory,
144 &mut next_temporary_image_id,
145 &mut indirect_files,
146 )
147 })
148 .collect::<Result<Vec<DiskFile>, _>>()?;
149
150 // Actually start the VM.
151 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000152 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000153 bootloader: as_asref(&config.bootloader),
154 kernel: as_asref(&config.kernel),
155 initrd: as_asref(&config.initrd),
156 disks,
157 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000158 protected: config.protected_vm,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000159 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000160 let composite_disk_fds: Vec<_> =
161 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000162 let instance = VmInstance::start(
163 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000164 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000165 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000166 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000167 requester_uid,
168 requester_sid,
169 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000170 )
171 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000172 error!("Failed to start VM with config {:?}: {}", config, e);
173 new_binder_exception(
174 ExceptionCode::SERVICE_SPECIFIC,
175 format!("Failed to start VM: {}", e),
176 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000177 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000178 state.add_vm(Arc::downgrade(&instance));
179 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000180 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000181
Andrew Walbrandff3b942021-06-09 15:20:36 +0000182 /// Initialise an empty partition image of the given size to be used as a writable partition.
183 fn initializeWritablePartition(
184 &self,
185 image_fd: &ParcelFileDescriptor,
186 size: i64,
187 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000188 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000189 new_binder_exception(
190 ExceptionCode::ILLEGAL_ARGUMENT,
191 format!("Invalid size {}: {}", size, e),
192 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000193 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000194 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000195
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000196 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000197 new_binder_exception(
198 ExceptionCode::SERVICE_SPECIFIC,
199 format!("Failed to create QCOW2 image: {}", e),
200 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000201 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000202
203 Ok(())
204 }
205
Andrew Walbran320b5602021-03-04 16:11:12 +0000206 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
207 /// and as such is only permitted from the shell user.
208 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000209 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000210
211 let state = &mut *self.state.lock().unwrap();
212 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000213 let cids = vms
214 .into_iter()
215 .map(|vm| VirtualMachineDebugInfo {
216 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000217 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000218 requesterUid: vm.requester_uid as i32,
219 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000220 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000221 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000222 })
223 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000224 Ok(cids)
225 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000226
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000227 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
228 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000229 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000230 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000231
David Brazdil3c2ddef2021-03-18 13:09:57 +0000232 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000233 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000234 Ok(())
235 }
236
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000237 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
238 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
239 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000240 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000241 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242
243 let state = &mut *self.state.lock().unwrap();
244 Ok(state.debug_drop_vm(cid))
245 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000246}
247
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000248/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
249///
250/// This may involve assembling a composite disk from a set of partition images.
251fn assemble_disk_image(
252 disk: &DiskImage,
253 temporary_directory: &Path,
254 next_temporary_image_id: &mut u64,
255 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000256) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000257 let image = if !disk.partitions.is_empty() {
258 if disk.image.is_some() {
259 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000260 return Err(new_binder_exception(
261 ExceptionCode::ILLEGAL_ARGUMENT,
262 "DiskImage contains both image and partitions.",
263 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000264 }
265
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000266 let composite_image_filenames =
267 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
268 let (image, partition_files) = make_composite_image(
269 &disk.partitions,
270 &composite_image_filenames.composite,
271 &composite_image_filenames.header,
272 &composite_image_filenames.footer,
273 )
274 .map_err(|e| {
275 error!("Failed to make composite image with config {:?}: {}", disk, e);
276 new_binder_exception(
277 ExceptionCode::SERVICE_SPECIFIC,
278 format!("Failed to make composite image: {}", e),
279 )
280 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000281
282 // Pass the file descriptors for the various partition files to crosvm when it
283 // is run.
284 indirect_files.extend(partition_files);
285
286 image
287 } else if let Some(image) = &disk.image {
288 clone_file(image)?
289 } else {
290 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000291 return Err(new_binder_exception(
292 ExceptionCode::ILLEGAL_ARGUMENT,
293 "DiskImage didn't contain image or partitions.",
294 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000295 };
296
297 Ok(DiskFile { image, writable: disk.writable })
298}
299
Jooyung Han21e9b922021-06-26 04:14:16 +0900300fn load_app_config(
Jooyung Han73bac242021-07-02 10:25:49 +0900301 apex_info_list: &ApexInfoList,
Jooyung Han21e9b922021-06-26 04:14:16 +0900302 config: &VirtualMachineAppConfig,
303 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900304) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900305 let apk_file = config.apk.as_ref().unwrap().as_ref();
306 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
307 let config_path = &config.configPath;
308
Jooyung Han35edb8f2021-07-01 16:17:16 +0900309 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900310 let config_file = apk_zip.by_name(config_path)?;
311 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
312
313 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900314 // For now, the only supported "os" value is "microdroid"
315 if os_name != "microdroid" {
316 bail!("unknown os: {}", os_name);
317 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900318 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
319 let vm_config_file = File::open(vm_config_path)?;
320 let mut vm_config = VmConfig::load(&vm_config_file)?;
321
Jiyong Park23601142021-07-05 13:15:32 +0900322 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900323 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900324 let mut apexes = vm_payload_config.apexes.clone();
325 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900326 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900327 );
328 apexes.dedup_by(|a, b| a.name == b.name);
329
Jooyung Han73bac242021-07-02 10:25:49 +0900330 vm_config.disks.push(make_payload_disk(
331 apex_info_list,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900332 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
333 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
334 config_path,
335 &apexes,
336 temporary_directory,
337 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900338
339 if config.debug {
340 vm_config.disks[1].partitions.push(Partition {
341 label: "bootconfig".to_owned(),
342 paths: vec![PathBuf::from(
343 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
344 )],
345 writable: false,
346 });
347 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900348 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900349
350 vm_config.to_parcelable()
351}
352
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000353/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000354fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000355 temporary_directory: &Path,
356 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000357) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000358 let id = *next_temporary_image_id;
359 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000360 CompositeImageFilenames {
361 composite: temporary_directory.join(format!("composite-{}.img", id)),
362 header: temporary_directory.join(format!("composite-{}-header.img", id)),
363 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
364 }
365}
366
367/// Filenames for a composite disk image, including header and footer partitions.
368#[derive(Clone, Debug, Eq, PartialEq)]
369struct CompositeImageFilenames {
370 /// The composite disk image itself.
371 composite: PathBuf,
372 /// The header partition image.
373 header: PathBuf,
374 /// The footer partition image.
375 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000376}
377
378/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000379fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000380 ThreadState::with_calling_sid(|sid| {
381 if let Some(sid) = sid {
382 match sid.to_str() {
383 Ok(sid) => Ok(sid.to_owned()),
384 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000385 error!("SID was not valid UTF-8: {}", e);
386 Err(new_binder_exception(
387 ExceptionCode::ILLEGAL_ARGUMENT,
388 format!("SID was not valid UTF-8: {}", e),
389 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000390 }
391 }
392 } else {
393 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000394 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000395 }
396 })
397}
398
Andrew Walbran320b5602021-03-04 16:11:12 +0000399/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000400fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000401 let uid = ThreadState::get_calling_uid();
402 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000403 if DEBUG_ALLOWED_UIDS.contains(&uid) {
404 Ok(())
405 } else {
406 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
407 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000408}
409
410/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
411#[derive(Debug)]
412struct VirtualMachine {
413 instance: Arc<VmInstance>,
414}
415
416impl VirtualMachine {
417 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
418 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000419 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000420 }
421}
422
423impl Interface for VirtualMachine {}
424
425impl IVirtualMachine for VirtualMachine {
426 fn getCid(&self) -> binder::Result<i32> {
427 Ok(self.instance.cid as i32)
428 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000429
430 fn isRunning(&self) -> binder::Result<bool> {
431 Ok(self.instance.running())
432 }
433
434 fn registerCallback(
435 &self,
436 callback: &Strong<dyn IVirtualMachineCallback>,
437 ) -> binder::Result<()> {
438 // TODO: Should this give an error if the VM is already dead?
439 self.instance.callbacks.add(callback.clone());
440 Ok(())
441 }
442}
443
444impl Drop for VirtualMachine {
445 fn drop(&mut self) {
446 debug!("Dropping {:?}", self);
447 self.instance.kill();
448 }
449}
450
451/// A set of Binders to be called back in response to various events on the VM, such as when it
452/// dies.
453#[derive(Debug, Default)]
454pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
455
456impl VirtualMachineCallbacks {
457 /// Call all registered callbacks to say that the VM has died.
458 pub fn callback_on_died(&self, cid: Cid) {
459 let callbacks = &*self.0.lock().unwrap();
460 for callback in callbacks {
461 if let Err(e) = callback.onDied(cid as i32) {
462 error!("Error calling callback: {}", e);
463 }
464 }
465 }
466
467 /// Add a new callback to the set.
468 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
469 self.0.lock().unwrap().push(callback);
470 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000471}
472
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000473/// The mutable state of the VirtualizationService. There should only be one instance of this
474/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000475#[derive(Debug)]
476struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000477 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000478 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000479
480 /// The VMs which have been started. When VMs are started a weak reference is added to this list
481 /// while a strong reference is returned to the caller over Binder. Once all copies of the
482 /// Binder client are dropped the weak reference here will become invalid, and will be removed
483 /// from the list opportunistically the next time `add_vm` is called.
484 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000485
486 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
487 /// This is only used for debugging purposes.
488 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000489}
490
491impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000492 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000493 fn vms(&self) -> Vec<Arc<VmInstance>> {
494 // Attempt to upgrade the weak pointers to strong pointers.
495 self.vms.iter().filter_map(Weak::upgrade).collect()
496 }
497
498 /// Add a new VM to the list.
499 fn add_vm(&mut self, vm: Weak<VmInstance>) {
500 // Garbage collect any entries from the stored list which no longer exist.
501 self.vms.retain(|vm| vm.strong_count() > 0);
502
503 // Actually add the new VM.
504 self.vms.push(vm);
505 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000506
507 /// Store a strong VM reference.
508 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
509 self.debug_held_vms.push(vm);
510 }
511
512 /// Retrieve and remove a strong VM reference.
513 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
514 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
515 Some(self.debug_held_vms.swap_remove(pos))
516 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000517
518 /// Get the next available CID, or an error if we have run out.
519 fn allocate_cid(&mut self) -> binder::Result<Cid> {
520 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
521 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000522 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000523 Ok(cid)
524 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000525}
526
527impl Default for State {
528 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000529 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000530 }
531}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000532
533/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
534fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
535 option.as_ref().map(|t| t.as_ref())
536}
537
538/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000539fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
540 file.as_ref().try_clone().map_err(|e| {
541 new_binder_exception(
542 ExceptionCode::BAD_PARCELABLE,
543 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
544 )
545 })
546}
547
548/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
549fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
550 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000551}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900552
553/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
554/// it doesn't require that T implements Clone.
555enum BorrowedOrOwned<'a, T> {
556 Borrowed(&'a T),
557 Owned(T),
558}
559
560impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
561 fn as_ref(&self) -> &T {
562 match self {
563 Self::Borrowed(b) => b,
564 Self::Owned(o) => &o,
565 }
566 }
567}