blob: c2953883356da86b1254b5a251d76fe16a919c8b [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};
33use std::fs::{File, create_dir};
34use std::os::unix::io::AsRawFd;
35use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000036use std::sync::{Arc, Mutex, Weak};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000037
Andrew Walbranf6bf6862021-05-21 12:41:13 +000038pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000039
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000040/// Directory in which to write disk image files used while running VMs.
41const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
42
Andrew Walbran320b5602021-03-04 16:11:12 +000043// 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.
45const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
46
Andrew Walbranf6bf6862021-05-21 12:41:13 +000047/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000048#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000049pub struct VirtualizationService {
Andrew Walbran9c01baa2021-03-08 18:23:50 +000050 state: Mutex<State>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051}
52
Andrew Walbranf6bf6862021-05-21 12:41:13 +000053impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054
Andrew Walbranf6bf6862021-05-21 12:41:13 +000055impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000056 /// 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 Walbrana89fc132021-03-17 17:08:36 +000059 fn startVm(
60 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000061 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000062 log_fd: Option<&ParcelFileDescriptor>,
63 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000064 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000065 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000066 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000067 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000068 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000069 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000070
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 Walbran02034492021-04-13 15:05:07 +0000103 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000104 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 Walbran02034492021-04-13 15:05:07 +0000119 log_fd,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000120 &composite_disk_mappings,
121 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000122 requester_uid,
123 requester_sid,
124 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000125 )
126 .map_err(|e| {
127 error!("Failed to start VM with config {:?}: {:?}", config, e);
128 StatusCode::UNKNOWN_ERROR
129 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000130 state.add_vm(Arc::downgrade(&instance));
131 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000133
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 Walbranf6a1eb92021-04-01 11:16:02 +0000143 let cids = vms
144 .into_iter()
145 .map(|vm| VirtualMachineDebugInfo {
146 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000147 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000148 requesterUid: vm.requester_uid as i32,
149 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000150 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000151 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000152 })
153 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000154 Ok(cids)
155 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000156
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000157 /// 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 Homescu1415c132021-03-24 02:39:55 +0000159 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000160 if !debug_access_allowed() {
161 return Err(StatusCode::PERMISSION_DENIED.into());
162 }
163
David Brazdil3c2ddef2021-03-18 13:09:57 +0000164 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000165 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000166 Ok(())
167 }
168
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000169 /// 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 Brazdil3c2ddef2021-03-18 13:09:57 +0000172 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 Walbran320b5602021-03-04 16:11:12 +0000180}
181
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000182/// 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.
185fn 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.
221fn 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.
231fn 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 Walbran320b5602021-03-04 16:11:12 +0000248/// Check whether the caller of the current Binder method is allowed to call debug methods.
249fn 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 Walbrand6dce6f2021-03-05 16:39:08 +0000253}
254
255/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
256#[derive(Debug)]
257struct VirtualMachine {
258 instance: Arc<VmInstance>,
259}
260
261impl VirtualMachine {
262 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
263 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000264 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000265 }
266}
267
268impl Interface for VirtualMachine {}
269
270impl IVirtualMachine for VirtualMachine {
271 fn getCid(&self) -> binder::Result<i32> {
272 Ok(self.instance.cid as i32)
273 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000274
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
289impl 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)]
299pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
300
301impl 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 Walbrand6dce6f2021-03-05 16:39:08 +0000316}
317
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000318/// The mutable state of the VirtualizationService. There should only be one instance of this
319/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000320#[derive(Debug)]
321struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000322 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000323 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000324
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 Brazdil3c2ddef2021-03-18 13:09:57 +0000330
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 Walbran320b5602021-03-04 16:11:12 +0000334}
335
336impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000337 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000338 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 Brazdil3c2ddef2021-03-18 13:09:57 +0000351
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 Walbrandae07162021-03-12 17:05:20 +0000362
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 Walbrand6dce6f2021-03-05 16:39:08 +0000370}
371
372impl Default for State {
373 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000374 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000375 }
376}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000377
378/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
379fn 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.
384fn clone_file(file: &ParcelFileDescriptor) -> Result<File, StatusCode> {
385 file.as_ref().try_clone().map_err(|_| StatusCode::UNKNOWN_ERROR)
386}