Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // 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 Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 15 | //! Implementation of the AIDL interface of the VirtualizationService. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 16 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 17 | use crate::composite::make_composite_image; |
| 18 | use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 19 | use crate::payload::add_microdroid_images; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 20 | use crate::{Cid, FIRST_GUEST_CID}; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 21 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 22 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 23 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 24 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 25 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{ |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 26 | BnVirtualMachine, IVirtualMachine, |
| 27 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 28 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 29 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
| 30 | VirtualMachineAppConfig::VirtualMachineAppConfig, |
| 31 | VirtualMachineConfig::VirtualMachineConfig, |
| 32 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
| 33 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 34 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
| 35 | use android_system_virtualizationservice::binder::{ |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 36 | self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 37 | }; |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 38 | use anyhow::{bail, Context, Result}; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 39 | use disk::QcowFile; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 40 | use log::{debug, error, warn, info}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 41 | use microdroid_payload_config::VmPayloadConfig; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 42 | use std::convert::TryInto; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 43 | use std::ffi::CString; |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 44 | use std::fs::{File, OpenOptions, create_dir}; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 45 | use std::num::NonZeroU32; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 46 | use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 47 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 48 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 49 | use vmconfig::VmConfig; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 50 | use vsock::{VsockListener, SockAddr, VsockStream}; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 51 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 52 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 53 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 54 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 55 | /// Directory in which to write disk image files used while running VMs. |
Andrew Walbran | 488bd07 | 2021-07-14 13:29:51 +0000 | [diff] [blame] | 56 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 57 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 58 | /// The CID representing the host VM |
| 59 | const VMADDR_CID_HOST: u32 = 2; |
| 60 | |
| 61 | /// Port number that virtualizationservice listens on connections from the guest VMs for the |
| 62 | /// payload output |
| 63 | const PORT_VIRT_SERVICE: u32 = 3000; |
| 64 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 65 | /// The size of zero.img. |
| 66 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 67 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 68 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 69 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame] | 70 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 71 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 72 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 73 | } |
| 74 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 75 | impl Interface for VirtualizationService {} |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 76 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 77 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 78 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 79 | /// |
| 80 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 81 | fn startVm( |
| 82 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 83 | config: &VirtualMachineConfig, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 84 | log_fd: Option<&ParcelFileDescriptor>, |
| 85 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 86 | check_manage_access()?; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 87 | let state = &mut *self.state.lock().unwrap(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 88 | let log_fd = log_fd.map(clone_file).transpose()?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 89 | let requester_uid = ThreadState::get_calling_uid(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 90 | let requester_sid = get_calling_sid()?; |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 91 | let requester_debug_pid = ThreadState::get_calling_pid(); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 92 | let cid = state.allocate_cid()?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 93 | |
| 94 | // Counter to generate unique IDs for temporary image files. |
| 95 | let mut next_temporary_image_id = 0; |
| 96 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 97 | // child process, and not closed before it is started. |
| 98 | let mut indirect_files = vec![]; |
| 99 | |
| 100 | // Make directory for temporary files. |
| 101 | let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 102 | create_dir(&temporary_directory).map_err(|e| { |
| 103 | error!( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 104 | "Failed to create temporary directory {:?} for VM files: {}", |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 105 | temporary_directory, e |
| 106 | ); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 107 | new_binder_exception( |
| 108 | ExceptionCode::SERVICE_SPECIFIC, |
| 109 | format!( |
| 110 | "Failed to create temporary directory {:?} for VM files: {}", |
| 111 | temporary_directory, e |
| 112 | ), |
| 113 | ) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 114 | })?; |
| 115 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 116 | let config = match config { |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 117 | VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned( |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame] | 118 | load_app_config(config, &temporary_directory).map_err(|e| { |
| 119 | error!("Failed to load app config from {}: {}", &config.configPath, e); |
| 120 | new_binder_exception( |
| 121 | ExceptionCode::SERVICE_SPECIFIC, |
| 122 | format!("Failed to load app config from {}: {}", &config.configPath, e), |
| 123 | ) |
| 124 | })?, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 125 | ), |
| 126 | VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config), |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 127 | }; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 128 | let config = config.as_ref(); |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 129 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 130 | let zero_filler_path = temporary_directory.join("zero.img"); |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame^] | 131 | write_zero_filler(&zero_filler_path).map_err(|e| { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 132 | error!("Failed to make composite image: {}", e); |
| 133 | new_binder_exception( |
| 134 | ExceptionCode::SERVICE_SPECIFIC, |
| 135 | format!("Failed to make composite image: {}", e), |
| 136 | ) |
| 137 | })?; |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 138 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 139 | // Assemble disk images if needed. |
| 140 | let disks = config |
| 141 | .disks |
| 142 | .iter() |
| 143 | .map(|disk| { |
| 144 | assemble_disk_image( |
| 145 | disk, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 146 | &zero_filler_path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 147 | &temporary_directory, |
| 148 | &mut next_temporary_image_id, |
| 149 | &mut indirect_files, |
| 150 | ) |
| 151 | }) |
| 152 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 153 | |
| 154 | // Actually start the VM. |
| 155 | let crosvm_config = CrosvmConfig { |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 156 | cid, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 157 | bootloader: as_asref(&config.bootloader), |
| 158 | kernel: as_asref(&config.kernel), |
| 159 | initrd: as_asref(&config.initrd), |
| 160 | disks, |
| 161 | params: config.params.to_owned(), |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 162 | protected: config.protectedVm, |
| 163 | memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new), |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 164 | }; |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 165 | let composite_disk_fds: Vec<_> = |
| 166 | indirect_files.iter().map(|file| file.as_raw_fd()).collect(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 167 | let instance = VmInstance::start( |
| 168 | &crosvm_config, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 169 | log_fd, |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 170 | &composite_disk_fds, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 171 | temporary_directory, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 172 | requester_uid, |
| 173 | requester_sid, |
| 174 | requester_debug_pid, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 175 | ) |
| 176 | .map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 177 | error!("Failed to start VM with config {:?}: {}", config, e); |
| 178 | new_binder_exception( |
| 179 | ExceptionCode::SERVICE_SPECIFIC, |
| 180 | format!("Failed to start VM: {}", e), |
| 181 | ) |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 182 | })?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 183 | state.add_vm(Arc::downgrade(&instance)); |
| 184 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 185 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 186 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 187 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 188 | fn initializeWritablePartition( |
| 189 | &self, |
| 190 | image_fd: &ParcelFileDescriptor, |
| 191 | size: i64, |
| 192 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 193 | check_manage_access()?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 194 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 195 | new_binder_exception( |
| 196 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 197 | format!("Invalid size {}: {}", size, e), |
| 198 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 199 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 200 | let image = clone_file(image_fd)?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 201 | |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 202 | QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 203 | new_binder_exception( |
| 204 | ExceptionCode::SERVICE_SPECIFIC, |
| 205 | format!("Failed to create QCOW2 image: {}", e), |
| 206 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 207 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 208 | |
| 209 | Ok(()) |
| 210 | } |
| 211 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 212 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 213 | /// and as such is only permitted from the shell user. |
| 214 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 215 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 216 | |
| 217 | let state = &mut *self.state.lock().unwrap(); |
| 218 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 219 | let cids = vms |
| 220 | .into_iter() |
| 221 | .map(|vm| VirtualMachineDebugInfo { |
| 222 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 223 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 224 | requesterUid: vm.requester_uid as i32, |
| 225 | requesterSid: vm.requester_sid.clone(), |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 226 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 227 | running: vm.running(), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 228 | }) |
| 229 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 230 | Ok(cids) |
| 231 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 232 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 233 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 234 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 235 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 236 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 237 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 238 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 239 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 240 | Ok(()) |
| 241 | } |
| 242 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 243 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 244 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 245 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 246 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 247 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 248 | |
| 249 | let state = &mut *self.state.lock().unwrap(); |
| 250 | Ok(state.debug_drop_vm(cid)) |
| 251 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 252 | } |
| 253 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 254 | impl VirtualizationService { |
| 255 | pub fn init() -> VirtualizationService { |
| 256 | let service = VirtualizationService::default(); |
| 257 | let state = service.state.clone(); // reference to state (not the state itself) is copied |
| 258 | std::thread::spawn(move || { |
| 259 | handle_connection_from_vm(state).unwrap(); |
| 260 | }); |
| 261 | service |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// Waits for incoming connections from VM. If a new connection is made, notify the event to the |
| 266 | /// client via the callback (if registered). |
| 267 | fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> { |
| 268 | let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?; |
| 269 | for stream in listener.incoming() { |
| 270 | let stream = match stream { |
| 271 | Err(e) => { |
| 272 | warn!("invalid incoming connection: {}", e); |
| 273 | continue; |
| 274 | } |
| 275 | Ok(s) => s, |
| 276 | }; |
| 277 | if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() { |
| 278 | let cid = addr.cid(); |
| 279 | let port = addr.port(); |
| 280 | info!("connected from cid={}, port={}", cid, port); |
| 281 | if cid < FIRST_GUEST_CID { |
| 282 | warn!("connection is not from a guest VM"); |
| 283 | continue; |
| 284 | } |
| 285 | if let Some(vm) = state.lock().unwrap().get_vm(cid) { |
| 286 | vm.callbacks.notify_payload_started(cid, stream); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | Ok(()) |
| 291 | } |
| 292 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame^] | 293 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 294 | let file = OpenOptions::new() |
| 295 | .create_new(true) |
| 296 | .read(true) |
| 297 | .write(true) |
| 298 | .open(zero_filler_path) |
| 299 | .with_context(|| "Failed to create zero.img")?; |
| 300 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame^] | 301 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 302 | } |
| 303 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 304 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 305 | /// |
| 306 | /// This may involve assembling a composite disk from a set of partition images. |
| 307 | fn assemble_disk_image( |
| 308 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 309 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 310 | temporary_directory: &Path, |
| 311 | next_temporary_image_id: &mut u64, |
| 312 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 313 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 314 | let image = if !disk.partitions.is_empty() { |
| 315 | if disk.image.is_some() { |
| 316 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 317 | return Err(new_binder_exception( |
| 318 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 319 | "DiskImage contains both image and partitions.", |
| 320 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 321 | } |
| 322 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 323 | let composite_image_filenames = |
| 324 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 325 | let (image, partition_files) = make_composite_image( |
| 326 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 327 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 328 | &composite_image_filenames.composite, |
| 329 | &composite_image_filenames.header, |
| 330 | &composite_image_filenames.footer, |
| 331 | ) |
| 332 | .map_err(|e| { |
| 333 | error!("Failed to make composite image with config {:?}: {}", disk, e); |
| 334 | new_binder_exception( |
| 335 | ExceptionCode::SERVICE_SPECIFIC, |
| 336 | format!("Failed to make composite image: {}", e), |
| 337 | ) |
| 338 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 339 | |
| 340 | // Pass the file descriptors for the various partition files to crosvm when it |
| 341 | // is run. |
| 342 | indirect_files.extend(partition_files); |
| 343 | |
| 344 | image |
| 345 | } else if let Some(image) = &disk.image { |
| 346 | clone_file(image)? |
| 347 | } else { |
| 348 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 349 | return Err(new_binder_exception( |
| 350 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 351 | "DiskImage didn't contain image or partitions.", |
| 352 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 353 | }; |
| 354 | |
| 355 | Ok(DiskFile { image, writable: disk.writable }) |
| 356 | } |
| 357 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 358 | fn load_app_config( |
| 359 | config: &VirtualMachineAppConfig, |
| 360 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 361 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 362 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 363 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 364 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 365 | let config_path = &config.configPath; |
| 366 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 367 | let mut apk_zip = ZipArchive::new(&apk_file)?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 368 | let config_file = apk_zip.by_name(config_path)?; |
| 369 | let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?; |
| 370 | |
| 371 | let os_name = &vm_payload_config.os.name; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 372 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 373 | // For now, the only supported "os" value is "microdroid" |
| 374 | if os_name != "microdroid" { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 375 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 376 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 377 | |
| 378 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 379 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 380 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 381 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 382 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 383 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 384 | if config.memoryMib > 0 { |
| 385 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 386 | } |
| 387 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 388 | // Microdroid requires an additional payload disk image and the bootconfig partition. |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 389 | if os_name == "microdroid" { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 390 | let apexes = vm_payload_config.apexes.clone(); |
| 391 | add_microdroid_images( |
| 392 | config, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 393 | temporary_directory, |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 394 | apk_file, |
| 395 | idsig_file, |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 396 | instance_file, |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 397 | apexes, |
| 398 | &mut vm_config, |
| 399 | )?; |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 400 | } |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 401 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 402 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 403 | } |
| 404 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 405 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 406 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 407 | temporary_directory: &Path, |
| 408 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 409 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 410 | let id = *next_temporary_image_id; |
| 411 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 412 | CompositeImageFilenames { |
| 413 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 414 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 415 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// Filenames for a composite disk image, including header and footer partitions. |
| 420 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 421 | struct CompositeImageFilenames { |
| 422 | /// The composite disk image itself. |
| 423 | composite: PathBuf, |
| 424 | /// The header partition image. |
| 425 | header: PathBuf, |
| 426 | /// The footer partition image. |
| 427 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 428 | } |
| 429 | |
| 430 | /// Gets the calling SID of the current Binder thread. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 431 | fn get_calling_sid() -> Result<String, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 432 | ThreadState::with_calling_sid(|sid| { |
| 433 | if let Some(sid) = sid { |
| 434 | match sid.to_str() { |
| 435 | Ok(sid) => Ok(sid.to_owned()), |
| 436 | Err(e) => { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 437 | error!("SID was not valid UTF-8: {}", e); |
| 438 | Err(new_binder_exception( |
| 439 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 440 | format!("SID was not valid UTF-8: {}", e), |
| 441 | )) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 442 | } |
| 443 | } |
| 444 | } else { |
| 445 | error!("Missing SID on startVm"); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 446 | Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm")) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 447 | } |
| 448 | }) |
| 449 | } |
| 450 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 451 | /// Checks whether the caller has a specific permission |
| 452 | fn check_permission(perm: &str) -> binder::Result<()> { |
| 453 | let calling_pid = ThreadState::get_calling_pid(); |
| 454 | let calling_uid = ThreadState::get_calling_uid(); |
| 455 | // Root can do anything |
| 456 | if calling_uid == 0 { |
| 457 | return Ok(()); |
| 458 | } |
| 459 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 460 | binder::get_interface("permission")?; |
| 461 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 462 | Ok(()) |
| 463 | } else { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 464 | Err(new_binder_exception( |
| 465 | ExceptionCode::SECURITY, |
| 466 | format!("does not have the {} permission", perm), |
| 467 | )) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 468 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 469 | } |
| 470 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 471 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 472 | fn check_debug_access() -> binder::Result<()> { |
| 473 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 474 | } |
| 475 | |
| 476 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 477 | fn check_manage_access() -> binder::Result<()> { |
| 478 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 479 | } |
| 480 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 481 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 482 | #[derive(Debug)] |
| 483 | struct VirtualMachine { |
| 484 | instance: Arc<VmInstance>, |
| 485 | } |
| 486 | |
| 487 | impl VirtualMachine { |
| 488 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 489 | let binder = VirtualMachine { instance }; |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 490 | BnVirtualMachine::new_binder(binder, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 491 | } |
| 492 | } |
| 493 | |
| 494 | impl Interface for VirtualMachine {} |
| 495 | |
| 496 | impl IVirtualMachine for VirtualMachine { |
| 497 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 498 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 499 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 500 | Ok(self.instance.cid as i32) |
| 501 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 502 | |
| 503 | fn isRunning(&self) -> binder::Result<bool> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 504 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 505 | // others. |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 506 | Ok(self.instance.running()) |
| 507 | } |
| 508 | |
| 509 | fn registerCallback( |
| 510 | &self, |
| 511 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 512 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 513 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 514 | // others. |
| 515 | // |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 516 | // TODO: Should this give an error if the VM is already dead? |
| 517 | self.instance.callbacks.add(callback.clone()); |
| 518 | Ok(()) |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | impl Drop for VirtualMachine { |
| 523 | fn drop(&mut self) { |
| 524 | debug!("Dropping {:?}", self); |
| 525 | self.instance.kill(); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 530 | /// dies. |
| 531 | #[derive(Debug, Default)] |
| 532 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 533 | |
| 534 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 535 | /// Call all registered callbacks to notify that the payload has started. |
| 536 | pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) { |
| 537 | let callbacks = &*self.0.lock().unwrap(); |
| 538 | // SAFETY: ownership is transferred from stream to f |
| 539 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 540 | let pfd = ParcelFileDescriptor::new(f); |
| 541 | for callback in callbacks { |
| 542 | if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) { |
| 543 | error!("Error notifying payload start event from VM CID {}: {}", cid, e); |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 548 | /// Call all registered callbacks to say that the VM has died. |
| 549 | pub fn callback_on_died(&self, cid: Cid) { |
| 550 | let callbacks = &*self.0.lock().unwrap(); |
| 551 | for callback in callbacks { |
| 552 | if let Err(e) = callback.onDied(cid as i32) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 553 | error!("Error notifying exit of VM CID {}: {}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 554 | } |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /// Add a new callback to the set. |
| 559 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 560 | self.0.lock().unwrap().push(callback); |
| 561 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 562 | } |
| 563 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 564 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 565 | /// struct. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 566 | #[derive(Debug)] |
| 567 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 568 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 569 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 570 | |
| 571 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 572 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 573 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 574 | /// from the list opportunistically the next time `add_vm` is called. |
| 575 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 576 | |
| 577 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 578 | /// This is only used for debugging purposes. |
| 579 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 580 | } |
| 581 | |
| 582 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 583 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 584 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 585 | // Attempt to upgrade the weak pointers to strong pointers. |
| 586 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 587 | } |
| 588 | |
| 589 | /// Add a new VM to the list. |
| 590 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 591 | // Garbage collect any entries from the stored list which no longer exist. |
| 592 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 593 | |
| 594 | // Actually add the new VM. |
| 595 | self.vms.push(vm); |
| 596 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 597 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 598 | /// Get a VM that corresponds to the given cid |
| 599 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 600 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 601 | } |
| 602 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 603 | /// Store a strong VM reference. |
| 604 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 605 | self.debug_held_vms.push(vm); |
| 606 | } |
| 607 | |
| 608 | /// Retrieve and remove a strong VM reference. |
| 609 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 610 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
| 611 | Some(self.debug_held_vms.swap_remove(pos)) |
| 612 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 613 | |
| 614 | /// Get the next available CID, or an error if we have run out. |
| 615 | fn allocate_cid(&mut self) -> binder::Result<Cid> { |
| 616 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 617 | let cid = self.next_cid; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 618 | self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 619 | Ok(cid) |
| 620 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 621 | } |
| 622 | |
| 623 | impl Default for State { |
| 624 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 625 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 626 | } |
| 627 | } |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 628 | |
| 629 | /// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`. |
| 630 | fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> { |
| 631 | option.as_ref().map(|t| t.as_ref()) |
| 632 | } |
| 633 | |
| 634 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 635 | fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
| 636 | file.as_ref().try_clone().map_err(|e| { |
| 637 | new_binder_exception( |
| 638 | ExceptionCode::BAD_PARCELABLE, |
| 639 | format!("Failed to clone File from ParcelFileDescriptor: {}", e), |
| 640 | ) |
| 641 | }) |
| 642 | } |
| 643 | |
| 644 | /// Constructs a new Binder error `Status` with the given `ExceptionCode` and message. |
| 645 | fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status { |
| 646 | Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref()) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 647 | } |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 648 | |
| 649 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 650 | /// it doesn't require that T implements Clone. |
| 651 | enum BorrowedOrOwned<'a, T> { |
| 652 | Borrowed(&'a T), |
| 653 | Owned(T), |
| 654 | } |
| 655 | |
| 656 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 657 | fn as_ref(&self) -> &T { |
| 658 | match self { |
| 659 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 660 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 661 | } |
| 662 | } |
| 663 | } |