blob: 7b63917254b3d42c8850d56bd0601ea4e4f4cf43 [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 Walbran4de28782021-04-13 14:51:43 +000029 self, BinderFeatures, Interface, ParcelFileDescriptor, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000030};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000031use command_fds::FdMapping;
32use log::{debug, error, warn};
Andrew Walbrandff3b942021-06-09 15:20:36 +000033use std::convert::TryInto;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000034use std::fs::{File, create_dir};
Andrew Walbrandff3b942021-06-09 15:20:36 +000035use std::io::{Seek, SeekFrom, Write};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000036use 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!(
83 "Failed to create temporary directory {:?} for VM files: {:?}",
84 temporary_directory, e
85 );
86 StatusCode::UNKNOWN_ERROR
87 })?;
88
89 // Assemble disk images if needed.
90 let disks = config
91 .disks
92 .iter()
93 .map(|disk| {
94 assemble_disk_image(
95 disk,
96 &temporary_directory,
97 &mut next_temporary_image_id,
98 &mut indirect_files,
99 )
100 })
101 .collect::<Result<Vec<DiskFile>, _>>()?;
102
103 // Actually start the VM.
104 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000105 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 bootloader: as_asref(&config.bootloader),
107 kernel: as_asref(&config.kernel),
108 initrd: as_asref(&config.initrd),
109 disks,
110 params: config.params.to_owned(),
111 };
112 let composite_disk_mappings: Vec<_> = indirect_files
113 .iter()
114 .map(|file| {
115 let fd = file.as_raw_fd();
116 FdMapping { parent_fd: fd, child_fd: fd }
117 })
118 .collect();
119 let instance = VmInstance::start(
120 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000121 log_fd,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000122 &composite_disk_mappings,
123 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000124 requester_uid,
125 requester_sid,
126 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000127 )
128 .map_err(|e| {
129 error!("Failed to start VM with config {:?}: {:?}", config, e);
130 StatusCode::UNKNOWN_ERROR
131 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000132 state.add_vm(Arc::downgrade(&instance));
133 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000134 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000135
Andrew Walbrandff3b942021-06-09 15:20:36 +0000136 /// Initialise an empty partition image of the given size to be used as a writable partition.
137 fn initializeWritablePartition(
138 &self,
139 image_fd: &ParcelFileDescriptor,
140 size: i64,
141 ) -> binder::Result<()> {
142 let size: u64 = size.try_into().map_err(|e| {
143 error!("Invalid size {}: {}", size, e);
144 StatusCode::BAD_VALUE
145 })?;
146 let mut image = clone_file(image_fd)?;
147
148 // TODO: create a QCOW2 image instead, like `crosvm create_qcow2`, once `mk_cdisk` supports
149 // it (b/189211641).
150 if size > 0 {
151 // Extend the file to the given size by seeking to the size we want and writing a single
152 // 0 byte there.
153 image.seek(SeekFrom::Start(size - 1)).map_err(|e| {
154 error!("Failed to seek to desired size of image file ({}): {}.", size, e);
155 StatusCode::UNKNOWN_ERROR
156 })?;
157 image.write_all(&[0]).map_err(|e| {
158 error!("Failed to write 0 to image file: {}.", e);
159 StatusCode::UNKNOWN_ERROR
160 })?;
161 }
162
163 Ok(())
164 }
165
Andrew Walbran320b5602021-03-04 16:11:12 +0000166 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
167 /// and as such is only permitted from the shell user.
168 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
169 if !debug_access_allowed() {
170 return Err(StatusCode::PERMISSION_DENIED.into());
171 }
172
173 let state = &mut *self.state.lock().unwrap();
174 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000175 let cids = vms
176 .into_iter()
177 .map(|vm| VirtualMachineDebugInfo {
178 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000179 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000180 requesterUid: vm.requester_uid as i32,
181 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000182 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000183 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000184 })
185 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000186 Ok(cids)
187 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000188
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000189 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
190 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000191 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000192 if !debug_access_allowed() {
193 return Err(StatusCode::PERMISSION_DENIED.into());
194 }
195
David Brazdil3c2ddef2021-03-18 13:09:57 +0000196 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000197 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000198 Ok(())
199 }
200
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000201 /// 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 Brazdil3c2ddef2021-03-18 13:09:57 +0000204 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
205 if !debug_access_allowed() {
206 return Err(StatusCode::PERMISSION_DENIED.into());
207 }
208
209 let state = &mut *self.state.lock().unwrap();
210 Ok(state.debug_drop_vm(cid))
211 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000212}
213
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000214/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
215///
216/// This may involve assembling a composite disk from a set of partition images.
217fn assemble_disk_image(
218 disk: &DiskImage,
219 temporary_directory: &Path,
220 next_temporary_image_id: &mut u64,
221 indirect_files: &mut Vec<File>,
222) -> Result<DiskFile, StatusCode> {
223 let image = if !disk.partitions.is_empty() {
224 if disk.image.is_some() {
225 warn!("DiskImage {:?} contains both image and partitions.", disk);
226 return Err(StatusCode::BAD_VALUE);
227 }
228
229 let composite_image_filename =
230 make_composite_image_filename(temporary_directory, next_temporary_image_id);
231 let (image, partition_files) =
232 make_composite_image(&disk.partitions, &composite_image_filename).map_err(|e| {
233 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
234 StatusCode::UNKNOWN_ERROR
235 })?;
236
237 // Pass the file descriptors for the various partition files to crosvm when it
238 // is run.
239 indirect_files.extend(partition_files);
240
241 image
242 } else if let Some(image) = &disk.image {
243 clone_file(image)?
244 } else {
245 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
246 return Err(StatusCode::BAD_VALUE);
247 };
248
249 Ok(DiskFile { image, writable: disk.writable })
250}
251
252/// Generates a unique filename to use for a composite disk image.
253fn make_composite_image_filename(
254 temporary_directory: &Path,
255 next_temporary_image_id: &mut u64,
256) -> PathBuf {
257 let id = *next_temporary_image_id;
258 *next_temporary_image_id += 1;
259 temporary_directory.join(format!("composite-{}.img", id))
260}
261
262/// Gets the calling SID of the current Binder thread.
263fn get_calling_sid() -> Result<String, StatusCode> {
264 ThreadState::with_calling_sid(|sid| {
265 if let Some(sid) = sid {
266 match sid.to_str() {
267 Ok(sid) => Ok(sid.to_owned()),
268 Err(e) => {
269 error!("SID was not valid UTF-8: {:?}", e);
270 Err(StatusCode::BAD_VALUE)
271 }
272 }
273 } else {
274 error!("Missing SID on startVm");
275 Err(StatusCode::UNKNOWN_ERROR)
276 }
277 })
278}
279
Andrew Walbran320b5602021-03-04 16:11:12 +0000280/// Check whether the caller of the current Binder method is allowed to call debug methods.
281fn debug_access_allowed() -> bool {
282 let uid = ThreadState::get_calling_uid();
283 log::trace!("Debug method call from UID {}.", uid);
284 DEBUG_ALLOWED_UIDS.contains(&uid)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000285}
286
287/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
288#[derive(Debug)]
289struct VirtualMachine {
290 instance: Arc<VmInstance>,
291}
292
293impl VirtualMachine {
294 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
295 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000296 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000297 }
298}
299
300impl Interface for VirtualMachine {}
301
302impl IVirtualMachine for VirtualMachine {
303 fn getCid(&self) -> binder::Result<i32> {
304 Ok(self.instance.cid as i32)
305 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000306
307 fn isRunning(&self) -> binder::Result<bool> {
308 Ok(self.instance.running())
309 }
310
311 fn registerCallback(
312 &self,
313 callback: &Strong<dyn IVirtualMachineCallback>,
314 ) -> binder::Result<()> {
315 // TODO: Should this give an error if the VM is already dead?
316 self.instance.callbacks.add(callback.clone());
317 Ok(())
318 }
319}
320
321impl Drop for VirtualMachine {
322 fn drop(&mut self) {
323 debug!("Dropping {:?}", self);
324 self.instance.kill();
325 }
326}
327
328/// A set of Binders to be called back in response to various events on the VM, such as when it
329/// dies.
330#[derive(Debug, Default)]
331pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
332
333impl VirtualMachineCallbacks {
334 /// Call all registered callbacks to say that the VM has died.
335 pub fn callback_on_died(&self, cid: Cid) {
336 let callbacks = &*self.0.lock().unwrap();
337 for callback in callbacks {
338 if let Err(e) = callback.onDied(cid as i32) {
339 error!("Error calling callback: {}", e);
340 }
341 }
342 }
343
344 /// Add a new callback to the set.
345 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
346 self.0.lock().unwrap().push(callback);
347 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000348}
349
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000350/// The mutable state of the VirtualizationService. There should only be one instance of this
351/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000352#[derive(Debug)]
353struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000354 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000355 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000356
357 /// The VMs which have been started. When VMs are started a weak reference is added to this list
358 /// while a strong reference is returned to the caller over Binder. Once all copies of the
359 /// Binder client are dropped the weak reference here will become invalid, and will be removed
360 /// from the list opportunistically the next time `add_vm` is called.
361 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000362
363 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
364 /// This is only used for debugging purposes.
365 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000366}
367
368impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000369 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000370 fn vms(&self) -> Vec<Arc<VmInstance>> {
371 // Attempt to upgrade the weak pointers to strong pointers.
372 self.vms.iter().filter_map(Weak::upgrade).collect()
373 }
374
375 /// Add a new VM to the list.
376 fn add_vm(&mut self, vm: Weak<VmInstance>) {
377 // Garbage collect any entries from the stored list which no longer exist.
378 self.vms.retain(|vm| vm.strong_count() > 0);
379
380 // Actually add the new VM.
381 self.vms.push(vm);
382 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000383
384 /// Store a strong VM reference.
385 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
386 self.debug_held_vms.push(vm);
387 }
388
389 /// Retrieve and remove a strong VM reference.
390 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
391 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
392 Some(self.debug_held_vms.swap_remove(pos))
393 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000394
395 /// Get the next available CID, or an error if we have run out.
396 fn allocate_cid(&mut self) -> binder::Result<Cid> {
397 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
398 let cid = self.next_cid;
399 self.next_cid = self.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
400 Ok(cid)
401 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000402}
403
404impl Default for State {
405 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000406 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000407 }
408}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000409
410/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
411fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
412 option.as_ref().map(|t| t.as_ref())
413}
414
415/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
416fn clone_file(file: &ParcelFileDescriptor) -> Result<File, StatusCode> {
417 file.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)
418}