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