blob: c0b2e1128b127e55963916e9ae64dc2eefe0839f [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};
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?
62const MICRODROID_REQUIRED_APEXES: [&str; 4] =
63 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd", "com.android.sdkext"];
64
Andrew Walbranf6bf6862021-05-21 12:41:13 +000065/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han73bac242021-07-02 10:25:49 +090066#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000067pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000068 state: Mutex<State>,
Jooyung Han73bac242021-07-02 10:25:49 +090069 apex_info_list: ApexInfoList,
70}
71
72impl VirtualizationService {
73 pub fn new() -> Result<VirtualizationService> {
74 Ok(VirtualizationService {
75 state: Default::default(),
76 apex_info_list: ApexInfoList::load()?,
77 })
78 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000079}
80
Andrew Walbranf6bf6862021-05-21 12:41:13 +000081impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000082
Andrew Walbranf6bf6862021-05-21 12:41:13 +000083impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000084 /// Create and start a new VM with the given configuration, assigning it the next available CID.
85 ///
86 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000087 fn startVm(
88 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000089 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000090 log_fd: Option<&ParcelFileDescriptor>,
91 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000092 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000094 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000095 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000096 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000097 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098
99 // Counter to generate unique IDs for temporary image files.
100 let mut next_temporary_image_id = 0;
101 // Files which are referred to from composite images. These must be mapped to the crosvm
102 // child process, and not closed before it is started.
103 let mut indirect_files = vec![];
104
105 // Make directory for temporary files.
106 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
107 create_dir(&temporary_directory).map_err(|e| {
108 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000109 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000110 temporary_directory, e
111 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000112 new_binder_exception(
113 ExceptionCode::SERVICE_SPECIFIC,
114 format!(
115 "Failed to create temporary directory {:?} for VM files: {}",
116 temporary_directory, e
117 ),
118 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119 })?;
120
Jooyung Han21e9b922021-06-26 04:14:16 +0900121 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900122 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han73bac242021-07-02 10:25:49 +0900123 load_app_config(&self.apex_info_list, config, &temporary_directory).map_err(
124 |e| {
125 error!("Failed to load app config from {}: {}", &config.configPath, e);
126 new_binder_exception(
127 ExceptionCode::SERVICE_SPECIFIC,
128 format!("Failed to load app config from {}: {}", &config.configPath, e),
129 )
130 },
131 )?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900132 ),
133 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900134 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900135 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900136
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000137 // Assemble disk images if needed.
138 let disks = config
139 .disks
140 .iter()
141 .map(|disk| {
142 assemble_disk_image(
143 disk,
144 &temporary_directory,
145 &mut next_temporary_image_id,
146 &mut indirect_files,
147 )
148 })
149 .collect::<Result<Vec<DiskFile>, _>>()?;
150
151 // Actually start the VM.
152 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000153 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000154 bootloader: as_asref(&config.bootloader),
155 kernel: as_asref(&config.kernel),
156 initrd: as_asref(&config.initrd),
157 disks,
158 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000159 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000160 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000161 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000162 let composite_disk_fds: Vec<_> =
163 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 let instance = VmInstance::start(
165 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000166 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000167 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000168 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000169 requester_uid,
170 requester_sid,
171 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000172 )
173 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000174 error!("Failed to start VM with config {:?}: {}", config, e);
175 new_binder_exception(
176 ExceptionCode::SERVICE_SPECIFIC,
177 format!("Failed to start VM: {}", e),
178 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000179 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000180 state.add_vm(Arc::downgrade(&instance));
181 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000182 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000183
Andrew Walbrandff3b942021-06-09 15:20:36 +0000184 /// Initialise an empty partition image of the given size to be used as a writable partition.
185 fn initializeWritablePartition(
186 &self,
187 image_fd: &ParcelFileDescriptor,
188 size: i64,
189 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000190 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000191 new_binder_exception(
192 ExceptionCode::ILLEGAL_ARGUMENT,
193 format!("Invalid size {}: {}", size, e),
194 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000195 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000196 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000197
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000198 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000199 new_binder_exception(
200 ExceptionCode::SERVICE_SPECIFIC,
201 format!("Failed to create QCOW2 image: {}", e),
202 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000203 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000204
205 Ok(())
206 }
207
Andrew Walbran320b5602021-03-04 16:11:12 +0000208 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
209 /// and as such is only permitted from the shell user.
210 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000211 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000212
213 let state = &mut *self.state.lock().unwrap();
214 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000215 let cids = vms
216 .into_iter()
217 .map(|vm| VirtualMachineDebugInfo {
218 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000219 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000220 requesterUid: vm.requester_uid as i32,
221 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000222 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000223 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000224 })
225 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000226 Ok(cids)
227 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000228
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000229 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
230 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000231 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000232 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000233
David Brazdil3c2ddef2021-03-18 13:09:57 +0000234 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000235 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000236 Ok(())
237 }
238
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000239 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
240 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
241 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000243 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000244
245 let state = &mut *self.state.lock().unwrap();
246 Ok(state.debug_drop_vm(cid))
247 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000248}
249
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000250/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
251///
252/// This may involve assembling a composite disk from a set of partition images.
253fn assemble_disk_image(
254 disk: &DiskImage,
255 temporary_directory: &Path,
256 next_temporary_image_id: &mut u64,
257 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000258) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000259 let image = if !disk.partitions.is_empty() {
260 if disk.image.is_some() {
261 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000262 return Err(new_binder_exception(
263 ExceptionCode::ILLEGAL_ARGUMENT,
264 "DiskImage contains both image and partitions.",
265 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000266 }
267
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000268 let composite_image_filenames =
269 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
270 let (image, partition_files) = make_composite_image(
271 &disk.partitions,
272 &composite_image_filenames.composite,
273 &composite_image_filenames.header,
274 &composite_image_filenames.footer,
275 )
276 .map_err(|e| {
277 error!("Failed to make composite image with config {:?}: {}", disk, e);
278 new_binder_exception(
279 ExceptionCode::SERVICE_SPECIFIC,
280 format!("Failed to make composite image: {}", e),
281 )
282 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000283
284 // Pass the file descriptors for the various partition files to crosvm when it
285 // is run.
286 indirect_files.extend(partition_files);
287
288 image
289 } else if let Some(image) = &disk.image {
290 clone_file(image)?
291 } else {
292 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000293 return Err(new_binder_exception(
294 ExceptionCode::ILLEGAL_ARGUMENT,
295 "DiskImage didn't contain image or partitions.",
296 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000297 };
298
299 Ok(DiskFile { image, writable: disk.writable })
300}
301
Jooyung Han21e9b922021-06-26 04:14:16 +0900302fn load_app_config(
Jooyung Han73bac242021-07-02 10:25:49 +0900303 apex_info_list: &ApexInfoList,
Jooyung Han21e9b922021-06-26 04:14:16 +0900304 config: &VirtualMachineAppConfig,
305 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900306) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900307 let apk_file = config.apk.as_ref().unwrap().as_ref();
308 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
309 let config_path = &config.configPath;
310
Jooyung Han35edb8f2021-07-01 16:17:16 +0900311 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900312 let config_file = apk_zip.by_name(config_path)?;
313 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
314
315 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900316 // For now, the only supported "os" value is "microdroid"
317 if os_name != "microdroid" {
318 bail!("unknown os: {}", os_name);
319 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900320 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
321 let vm_config_file = File::open(vm_config_path)?;
322 let mut vm_config = VmConfig::load(&vm_config_file)?;
323
Jiyong Park23601142021-07-05 13:15:32 +0900324 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900325 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900326 let mut apexes = vm_payload_config.apexes.clone();
327 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900328 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900329 );
330 apexes.dedup_by(|a, b| a.name == b.name);
331
Jooyung Han73bac242021-07-02 10:25:49 +0900332 vm_config.disks.push(make_payload_disk(
333 apex_info_list,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900334 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
335 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
336 config_path,
337 &apexes,
338 temporary_directory,
339 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900340
341 if config.debug {
342 vm_config.disks[1].partitions.push(Partition {
343 label: "bootconfig".to_owned(),
344 paths: vec![PathBuf::from(
345 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
346 )],
347 writable: false,
348 });
349 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900350 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900351
352 vm_config.to_parcelable()
353}
354
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000355/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000356fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000357 temporary_directory: &Path,
358 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000359) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000360 let id = *next_temporary_image_id;
361 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000362 CompositeImageFilenames {
363 composite: temporary_directory.join(format!("composite-{}.img", id)),
364 header: temporary_directory.join(format!("composite-{}-header.img", id)),
365 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
366 }
367}
368
369/// Filenames for a composite disk image, including header and footer partitions.
370#[derive(Clone, Debug, Eq, PartialEq)]
371struct CompositeImageFilenames {
372 /// The composite disk image itself.
373 composite: PathBuf,
374 /// The header partition image.
375 header: PathBuf,
376 /// The footer partition image.
377 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000378}
379
380/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000381fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000382 ThreadState::with_calling_sid(|sid| {
383 if let Some(sid) = sid {
384 match sid.to_str() {
385 Ok(sid) => Ok(sid.to_owned()),
386 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000387 error!("SID was not valid UTF-8: {}", e);
388 Err(new_binder_exception(
389 ExceptionCode::ILLEGAL_ARGUMENT,
390 format!("SID was not valid UTF-8: {}", e),
391 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392 }
393 }
394 } else {
395 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000396 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000397 }
398 })
399}
400
Andrew Walbran320b5602021-03-04 16:11:12 +0000401/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000402fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000403 let uid = ThreadState::get_calling_uid();
404 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000405 if DEBUG_ALLOWED_UIDS.contains(&uid) {
406 Ok(())
407 } else {
408 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
409 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000410}
411
412/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
413#[derive(Debug)]
414struct VirtualMachine {
415 instance: Arc<VmInstance>,
416}
417
418impl VirtualMachine {
419 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
420 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000421 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000422 }
423}
424
425impl Interface for VirtualMachine {}
426
427impl IVirtualMachine for VirtualMachine {
428 fn getCid(&self) -> binder::Result<i32> {
429 Ok(self.instance.cid as i32)
430 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000431
432 fn isRunning(&self) -> binder::Result<bool> {
433 Ok(self.instance.running())
434 }
435
436 fn registerCallback(
437 &self,
438 callback: &Strong<dyn IVirtualMachineCallback>,
439 ) -> binder::Result<()> {
440 // TODO: Should this give an error if the VM is already dead?
441 self.instance.callbacks.add(callback.clone());
442 Ok(())
443 }
444}
445
446impl Drop for VirtualMachine {
447 fn drop(&mut self) {
448 debug!("Dropping {:?}", self);
449 self.instance.kill();
450 }
451}
452
453/// A set of Binders to be called back in response to various events on the VM, such as when it
454/// dies.
455#[derive(Debug, Default)]
456pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
457
458impl VirtualMachineCallbacks {
459 /// Call all registered callbacks to say that the VM has died.
460 pub fn callback_on_died(&self, cid: Cid) {
461 let callbacks = &*self.0.lock().unwrap();
462 for callback in callbacks {
463 if let Err(e) = callback.onDied(cid as i32) {
464 error!("Error calling callback: {}", e);
465 }
466 }
467 }
468
469 /// Add a new callback to the set.
470 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
471 self.0.lock().unwrap().push(callback);
472 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000473}
474
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000475/// The mutable state of the VirtualizationService. There should only be one instance of this
476/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000477#[derive(Debug)]
478struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000479 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000480 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000481
482 /// The VMs which have been started. When VMs are started a weak reference is added to this list
483 /// while a strong reference is returned to the caller over Binder. Once all copies of the
484 /// Binder client are dropped the weak reference here will become invalid, and will be removed
485 /// from the list opportunistically the next time `add_vm` is called.
486 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000487
488 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
489 /// This is only used for debugging purposes.
490 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000491}
492
493impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000494 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000495 fn vms(&self) -> Vec<Arc<VmInstance>> {
496 // Attempt to upgrade the weak pointers to strong pointers.
497 self.vms.iter().filter_map(Weak::upgrade).collect()
498 }
499
500 /// Add a new VM to the list.
501 fn add_vm(&mut self, vm: Weak<VmInstance>) {
502 // Garbage collect any entries from the stored list which no longer exist.
503 self.vms.retain(|vm| vm.strong_count() > 0);
504
505 // Actually add the new VM.
506 self.vms.push(vm);
507 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000508
509 /// Store a strong VM reference.
510 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
511 self.debug_held_vms.push(vm);
512 }
513
514 /// Retrieve and remove a strong VM reference.
515 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
516 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
517 Some(self.debug_held_vms.swap_remove(pos))
518 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000519
520 /// Get the next available CID, or an error if we have run out.
521 fn allocate_cid(&mut self) -> binder::Result<Cid> {
522 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
523 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000524 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000525 Ok(cid)
526 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000527}
528
529impl Default for State {
530 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000531 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000532 }
533}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000534
535/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
536fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
537 option.as_ref().map(|t| t.as_ref())
538}
539
540/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000541fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
542 file.as_ref().try_clone().map_err(|e| {
543 new_binder_exception(
544 ExceptionCode::BAD_PARCELABLE,
545 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
546 )
547 })
548}
549
550/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
551fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
552 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000553}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900554
555/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
556/// it doesn't require that T implements Clone.
557enum BorrowedOrOwned<'a, T> {
558 Borrowed(&'a T),
559 Owned(T),
560}
561
562impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
563 fn as_ref(&self) -> &T {
564 match self {
565 Self::Borrowed(b) => b,
566 Self::Owned(o) => &o,
567 }
568 }
569}