blob: b1b0b38f489426cd7c3398253eb9bebb2905a85c [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 Walbranf5fbb7d2021-05-12 17:15:48 +000031use command_fds::FdMapping;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000032use disk::QcowFile;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000033use log::{debug, error, warn};
Andrew Walbrandff3b942021-06-09 15:20:36 +000034use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000035use std::ffi::CString;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000036use std::fs::{File, create_dir};
37use std::os::unix::io::AsRawFd;
38use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000039use std::sync::{Arc, Mutex, Weak};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000040
Andrew Walbranf6bf6862021-05-21 12:41:13 +000041pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000042
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000043/// Directory in which to write disk image files used while running VMs.
44const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
45
Andrew Walbran320b5602021-03-04 16:11:12 +000046// 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.
48const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
49
Andrew Walbranf6bf6862021-05-21 12:41:13 +000050/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000052pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000053 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054}
55
Andrew Walbranf6bf6862021-05-21 12:41:13 +000056impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000057
Andrew Walbranf6bf6862021-05-21 12:41:13 +000058impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000059 /// 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 Walbrana89fc132021-03-17 17:08:36 +000062 fn startVm(
63 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000064 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000065 log_fd: Option<&ParcelFileDescriptor>,
66 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000067 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000068 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000069 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000070 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000071 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000072 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073
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 Walbran806f1542021-06-10 14:07:12 +000084 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000085 temporary_directory, e
86 );
Andrew Walbran806f1542021-06-10 14:07:12 +000087 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 Walbranf5fbb7d2021-05-12 17:15:48 +000094 })?;
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 Walbran02034492021-04-13 15:05:07 +0000112 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000113 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(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000118 protected: config.protected_vm,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119 };
120 let composite_disk_mappings: Vec<_> = indirect_files
121 .iter()
122 .map(|file| {
123 let fd = file.as_raw_fd();
124 FdMapping { parent_fd: fd, child_fd: fd }
125 })
126 .collect();
127 let instance = VmInstance::start(
128 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000129 log_fd,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000130 &composite_disk_mappings,
131 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000132 requester_uid,
133 requester_sid,
134 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000135 )
136 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000137 error!("Failed to start VM with config {:?}: {}", config, e);
138 new_binder_exception(
139 ExceptionCode::SERVICE_SPECIFIC,
140 format!("Failed to start VM: {}", e),
141 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000142 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000143 state.add_vm(Arc::downgrade(&instance));
144 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000145 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000146
Andrew Walbrandff3b942021-06-09 15:20:36 +0000147 /// Initialise an empty partition image of the given size to be used as a writable partition.
148 fn initializeWritablePartition(
149 &self,
150 image_fd: &ParcelFileDescriptor,
151 size: i64,
152 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000153 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000154 new_binder_exception(
155 ExceptionCode::ILLEGAL_ARGUMENT,
156 format!("Invalid size {}: {}", size, e),
157 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000158 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000159 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000160
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000161 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000162 new_binder_exception(
163 ExceptionCode::SERVICE_SPECIFIC,
164 format!("Failed to create QCOW2 image: {}", e),
165 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000166 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000167
168 Ok(())
169 }
170
Andrew Walbran320b5602021-03-04 16:11:12 +0000171 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
172 /// and as such is only permitted from the shell user.
173 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000174 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000175
176 let state = &mut *self.state.lock().unwrap();
177 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000178 let cids = vms
179 .into_iter()
180 .map(|vm| VirtualMachineDebugInfo {
181 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000182 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000183 requesterUid: vm.requester_uid as i32,
184 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000185 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000186 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000187 })
188 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000189 Ok(cids)
190 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000191
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000192 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
193 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000194 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000195 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000196
David Brazdil3c2ddef2021-03-18 13:09:57 +0000197 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000198 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000199 Ok(())
200 }
201
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000202 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
203 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
204 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000205 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000206 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000207
208 let state = &mut *self.state.lock().unwrap();
209 Ok(state.debug_drop_vm(cid))
210 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000211}
212
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000213/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
214///
215/// This may involve assembling a composite disk from a set of partition images.
216fn assemble_disk_image(
217 disk: &DiskImage,
218 temporary_directory: &Path,
219 next_temporary_image_id: &mut u64,
220 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000221) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000222 let image = if !disk.partitions.is_empty() {
223 if disk.image.is_some() {
224 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000225 return Err(new_binder_exception(
226 ExceptionCode::ILLEGAL_ARGUMENT,
227 "DiskImage contains both image and partitions.",
228 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000229 }
230
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000231 let composite_image_filenames =
232 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
233 let (image, partition_files) = make_composite_image(
234 &disk.partitions,
235 &composite_image_filenames.composite,
236 &composite_image_filenames.header,
237 &composite_image_filenames.footer,
238 )
239 .map_err(|e| {
240 error!("Failed to make composite image with config {:?}: {}", disk, e);
241 new_binder_exception(
242 ExceptionCode::SERVICE_SPECIFIC,
243 format!("Failed to make composite image: {}", e),
244 )
245 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000246
247 // Pass the file descriptors for the various partition files to crosvm when it
248 // is run.
249 indirect_files.extend(partition_files);
250
251 image
252 } else if let Some(image) = &disk.image {
253 clone_file(image)?
254 } else {
255 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000256 return Err(new_binder_exception(
257 ExceptionCode::ILLEGAL_ARGUMENT,
258 "DiskImage didn't contain image or partitions.",
259 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000260 };
261
262 Ok(DiskFile { image, writable: disk.writable })
263}
264
265/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000266fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000267 temporary_directory: &Path,
268 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000269) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000270 let id = *next_temporary_image_id;
271 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000272 CompositeImageFilenames {
273 composite: temporary_directory.join(format!("composite-{}.img", id)),
274 header: temporary_directory.join(format!("composite-{}-header.img", id)),
275 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
276 }
277}
278
279/// Filenames for a composite disk image, including header and footer partitions.
280#[derive(Clone, Debug, Eq, PartialEq)]
281struct CompositeImageFilenames {
282 /// The composite disk image itself.
283 composite: PathBuf,
284 /// The header partition image.
285 header: PathBuf,
286 /// The footer partition image.
287 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000288}
289
290/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000291fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000292 ThreadState::with_calling_sid(|sid| {
293 if let Some(sid) = sid {
294 match sid.to_str() {
295 Ok(sid) => Ok(sid.to_owned()),
296 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000297 error!("SID was not valid UTF-8: {}", e);
298 Err(new_binder_exception(
299 ExceptionCode::ILLEGAL_ARGUMENT,
300 format!("SID was not valid UTF-8: {}", e),
301 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000302 }
303 }
304 } else {
305 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000306 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000307 }
308 })
309}
310
Andrew Walbran320b5602021-03-04 16:11:12 +0000311/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000312fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000313 let uid = ThreadState::get_calling_uid();
314 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000315 if DEBUG_ALLOWED_UIDS.contains(&uid) {
316 Ok(())
317 } else {
318 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
319 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000320}
321
322/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
323#[derive(Debug)]
324struct VirtualMachine {
325 instance: Arc<VmInstance>,
326}
327
328impl VirtualMachine {
329 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
330 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000331 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000332 }
333}
334
335impl Interface for VirtualMachine {}
336
337impl IVirtualMachine for VirtualMachine {
338 fn getCid(&self) -> binder::Result<i32> {
339 Ok(self.instance.cid as i32)
340 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000341
342 fn isRunning(&self) -> binder::Result<bool> {
343 Ok(self.instance.running())
344 }
345
346 fn registerCallback(
347 &self,
348 callback: &Strong<dyn IVirtualMachineCallback>,
349 ) -> binder::Result<()> {
350 // TODO: Should this give an error if the VM is already dead?
351 self.instance.callbacks.add(callback.clone());
352 Ok(())
353 }
354}
355
356impl Drop for VirtualMachine {
357 fn drop(&mut self) {
358 debug!("Dropping {:?}", self);
359 self.instance.kill();
360 }
361}
362
363/// A set of Binders to be called back in response to various events on the VM, such as when it
364/// dies.
365#[derive(Debug, Default)]
366pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
367
368impl VirtualMachineCallbacks {
369 /// Call all registered callbacks to say that the VM has died.
370 pub fn callback_on_died(&self, cid: Cid) {
371 let callbacks = &*self.0.lock().unwrap();
372 for callback in callbacks {
373 if let Err(e) = callback.onDied(cid as i32) {
374 error!("Error calling callback: {}", e);
375 }
376 }
377 }
378
379 /// Add a new callback to the set.
380 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
381 self.0.lock().unwrap().push(callback);
382 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000383}
384
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000385/// The mutable state of the VirtualizationService. There should only be one instance of this
386/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000387#[derive(Debug)]
388struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000389 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000390 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000391
392 /// The VMs which have been started. When VMs are started a weak reference is added to this list
393 /// while a strong reference is returned to the caller over Binder. Once all copies of the
394 /// Binder client are dropped the weak reference here will become invalid, and will be removed
395 /// from the list opportunistically the next time `add_vm` is called.
396 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000397
398 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
399 /// This is only used for debugging purposes.
400 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000401}
402
403impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000404 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000405 fn vms(&self) -> Vec<Arc<VmInstance>> {
406 // Attempt to upgrade the weak pointers to strong pointers.
407 self.vms.iter().filter_map(Weak::upgrade).collect()
408 }
409
410 /// Add a new VM to the list.
411 fn add_vm(&mut self, vm: Weak<VmInstance>) {
412 // Garbage collect any entries from the stored list which no longer exist.
413 self.vms.retain(|vm| vm.strong_count() > 0);
414
415 // Actually add the new VM.
416 self.vms.push(vm);
417 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000418
419 /// Store a strong VM reference.
420 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
421 self.debug_held_vms.push(vm);
422 }
423
424 /// Retrieve and remove a strong VM reference.
425 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
426 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
427 Some(self.debug_held_vms.swap_remove(pos))
428 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000429
430 /// Get the next available CID, or an error if we have run out.
431 fn allocate_cid(&mut self) -> binder::Result<Cid> {
432 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
433 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000434 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000435 Ok(cid)
436 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000437}
438
439impl Default for State {
440 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000441 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000442 }
443}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000444
445/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
446fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
447 option.as_ref().map(|t| t.as_ref())
448}
449
450/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000451fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
452 file.as_ref().try_clone().map_err(|e| {
453 new_binder_exception(
454 ExceptionCode::BAD_PARCELABLE,
455 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
456 )
457 })
458}
459
460/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
461fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
462 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000463}