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 | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 19 | use crate::{Cid, FIRST_GUEST_CID}; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 20 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 21 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 22 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{ |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 23 | BnVirtualMachine, IVirtualMachine, |
| 24 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 25 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback; |
| 26 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig; |
| 27 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
| 28 | use android_system_virtualizationservice::binder::{ |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 29 | self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 30 | }; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 31 | use command_fds::FdMapping; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 32 | use disk::QcowFile; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 33 | use log::{debug, error, warn}; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 34 | use std::convert::TryInto; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 35 | use std::ffi::CString; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 36 | use std::fs::{File, create_dir}; |
| 37 | use std::os::unix::io::AsRawFd; |
| 38 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 39 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 40 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 41 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 42 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 43 | /// Directory in which to write disk image files used while running VMs. |
| 44 | const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
| 45 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 46 | // TODO(qwandor): Use PermissionController once it is available to Rust. |
| 47 | /// Only processes running with one of these UIDs are allowed to call debug methods. |
| 48 | const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000]; |
| 49 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 50 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 51 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 52 | pub struct VirtualizationService { |
Andrew Walbran | 9c01baa | 2021-03-08 18:23:50 +0000 | [diff] [blame] | 53 | state: Mutex<State>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 54 | } |
| 55 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 56 | impl Interface for VirtualizationService {} |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 57 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 58 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 59 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 60 | /// |
| 61 | /// 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] | 62 | fn startVm( |
| 63 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 64 | config: &VirtualMachineConfig, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 65 | log_fd: Option<&ParcelFileDescriptor>, |
| 66 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 67 | let state = &mut *self.state.lock().unwrap(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 68 | let log_fd = log_fd.map(clone_file).transpose()?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 69 | let requester_uid = ThreadState::get_calling_uid(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 70 | let requester_sid = get_calling_sid()?; |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 71 | let requester_debug_pid = ThreadState::get_calling_pid(); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 72 | let cid = state.allocate_cid()?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 73 | |
| 74 | // Counter to generate unique IDs for temporary image files. |
| 75 | let mut next_temporary_image_id = 0; |
| 76 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 77 | // child process, and not closed before it is started. |
| 78 | let mut indirect_files = vec![]; |
| 79 | |
| 80 | // Make directory for temporary files. |
| 81 | let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 82 | create_dir(&temporary_directory).map_err(|e| { |
| 83 | error!( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 84 | "Failed to create temporary directory {:?} for VM files: {}", |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 85 | temporary_directory, e |
| 86 | ); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 87 | new_binder_exception( |
| 88 | ExceptionCode::SERVICE_SPECIFIC, |
| 89 | format!( |
| 90 | "Failed to create temporary directory {:?} for VM files: {}", |
| 91 | temporary_directory, e |
| 92 | ), |
| 93 | ) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 94 | })?; |
| 95 | |
| 96 | // Assemble disk images if needed. |
| 97 | let disks = config |
| 98 | .disks |
| 99 | .iter() |
| 100 | .map(|disk| { |
| 101 | assemble_disk_image( |
| 102 | disk, |
| 103 | &temporary_directory, |
| 104 | &mut next_temporary_image_id, |
| 105 | &mut indirect_files, |
| 106 | ) |
| 107 | }) |
| 108 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 109 | |
| 110 | // Actually start the VM. |
| 111 | let crosvm_config = CrosvmConfig { |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 112 | cid, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 113 | bootloader: as_asref(&config.bootloader), |
| 114 | kernel: as_asref(&config.kernel), |
| 115 | initrd: as_asref(&config.initrd), |
| 116 | disks, |
| 117 | params: config.params.to_owned(), |
| 118 | }; |
| 119 | let composite_disk_mappings: Vec<_> = indirect_files |
| 120 | .iter() |
| 121 | .map(|file| { |
| 122 | let fd = file.as_raw_fd(); |
| 123 | FdMapping { parent_fd: fd, child_fd: fd } |
| 124 | }) |
| 125 | .collect(); |
| 126 | let instance = VmInstance::start( |
| 127 | &crosvm_config, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 128 | log_fd, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 129 | &composite_disk_mappings, |
| 130 | temporary_directory, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 131 | requester_uid, |
| 132 | requester_sid, |
| 133 | requester_debug_pid, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 134 | ) |
| 135 | .map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 136 | error!("Failed to start VM with config {:?}: {}", config, e); |
| 137 | new_binder_exception( |
| 138 | ExceptionCode::SERVICE_SPECIFIC, |
| 139 | format!("Failed to start VM: {}", e), |
| 140 | ) |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 141 | })?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 142 | state.add_vm(Arc::downgrade(&instance)); |
| 143 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 144 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 145 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 146 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 147 | fn initializeWritablePartition( |
| 148 | &self, |
| 149 | image_fd: &ParcelFileDescriptor, |
| 150 | size: i64, |
| 151 | ) -> binder::Result<()> { |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 152 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 153 | new_binder_exception( |
| 154 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 155 | format!("Invalid size {}: {}", size, e), |
| 156 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 157 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 158 | let image = clone_file(image_fd)?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 159 | |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 160 | QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 161 | new_binder_exception( |
| 162 | ExceptionCode::SERVICE_SPECIFIC, |
| 163 | format!("Failed to create QCOW2 image: {}", e), |
| 164 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 165 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 166 | |
| 167 | Ok(()) |
| 168 | } |
| 169 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 170 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 171 | /// and as such is only permitted from the shell user. |
| 172 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 173 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 174 | |
| 175 | let state = &mut *self.state.lock().unwrap(); |
| 176 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 177 | let cids = vms |
| 178 | .into_iter() |
| 179 | .map(|vm| VirtualMachineDebugInfo { |
| 180 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 181 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 182 | requesterUid: vm.requester_uid as i32, |
| 183 | requesterSid: vm.requester_sid.clone(), |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 184 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 185 | running: vm.running(), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 186 | }) |
| 187 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 188 | Ok(cids) |
| 189 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 190 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 191 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 192 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 193 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 194 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 195 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 196 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 197 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 198 | Ok(()) |
| 199 | } |
| 200 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 201 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 202 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 203 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 204 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 205 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 206 | |
| 207 | let state = &mut *self.state.lock().unwrap(); |
| 208 | Ok(state.debug_drop_vm(cid)) |
| 209 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 210 | } |
| 211 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 212 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 213 | /// |
| 214 | /// This may involve assembling a composite disk from a set of partition images. |
| 215 | fn assemble_disk_image( |
| 216 | disk: &DiskImage, |
| 217 | temporary_directory: &Path, |
| 218 | next_temporary_image_id: &mut u64, |
| 219 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 220 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 221 | let image = if !disk.partitions.is_empty() { |
| 222 | if disk.image.is_some() { |
| 223 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 224 | return Err(new_binder_exception( |
| 225 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 226 | "DiskImage contains both image and partitions.", |
| 227 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 228 | } |
| 229 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame^] | 230 | let composite_image_filenames = |
| 231 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 232 | let (image, partition_files) = make_composite_image( |
| 233 | &disk.partitions, |
| 234 | &composite_image_filenames.composite, |
| 235 | &composite_image_filenames.header, |
| 236 | &composite_image_filenames.footer, |
| 237 | ) |
| 238 | .map_err(|e| { |
| 239 | error!("Failed to make composite image with config {:?}: {}", disk, e); |
| 240 | new_binder_exception( |
| 241 | ExceptionCode::SERVICE_SPECIFIC, |
| 242 | format!("Failed to make composite image: {}", e), |
| 243 | ) |
| 244 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 245 | |
| 246 | // Pass the file descriptors for the various partition files to crosvm when it |
| 247 | // is run. |
| 248 | indirect_files.extend(partition_files); |
| 249 | |
| 250 | image |
| 251 | } else if let Some(image) = &disk.image { |
| 252 | clone_file(image)? |
| 253 | } else { |
| 254 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 255 | return Err(new_binder_exception( |
| 256 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 257 | "DiskImage didn't contain image or partitions.", |
| 258 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 259 | }; |
| 260 | |
| 261 | Ok(DiskFile { image, writable: disk.writable }) |
| 262 | } |
| 263 | |
| 264 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame^] | 265 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 266 | temporary_directory: &Path, |
| 267 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame^] | 268 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 269 | let id = *next_temporary_image_id; |
| 270 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame^] | 271 | CompositeImageFilenames { |
| 272 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 273 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 274 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | /// Filenames for a composite disk image, including header and footer partitions. |
| 279 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 280 | struct CompositeImageFilenames { |
| 281 | /// The composite disk image itself. |
| 282 | composite: PathBuf, |
| 283 | /// The header partition image. |
| 284 | header: PathBuf, |
| 285 | /// The footer partition image. |
| 286 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 287 | } |
| 288 | |
| 289 | /// Gets the calling SID of the current Binder thread. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 290 | fn get_calling_sid() -> Result<String, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 291 | ThreadState::with_calling_sid(|sid| { |
| 292 | if let Some(sid) = sid { |
| 293 | match sid.to_str() { |
| 294 | Ok(sid) => Ok(sid.to_owned()), |
| 295 | Err(e) => { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 296 | error!("SID was not valid UTF-8: {}", e); |
| 297 | Err(new_binder_exception( |
| 298 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 299 | format!("SID was not valid UTF-8: {}", e), |
| 300 | )) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 301 | } |
| 302 | } |
| 303 | } else { |
| 304 | error!("Missing SID on startVm"); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 305 | Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm")) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 306 | } |
| 307 | }) |
| 308 | } |
| 309 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 310 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 311 | fn check_debug_access() -> binder::Result<()> { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 312 | let uid = ThreadState::get_calling_uid(); |
| 313 | log::trace!("Debug method call from UID {}.", uid); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 314 | if DEBUG_ALLOWED_UIDS.contains(&uid) { |
| 315 | Ok(()) |
| 316 | } else { |
| 317 | Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied")) |
| 318 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 319 | } |
| 320 | |
| 321 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 322 | #[derive(Debug)] |
| 323 | struct VirtualMachine { |
| 324 | instance: Arc<VmInstance>, |
| 325 | } |
| 326 | |
| 327 | impl VirtualMachine { |
| 328 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 329 | let binder = VirtualMachine { instance }; |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 330 | BnVirtualMachine::new_binder(binder, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 331 | } |
| 332 | } |
| 333 | |
| 334 | impl Interface for VirtualMachine {} |
| 335 | |
| 336 | impl IVirtualMachine for VirtualMachine { |
| 337 | fn getCid(&self) -> binder::Result<i32> { |
| 338 | Ok(self.instance.cid as i32) |
| 339 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 340 | |
| 341 | fn isRunning(&self) -> binder::Result<bool> { |
| 342 | Ok(self.instance.running()) |
| 343 | } |
| 344 | |
| 345 | fn registerCallback( |
| 346 | &self, |
| 347 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 348 | ) -> binder::Result<()> { |
| 349 | // TODO: Should this give an error if the VM is already dead? |
| 350 | self.instance.callbacks.add(callback.clone()); |
| 351 | Ok(()) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | impl Drop for VirtualMachine { |
| 356 | fn drop(&mut self) { |
| 357 | debug!("Dropping {:?}", self); |
| 358 | self.instance.kill(); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 363 | /// dies. |
| 364 | #[derive(Debug, Default)] |
| 365 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 366 | |
| 367 | impl VirtualMachineCallbacks { |
| 368 | /// Call all registered callbacks to say that the VM has died. |
| 369 | pub fn callback_on_died(&self, cid: Cid) { |
| 370 | let callbacks = &*self.0.lock().unwrap(); |
| 371 | for callback in callbacks { |
| 372 | if let Err(e) = callback.onDied(cid as i32) { |
| 373 | error!("Error calling callback: {}", e); |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | /// Add a new callback to the set. |
| 379 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 380 | self.0.lock().unwrap().push(callback); |
| 381 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 382 | } |
| 383 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 384 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 385 | /// struct. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 386 | #[derive(Debug)] |
| 387 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 388 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 389 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 390 | |
| 391 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 392 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 393 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 394 | /// from the list opportunistically the next time `add_vm` is called. |
| 395 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 396 | |
| 397 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 398 | /// This is only used for debugging purposes. |
| 399 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 400 | } |
| 401 | |
| 402 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 403 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 404 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 405 | // Attempt to upgrade the weak pointers to strong pointers. |
| 406 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 407 | } |
| 408 | |
| 409 | /// Add a new VM to the list. |
| 410 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 411 | // Garbage collect any entries from the stored list which no longer exist. |
| 412 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 413 | |
| 414 | // Actually add the new VM. |
| 415 | self.vms.push(vm); |
| 416 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 417 | |
| 418 | /// Store a strong VM reference. |
| 419 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 420 | self.debug_held_vms.push(vm); |
| 421 | } |
| 422 | |
| 423 | /// Retrieve and remove a strong VM reference. |
| 424 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 425 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
| 426 | Some(self.debug_held_vms.swap_remove(pos)) |
| 427 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 428 | |
| 429 | /// Get the next available CID, or an error if we have run out. |
| 430 | fn allocate_cid(&mut self) -> binder::Result<Cid> { |
| 431 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 432 | let cid = self.next_cid; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 433 | 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] | 434 | Ok(cid) |
| 435 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 436 | } |
| 437 | |
| 438 | impl Default for State { |
| 439 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 440 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 441 | } |
| 442 | } |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 443 | |
| 444 | /// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`. |
| 445 | fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> { |
| 446 | option.as_ref().map(|t| t.as_ref()) |
| 447 | } |
| 448 | |
| 449 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 450 | fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
| 451 | file.as_ref().try_clone().map_err(|e| { |
| 452 | new_binder_exception( |
| 453 | ExceptionCode::BAD_PARCELABLE, |
| 454 | format!("Failed to clone File from ParcelFileDescriptor: {}", e), |
| 455 | ) |
| 456 | }) |
| 457 | } |
| 458 | |
| 459 | /// Constructs a new Binder error `Status` with the given `ExceptionCode` and message. |
| 460 | fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status { |
| 461 | Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref()) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 462 | } |