blob: bc8df9ddd622be9615f10a8d0a7f23d4487b3329 [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;
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 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!(
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<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000142 let size = size.try_into().map_err(|e| {
Andrew Walbrandff3b942021-06-09 15:20:36 +0000143 error!("Invalid size {}: {}", size, e);
144 StatusCode::BAD_VALUE
145 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000146 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000147
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000148 QcowFile::new(image, size).map_err(|e| {
149 error!("Failed to create QCOW2 image: {}", e);
150 StatusCode::UNKNOWN_ERROR
151 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000152
153 Ok(())
154 }
155
Andrew Walbran320b5602021-03-04 16:11:12 +0000156 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
157 /// and as such is only permitted from the shell user.
158 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
159 if !debug_access_allowed() {
160 return Err(StatusCode::PERMISSION_DENIED.into());
161 }
162
163 let state = &mut *self.state.lock().unwrap();
164 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000165 let cids = vms
166 .into_iter()
167 .map(|vm| VirtualMachineDebugInfo {
168 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000169 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000170 requesterUid: vm.requester_uid as i32,
171 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000172 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000173 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000174 })
175 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000176 Ok(cids)
177 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000178
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000179 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
180 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000181 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000182 if !debug_access_allowed() {
183 return Err(StatusCode::PERMISSION_DENIED.into());
184 }
185
David Brazdil3c2ddef2021-03-18 13:09:57 +0000186 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000187 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000188 Ok(())
189 }
190
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000191 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
192 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
193 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000194 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
195 if !debug_access_allowed() {
196 return Err(StatusCode::PERMISSION_DENIED.into());
197 }
198
199 let state = &mut *self.state.lock().unwrap();
200 Ok(state.debug_drop_vm(cid))
201 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000202}
203
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000204/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
205///
206/// This may involve assembling a composite disk from a set of partition images.
207fn assemble_disk_image(
208 disk: &DiskImage,
209 temporary_directory: &Path,
210 next_temporary_image_id: &mut u64,
211 indirect_files: &mut Vec<File>,
212) -> Result<DiskFile, StatusCode> {
213 let image = if !disk.partitions.is_empty() {
214 if disk.image.is_some() {
215 warn!("DiskImage {:?} contains both image and partitions.", disk);
216 return Err(StatusCode::BAD_VALUE);
217 }
218
219 let composite_image_filename =
220 make_composite_image_filename(temporary_directory, next_temporary_image_id);
221 let (image, partition_files) =
222 make_composite_image(&disk.partitions, &composite_image_filename).map_err(|e| {
223 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
224 StatusCode::UNKNOWN_ERROR
225 })?;
226
227 // Pass the file descriptors for the various partition files to crosvm when it
228 // is run.
229 indirect_files.extend(partition_files);
230
231 image
232 } else if let Some(image) = &disk.image {
233 clone_file(image)?
234 } else {
235 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
236 return Err(StatusCode::BAD_VALUE);
237 };
238
239 Ok(DiskFile { image, writable: disk.writable })
240}
241
242/// Generates a unique filename to use for a composite disk image.
243fn make_composite_image_filename(
244 temporary_directory: &Path,
245 next_temporary_image_id: &mut u64,
246) -> PathBuf {
247 let id = *next_temporary_image_id;
248 *next_temporary_image_id += 1;
249 temporary_directory.join(format!("composite-{}.img", id))
250}
251
252/// Gets the calling SID of the current Binder thread.
253fn get_calling_sid() -> Result<String, StatusCode> {
254 ThreadState::with_calling_sid(|sid| {
255 if let Some(sid) = sid {
256 match sid.to_str() {
257 Ok(sid) => Ok(sid.to_owned()),
258 Err(e) => {
259 error!("SID was not valid UTF-8: {:?}", e);
260 Err(StatusCode::BAD_VALUE)
261 }
262 }
263 } else {
264 error!("Missing SID on startVm");
265 Err(StatusCode::UNKNOWN_ERROR)
266 }
267 })
268}
269
Andrew Walbran320b5602021-03-04 16:11:12 +0000270/// Check whether the caller of the current Binder method is allowed to call debug methods.
271fn debug_access_allowed() -> bool {
272 let uid = ThreadState::get_calling_uid();
273 log::trace!("Debug method call from UID {}.", uid);
274 DEBUG_ALLOWED_UIDS.contains(&uid)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000275}
276
277/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
278#[derive(Debug)]
279struct VirtualMachine {
280 instance: Arc<VmInstance>,
281}
282
283impl VirtualMachine {
284 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
285 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000286 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000287 }
288}
289
290impl Interface for VirtualMachine {}
291
292impl IVirtualMachine for VirtualMachine {
293 fn getCid(&self) -> binder::Result<i32> {
294 Ok(self.instance.cid as i32)
295 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000296
297 fn isRunning(&self) -> binder::Result<bool> {
298 Ok(self.instance.running())
299 }
300
301 fn registerCallback(
302 &self,
303 callback: &Strong<dyn IVirtualMachineCallback>,
304 ) -> binder::Result<()> {
305 // TODO: Should this give an error if the VM is already dead?
306 self.instance.callbacks.add(callback.clone());
307 Ok(())
308 }
309}
310
311impl Drop for VirtualMachine {
312 fn drop(&mut self) {
313 debug!("Dropping {:?}", self);
314 self.instance.kill();
315 }
316}
317
318/// A set of Binders to be called back in response to various events on the VM, such as when it
319/// dies.
320#[derive(Debug, Default)]
321pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
322
323impl VirtualMachineCallbacks {
324 /// Call all registered callbacks to say that the VM has died.
325 pub fn callback_on_died(&self, cid: Cid) {
326 let callbacks = &*self.0.lock().unwrap();
327 for callback in callbacks {
328 if let Err(e) = callback.onDied(cid as i32) {
329 error!("Error calling callback: {}", e);
330 }
331 }
332 }
333
334 /// Add a new callback to the set.
335 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
336 self.0.lock().unwrap().push(callback);
337 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000338}
339
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000340/// The mutable state of the VirtualizationService. There should only be one instance of this
341/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000342#[derive(Debug)]
343struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000344 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000345 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000346
347 /// The VMs which have been started. When VMs are started a weak reference is added to this list
348 /// while a strong reference is returned to the caller over Binder. Once all copies of the
349 /// Binder client are dropped the weak reference here will become invalid, and will be removed
350 /// from the list opportunistically the next time `add_vm` is called.
351 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000352
353 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
354 /// This is only used for debugging purposes.
355 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000356}
357
358impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000359 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000360 fn vms(&self) -> Vec<Arc<VmInstance>> {
361 // Attempt to upgrade the weak pointers to strong pointers.
362 self.vms.iter().filter_map(Weak::upgrade).collect()
363 }
364
365 /// Add a new VM to the list.
366 fn add_vm(&mut self, vm: Weak<VmInstance>) {
367 // Garbage collect any entries from the stored list which no longer exist.
368 self.vms.retain(|vm| vm.strong_count() > 0);
369
370 // Actually add the new VM.
371 self.vms.push(vm);
372 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000373
374 /// Store a strong VM reference.
375 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
376 self.debug_held_vms.push(vm);
377 }
378
379 /// Retrieve and remove a strong VM reference.
380 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
381 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
382 Some(self.debug_held_vms.swap_remove(pos))
383 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000384
385 /// Get the next available CID, or an error if we have run out.
386 fn allocate_cid(&mut self) -> binder::Result<Cid> {
387 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
388 let cid = self.next_cid;
389 self.next_cid = self.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
390 Ok(cid)
391 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000392}
393
394impl Default for State {
395 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000396 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000397 }
398}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000399
400/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
401fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
402 option.as_ref().map(|t| t.as_ref())
403}
404
405/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
406fn clone_file(file: &ParcelFileDescriptor) -> Result<File, StatusCode> {
407 file.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)
408}