blob: ce9a080c51dcf0cdf4f05d6f1278e73d1653f147 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000017use crate::composite::make_composite_image;
18use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000019use crate::{Cid, FIRST_GUEST_CID};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000020use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000021use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000022use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000023 BnVirtualMachine, IVirtualMachine,
24};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000025use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
26use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig;
27use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
28use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000029 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000030};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000031use disk::QcowFile;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000032use log::{debug, error, warn};
Andrew Walbrandff3b942021-06-09 15:20:36 +000033use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000034use std::ffi::CString;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000035use std::fs::{File, create_dir};
36use std::os::unix::io::AsRawFd;
37use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000038use std::sync::{Arc, Mutex, Weak};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000039
Andrew Walbranf6bf6862021-05-21 12:41:13 +000040pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000041
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000042/// Directory in which to write disk image files used while running VMs.
43const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
44
Andrew Walbran320b5602021-03-04 16:11:12 +000045// TODO(qwandor): Use PermissionController once it is available to Rust.
46/// Only processes running with one of these UIDs are allowed to call debug methods.
47const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
48
Andrew Walbranf6bf6862021-05-21 12:41:13 +000049/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000051pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000052 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000053}
54
Andrew Walbranf6bf6862021-05-21 12:41:13 +000055impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000056
Andrew Walbranf6bf6862021-05-21 12:41:13 +000057impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000058 /// Create and start a new VM with the given configuration, assigning it the next available CID.
59 ///
60 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000061 fn startVm(
62 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000063 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000064 log_fd: Option<&ParcelFileDescriptor>,
65 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000066 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000067 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000068 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000070 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000071 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072
73 // Counter to generate unique IDs for temporary image files.
74 let mut next_temporary_image_id = 0;
75 // Files which are referred to from composite images. These must be mapped to the crosvm
76 // child process, and not closed before it is started.
77 let mut indirect_files = vec![];
78
79 // Make directory for temporary files.
80 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
81 create_dir(&temporary_directory).map_err(|e| {
82 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +000083 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000084 temporary_directory, e
85 );
Andrew Walbran806f1542021-06-10 14:07:12 +000086 new_binder_exception(
87 ExceptionCode::SERVICE_SPECIFIC,
88 format!(
89 "Failed to create temporary directory {:?} for VM files: {}",
90 temporary_directory, e
91 ),
92 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 })?;
94
95 // Assemble disk images if needed.
96 let disks = config
97 .disks
98 .iter()
99 .map(|disk| {
100 assemble_disk_image(
101 disk,
102 &temporary_directory,
103 &mut next_temporary_image_id,
104 &mut indirect_files,
105 )
106 })
107 .collect::<Result<Vec<DiskFile>, _>>()?;
108
109 // Actually start the VM.
110 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000111 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000112 bootloader: as_asref(&config.bootloader),
113 kernel: as_asref(&config.kernel),
114 initrd: as_asref(&config.initrd),
115 disks,
116 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000117 protected: config.protected_vm,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000118 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000119 let composite_disk_fds: Vec<_> =
120 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000121 let instance = VmInstance::start(
122 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000123 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000124 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000125 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000126 requester_uid,
127 requester_sid,
128 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000129 )
130 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000131 error!("Failed to start VM with config {:?}: {}", config, e);
132 new_binder_exception(
133 ExceptionCode::SERVICE_SPECIFIC,
134 format!("Failed to start VM: {}", e),
135 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000136 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000137 state.add_vm(Arc::downgrade(&instance));
138 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000139 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000140
Andrew Walbrandff3b942021-06-09 15:20:36 +0000141 /// Initialise an empty partition image of the given size to be used as a writable partition.
142 fn initializeWritablePartition(
143 &self,
144 image_fd: &ParcelFileDescriptor,
145 size: i64,
146 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000147 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000148 new_binder_exception(
149 ExceptionCode::ILLEGAL_ARGUMENT,
150 format!("Invalid size {}: {}", size, e),
151 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000152 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000153 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000154
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000155 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000156 new_binder_exception(
157 ExceptionCode::SERVICE_SPECIFIC,
158 format!("Failed to create QCOW2 image: {}", e),
159 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000160 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000161
162 Ok(())
163 }
164
Andrew Walbran320b5602021-03-04 16:11:12 +0000165 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
166 /// and as such is only permitted from the shell user.
167 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000168 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000169
170 let state = &mut *self.state.lock().unwrap();
171 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000172 let cids = vms
173 .into_iter()
174 .map(|vm| VirtualMachineDebugInfo {
175 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000176 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000177 requesterUid: vm.requester_uid as i32,
178 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000179 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000180 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000181 })
182 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000183 Ok(cids)
184 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000185
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000186 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
187 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000188 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000189 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000190
David Brazdil3c2ddef2021-03-18 13:09:57 +0000191 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000192 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000193 Ok(())
194 }
195
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000196 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
197 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
198 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000199 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000200 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000201
202 let state = &mut *self.state.lock().unwrap();
203 Ok(state.debug_drop_vm(cid))
204 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000205}
206
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000207/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
208///
209/// This may involve assembling a composite disk from a set of partition images.
210fn assemble_disk_image(
211 disk: &DiskImage,
212 temporary_directory: &Path,
213 next_temporary_image_id: &mut u64,
214 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000215) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000216 let image = if !disk.partitions.is_empty() {
217 if disk.image.is_some() {
218 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000219 return Err(new_binder_exception(
220 ExceptionCode::ILLEGAL_ARGUMENT,
221 "DiskImage contains both image and partitions.",
222 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000223 }
224
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000225 let composite_image_filenames =
226 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
227 let (image, partition_files) = make_composite_image(
228 &disk.partitions,
229 &composite_image_filenames.composite,
230 &composite_image_filenames.header,
231 &composite_image_filenames.footer,
232 )
233 .map_err(|e| {
234 error!("Failed to make composite image with config {:?}: {}", disk, e);
235 new_binder_exception(
236 ExceptionCode::SERVICE_SPECIFIC,
237 format!("Failed to make composite image: {}", e),
238 )
239 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000240
241 // Pass the file descriptors for the various partition files to crosvm when it
242 // is run.
243 indirect_files.extend(partition_files);
244
245 image
246 } else if let Some(image) = &disk.image {
247 clone_file(image)?
248 } else {
249 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000250 return Err(new_binder_exception(
251 ExceptionCode::ILLEGAL_ARGUMENT,
252 "DiskImage didn't contain image or partitions.",
253 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000254 };
255
256 Ok(DiskFile { image, writable: disk.writable })
257}
258
259/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000260fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000261 temporary_directory: &Path,
262 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000263) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000264 let id = *next_temporary_image_id;
265 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000266 CompositeImageFilenames {
267 composite: temporary_directory.join(format!("composite-{}.img", id)),
268 header: temporary_directory.join(format!("composite-{}-header.img", id)),
269 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
270 }
271}
272
273/// Filenames for a composite disk image, including header and footer partitions.
274#[derive(Clone, Debug, Eq, PartialEq)]
275struct CompositeImageFilenames {
276 /// The composite disk image itself.
277 composite: PathBuf,
278 /// The header partition image.
279 header: PathBuf,
280 /// The footer partition image.
281 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000282}
283
284/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000285fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000286 ThreadState::with_calling_sid(|sid| {
287 if let Some(sid) = sid {
288 match sid.to_str() {
289 Ok(sid) => Ok(sid.to_owned()),
290 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000291 error!("SID was not valid UTF-8: {}", e);
292 Err(new_binder_exception(
293 ExceptionCode::ILLEGAL_ARGUMENT,
294 format!("SID was not valid UTF-8: {}", e),
295 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000296 }
297 }
298 } else {
299 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000300 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000301 }
302 })
303}
304
Andrew Walbran320b5602021-03-04 16:11:12 +0000305/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000306fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000307 let uid = ThreadState::get_calling_uid();
308 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000309 if DEBUG_ALLOWED_UIDS.contains(&uid) {
310 Ok(())
311 } else {
312 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
313 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000314}
315
316/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
317#[derive(Debug)]
318struct VirtualMachine {
319 instance: Arc<VmInstance>,
320}
321
322impl VirtualMachine {
323 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
324 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000325 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000326 }
327}
328
329impl Interface for VirtualMachine {}
330
331impl IVirtualMachine for VirtualMachine {
332 fn getCid(&self) -> binder::Result<i32> {
333 Ok(self.instance.cid as i32)
334 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000335
336 fn isRunning(&self) -> binder::Result<bool> {
337 Ok(self.instance.running())
338 }
339
340 fn registerCallback(
341 &self,
342 callback: &Strong<dyn IVirtualMachineCallback>,
343 ) -> binder::Result<()> {
344 // TODO: Should this give an error if the VM is already dead?
345 self.instance.callbacks.add(callback.clone());
346 Ok(())
347 }
348}
349
350impl Drop for VirtualMachine {
351 fn drop(&mut self) {
352 debug!("Dropping {:?}", self);
353 self.instance.kill();
354 }
355}
356
357/// A set of Binders to be called back in response to various events on the VM, such as when it
358/// dies.
359#[derive(Debug, Default)]
360pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
361
362impl VirtualMachineCallbacks {
363 /// Call all registered callbacks to say that the VM has died.
364 pub fn callback_on_died(&self, cid: Cid) {
365 let callbacks = &*self.0.lock().unwrap();
366 for callback in callbacks {
367 if let Err(e) = callback.onDied(cid as i32) {
368 error!("Error calling callback: {}", e);
369 }
370 }
371 }
372
373 /// Add a new callback to the set.
374 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
375 self.0.lock().unwrap().push(callback);
376 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000377}
378
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000379/// The mutable state of the VirtualizationService. There should only be one instance of this
380/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000381#[derive(Debug)]
382struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000383 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000384 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000385
386 /// The VMs which have been started. When VMs are started a weak reference is added to this list
387 /// while a strong reference is returned to the caller over Binder. Once all copies of the
388 /// Binder client are dropped the weak reference here will become invalid, and will be removed
389 /// from the list opportunistically the next time `add_vm` is called.
390 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000391
392 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
393 /// This is only used for debugging purposes.
394 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000395}
396
397impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000398 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000399 fn vms(&self) -> Vec<Arc<VmInstance>> {
400 // Attempt to upgrade the weak pointers to strong pointers.
401 self.vms.iter().filter_map(Weak::upgrade).collect()
402 }
403
404 /// Add a new VM to the list.
405 fn add_vm(&mut self, vm: Weak<VmInstance>) {
406 // Garbage collect any entries from the stored list which no longer exist.
407 self.vms.retain(|vm| vm.strong_count() > 0);
408
409 // Actually add the new VM.
410 self.vms.push(vm);
411 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000412
413 /// Store a strong VM reference.
414 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
415 self.debug_held_vms.push(vm);
416 }
417
418 /// Retrieve and remove a strong VM reference.
419 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
420 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
421 Some(self.debug_held_vms.swap_remove(pos))
422 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000423
424 /// Get the next available CID, or an error if we have run out.
425 fn allocate_cid(&mut self) -> binder::Result<Cid> {
426 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
427 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000428 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000429 Ok(cid)
430 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000431}
432
433impl Default for State {
434 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000435 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000436 }
437}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000438
439/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
440fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
441 option.as_ref().map(|t| t.as_ref())
442}
443
444/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000445fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
446 file.as_ref().try_clone().map_err(|e| {
447 new_binder_exception(
448 ExceptionCode::BAD_PARCELABLE,
449 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
450 )
451 })
452}
453
454/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
455fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
456 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000457}