blob: ff5298c39b8846ba638d224967c29e7bc287dd41 [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 Walbrancc0db522021-07-12 17:03:42 +000019use crate::payload::add_microdroid_images;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000020use crate::{Cid, FIRST_GUEST_CID};
Jooyung Han21e9b922021-06-26 04:14:16 +090021
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000025use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000026 BnVirtualMachine, IVirtualMachine,
27};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
Jooyung Han21e9b922021-06-26 04:14:16 +090029use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
30 VirtualMachineAppConfig::VirtualMachineAppConfig,
31 VirtualMachineConfig::VirtualMachineConfig,
32 VirtualMachineRawConfig::VirtualMachineRawConfig,
33};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000034use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
Jiyong Park9dd389e2021-08-23 20:42:59 +090035use android_system_virtualizationservice::aidl::android::system::virtualizationservice::PartitionType::PartitionType;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000036use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000037 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000038};
Jooyung Han95884632021-07-06 22:27:54 +090039use anyhow::{bail, Context, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000040use disk::QcowFile;
Jiyong Park0a248432021-08-20 23:32:39 +090041use idsig::{V4Signature, HashAlgorithm};
Jiyong Park8611a6c2021-07-09 18:17:44 +090042use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000043use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000044use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000045use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090046use std::fs::{File, OpenOptions, create_dir};
Jiyong Park9dd389e2021-08-23 20:42:59 +090047use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000048use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090049use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000050use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000051use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000052use vmconfig::VmConfig;
Jiyong Park8611a6c2021-07-09 18:17:44 +090053use vsock::{VsockListener, SockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090054use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000055
Andrew Walbranf6bf6862021-05-21 12:41:13 +000056pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000057
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000059pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000060
Jiyong Park8611a6c2021-07-09 18:17:44 +090061/// The CID representing the host VM
62const VMADDR_CID_HOST: u32 = 2;
63
64/// Port number that virtualizationservice listens on connections from the guest VMs for the
65/// payload output
66const PORT_VIRT_SERVICE: u32 = 3000;
67
Jooyung Han95884632021-07-06 22:27:54 +090068/// The size of zero.img.
69/// Gaps in composite disk images are filled with a shared zero.img.
70const ZERO_FILLER_SIZE: u64 = 4096;
71
Jiyong Park9dd389e2021-08-23 20:42:59 +090072/// Magic string for the instance image
73const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
74
75/// Version of the instance image format
76const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
77
Andrew Walbranf6bf6862021-05-21 12:41:13 +000078/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090079#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000080pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090081 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000082}
83
Andrew Walbranf6bf6862021-05-21 12:41:13 +000084impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000085
Andrew Walbranf6bf6862021-05-21 12:41:13 +000086impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087 /// Create and start a new VM with the given configuration, assigning it the next available CID.
88 ///
89 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000090 fn startVm(
91 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000092 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000093 log_fd: Option<&ParcelFileDescriptor>,
94 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090095 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000097 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000098 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000099 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000100 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +0000101 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102
103 // Counter to generate unique IDs for temporary image files.
104 let mut next_temporary_image_id = 0;
105 // Files which are referred to from composite images. These must be mapped to the crosvm
106 // child process, and not closed before it is started.
107 let mut indirect_files = vec![];
108
109 // Make directory for temporary files.
110 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
111 create_dir(&temporary_directory).map_err(|e| {
112 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000113 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000114 temporary_directory, e
115 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000116 new_binder_exception(
117 ExceptionCode::SERVICE_SPECIFIC,
118 format!(
119 "Failed to create temporary directory {:?} for VM files: {}",
120 temporary_directory, e
121 ),
122 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000123 })?;
124
Jooyung Han21e9b922021-06-26 04:14:16 +0900125 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900126 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900127 load_app_config(config, &temporary_directory).map_err(|e| {
128 error!("Failed to load app config from {}: {}", &config.configPath, e);
129 new_binder_exception(
130 ExceptionCode::SERVICE_SPECIFIC,
131 format!("Failed to load app config from {}: {}", &config.configPath, e),
132 )
133 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900134 ),
135 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900136 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900137 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900138
Jooyung Han95884632021-07-06 22:27:54 +0900139 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000140 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900141 error!("Failed to make composite image: {}", e);
142 new_binder_exception(
143 ExceptionCode::SERVICE_SPECIFIC,
144 format!("Failed to make composite image: {}", e),
145 )
146 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900147
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 // Assemble disk images if needed.
149 let disks = config
150 .disks
151 .iter()
152 .map(|disk| {
153 assemble_disk_image(
154 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900155 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156 &temporary_directory,
157 &mut next_temporary_image_id,
158 &mut indirect_files,
159 )
160 })
161 .collect::<Result<Vec<DiskFile>, _>>()?;
162
163 // Actually start the VM.
164 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000165 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000166 bootloader: as_asref(&config.bootloader),
167 kernel: as_asref(&config.kernel),
168 initrd: as_asref(&config.initrd),
169 disks,
170 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000171 protected: config.protectedVm,
172 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000173 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000174 let composite_disk_fds: Vec<_> =
175 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000176 let instance = VmInstance::start(
177 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000178 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000179 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000180 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000181 requester_uid,
182 requester_sid,
183 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000184 )
185 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000186 error!("Failed to start VM with config {:?}: {}", config, e);
187 new_binder_exception(
188 ExceptionCode::SERVICE_SPECIFIC,
189 format!("Failed to start VM: {}", e),
190 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000191 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000192 state.add_vm(Arc::downgrade(&instance));
193 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000194 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000195
Andrew Walbrandff3b942021-06-09 15:20:36 +0000196 /// Initialise an empty partition image of the given size to be used as a writable partition.
197 fn initializeWritablePartition(
198 &self,
199 image_fd: &ParcelFileDescriptor,
200 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900201 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000202 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900203 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000204 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000205 new_binder_exception(
206 ExceptionCode::ILLEGAL_ARGUMENT,
207 format!("Invalid size {}: {}", size, e),
208 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000209 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000210 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000211
Jiyong Park9dd389e2021-08-23 20:42:59 +0900212 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000213 new_binder_exception(
214 ExceptionCode::SERVICE_SPECIFIC,
215 format!("Failed to create QCOW2 image: {}", e),
216 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000217 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000218
Jiyong Park9dd389e2021-08-23 20:42:59 +0900219 match partition_type {
220 PartitionType::RAW => Ok(()),
221 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
222 _ => Err(Error::new(
223 ErrorKind::Unsupported,
224 format!("Unsupported partition type {:?}", partition_type),
225 )),
226 }
227 .map_err(|e| {
228 new_binder_exception(
229 ExceptionCode::SERVICE_SPECIFIC,
230 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
231 )
232 })?;
233
Andrew Walbrandff3b942021-06-09 15:20:36 +0000234 Ok(())
235 }
236
Jiyong Park0a248432021-08-20 23:32:39 +0900237 /// Creates or update the idsig file by digesting the input APK file.
238 fn createOrUpdateIdsigFile(
239 &self,
240 input_fd: &ParcelFileDescriptor,
241 idsig_fd: &ParcelFileDescriptor,
242 ) -> binder::Result<()> {
243 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
244 // idsig_fd is different from APK digest in input_fd
245
246 let mut input = clone_file(input_fd)?;
247 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
248
249 let mut output = clone_file(idsig_fd)?;
250 output.set_len(0).unwrap();
251 sig.write_into(&mut output).unwrap();
252 Ok(())
253 }
254
Andrew Walbran320b5602021-03-04 16:11:12 +0000255 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
256 /// and as such is only permitted from the shell user.
257 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000258 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000259
260 let state = &mut *self.state.lock().unwrap();
261 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000262 let cids = vms
263 .into_iter()
264 .map(|vm| VirtualMachineDebugInfo {
265 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000266 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000267 requesterUid: vm.requester_uid as i32,
268 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000269 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000270 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000271 })
272 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000273 Ok(cids)
274 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000275
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000276 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
277 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000278 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000279 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000280
David Brazdil3c2ddef2021-03-18 13:09:57 +0000281 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000282 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000283 Ok(())
284 }
285
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000286 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
287 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
288 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000289 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000290 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000291
292 let state = &mut *self.state.lock().unwrap();
293 Ok(state.debug_drop_vm(cid))
294 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000295}
296
Jiyong Park8611a6c2021-07-09 18:17:44 +0900297impl VirtualizationService {
298 pub fn init() -> VirtualizationService {
299 let service = VirtualizationService::default();
300 let state = service.state.clone(); // reference to state (not the state itself) is copied
301 std::thread::spawn(move || {
302 handle_connection_from_vm(state).unwrap();
303 });
304 service
305 }
306}
307
308/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
309/// client via the callback (if registered).
310fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
311 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
312 for stream in listener.incoming() {
313 let stream = match stream {
314 Err(e) => {
315 warn!("invalid incoming connection: {}", e);
316 continue;
317 }
318 Ok(s) => s,
319 };
320 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
321 let cid = addr.cid();
322 let port = addr.port();
323 info!("connected from cid={}, port={}", cid, port);
324 if cid < FIRST_GUEST_CID {
325 warn!("connection is not from a guest VM");
326 continue;
327 }
328 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
329 vm.callbacks.notify_payload_started(cid, stream);
330 }
331 }
332 }
333 Ok(())
334}
335
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000336fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900337 let file = OpenOptions::new()
338 .create_new(true)
339 .read(true)
340 .write(true)
341 .open(zero_filler_path)
342 .with_context(|| "Failed to create zero.img")?;
343 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000344 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900345}
346
Jiyong Park9dd389e2021-08-23 20:42:59 +0900347fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
348 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
349 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
350 part.flush()
351}
352
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000353/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
354///
355/// This may involve assembling a composite disk from a set of partition images.
356fn assemble_disk_image(
357 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900358 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000359 temporary_directory: &Path,
360 next_temporary_image_id: &mut u64,
361 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000362) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000363 let image = if !disk.partitions.is_empty() {
364 if disk.image.is_some() {
365 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000366 return Err(new_binder_exception(
367 ExceptionCode::ILLEGAL_ARGUMENT,
368 "DiskImage contains both image and partitions.",
369 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000370 }
371
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000372 let composite_image_filenames =
373 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
374 let (image, partition_files) = make_composite_image(
375 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900376 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000377 &composite_image_filenames.composite,
378 &composite_image_filenames.header,
379 &composite_image_filenames.footer,
380 )
381 .map_err(|e| {
382 error!("Failed to make composite image with config {:?}: {}", disk, e);
383 new_binder_exception(
384 ExceptionCode::SERVICE_SPECIFIC,
385 format!("Failed to make composite image: {}", e),
386 )
387 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000388
389 // Pass the file descriptors for the various partition files to crosvm when it
390 // is run.
391 indirect_files.extend(partition_files);
392
393 image
394 } else if let Some(image) = &disk.image {
395 clone_file(image)?
396 } else {
397 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000398 return Err(new_binder_exception(
399 ExceptionCode::ILLEGAL_ARGUMENT,
400 "DiskImage didn't contain image or partitions.",
401 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000402 };
403
404 Ok(DiskFile { image, writable: disk.writable })
405}
406
Jooyung Han21e9b922021-06-26 04:14:16 +0900407fn load_app_config(
408 config: &VirtualMachineAppConfig,
409 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900410) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000411 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
412 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900413 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900414 let config_path = &config.configPath;
415
Andrew Walbrancc0db522021-07-12 17:03:42 +0000416 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900417 let config_file = apk_zip.by_name(config_path)?;
418 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
419
420 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000421
Jooyung Han35edb8f2021-07-01 16:17:16 +0900422 // For now, the only supported "os" value is "microdroid"
423 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000424 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900425 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000426
427 // It is safe to construct a filename based on the os_name because we've already checked that it
428 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900429 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
430 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000431 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900432
Andrew Walbrancc045902021-07-27 16:06:17 +0000433 if config.memoryMib > 0 {
434 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000435 }
436
Andrew Walbrancc0db522021-07-12 17:03:42 +0000437 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900438 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000439 let apexes = vm_payload_config.apexes.clone();
440 add_microdroid_images(
441 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900442 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000443 apk_file,
444 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900445 instance_file,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000446 apexes,
447 &mut vm_config,
448 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900449 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900450
Andrew Walbrancc0db522021-07-12 17:03:42 +0000451 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900452}
453
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000454/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000455fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000456 temporary_directory: &Path,
457 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000458) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000459 let id = *next_temporary_image_id;
460 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000461 CompositeImageFilenames {
462 composite: temporary_directory.join(format!("composite-{}.img", id)),
463 header: temporary_directory.join(format!("composite-{}-header.img", id)),
464 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
465 }
466}
467
468/// Filenames for a composite disk image, including header and footer partitions.
469#[derive(Clone, Debug, Eq, PartialEq)]
470struct CompositeImageFilenames {
471 /// The composite disk image itself.
472 composite: PathBuf,
473 /// The header partition image.
474 header: PathBuf,
475 /// The footer partition image.
476 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000477}
478
479/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000480fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000481 ThreadState::with_calling_sid(|sid| {
482 if let Some(sid) = sid {
483 match sid.to_str() {
484 Ok(sid) => Ok(sid.to_owned()),
485 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000486 error!("SID was not valid UTF-8: {}", e);
487 Err(new_binder_exception(
488 ExceptionCode::ILLEGAL_ARGUMENT,
489 format!("SID was not valid UTF-8: {}", e),
490 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000491 }
492 }
493 } else {
494 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000495 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000496 }
497 })
498}
499
Jiyong Park753553b2021-07-12 21:21:09 +0900500/// Checks whether the caller has a specific permission
501fn check_permission(perm: &str) -> binder::Result<()> {
502 let calling_pid = ThreadState::get_calling_pid();
503 let calling_uid = ThreadState::get_calling_uid();
504 // Root can do anything
505 if calling_uid == 0 {
506 return Ok(());
507 }
508 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
509 binder::get_interface("permission")?;
510 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000511 Ok(())
512 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900513 Err(new_binder_exception(
514 ExceptionCode::SECURITY,
515 format!("does not have the {} permission", perm),
516 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000517 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000518}
519
Jiyong Park753553b2021-07-12 21:21:09 +0900520/// Check whether the caller of the current Binder method is allowed to call debug methods.
521fn check_debug_access() -> binder::Result<()> {
522 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
523}
524
525/// Check whether the caller of the current Binder method is allowed to manage VMs
526fn check_manage_access() -> binder::Result<()> {
527 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
528}
529
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000530/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
531#[derive(Debug)]
532struct VirtualMachine {
533 instance: Arc<VmInstance>,
534}
535
536impl VirtualMachine {
537 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
538 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000539 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000540 }
541}
542
543impl Interface for VirtualMachine {}
544
545impl IVirtualMachine for VirtualMachine {
546 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900547 // Don't check permission. The owner of the VM might have passed this binder object to
548 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000549 Ok(self.instance.cid as i32)
550 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000551
552 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900553 // Don't check permission. The owner of the VM might have passed this binder object to
554 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000555 Ok(self.instance.running())
556 }
557
558 fn registerCallback(
559 &self,
560 callback: &Strong<dyn IVirtualMachineCallback>,
561 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900562 // Don't check permission. The owner of the VM might have passed this binder object to
563 // others.
564 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000565 // TODO: Should this give an error if the VM is already dead?
566 self.instance.callbacks.add(callback.clone());
567 Ok(())
568 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000569
570 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
571 if !self.instance.running() {
572 return Err(new_binder_exception(
573 ExceptionCode::SERVICE_SPECIFIC,
574 "VM is no longer running",
575 ));
576 }
577 let stream =
578 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
579 new_binder_exception(
580 ExceptionCode::SERVICE_SPECIFIC,
581 format!("Failed to connect: {}", e),
582 )
583 })?;
584 Ok(vsock_stream_to_pfd(stream))
585 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000586}
587
588impl Drop for VirtualMachine {
589 fn drop(&mut self) {
590 debug!("Dropping {:?}", self);
591 self.instance.kill();
592 }
593}
594
595/// A set of Binders to be called back in response to various events on the VM, such as when it
596/// dies.
597#[derive(Debug, Default)]
598pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
599
600impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900601 /// Call all registered callbacks to notify that the payload has started.
602 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
603 let callbacks = &*self.0.lock().unwrap();
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000604 let pfd = vsock_stream_to_pfd(stream);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900605 for callback in callbacks {
606 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
607 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
608 }
609 }
610 }
611
Andrew Walbrandae07162021-03-12 17:05:20 +0000612 /// Call all registered callbacks to say that the VM has died.
613 pub fn callback_on_died(&self, cid: Cid) {
614 let callbacks = &*self.0.lock().unwrap();
615 for callback in callbacks {
616 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900617 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000618 }
619 }
620 }
621
622 /// Add a new callback to the set.
623 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
624 self.0.lock().unwrap().push(callback);
625 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000626}
627
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000628/// The mutable state of the VirtualizationService. There should only be one instance of this
629/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000630#[derive(Debug)]
631struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000632 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000633 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000634
635 /// The VMs which have been started. When VMs are started a weak reference is added to this list
636 /// while a strong reference is returned to the caller over Binder. Once all copies of the
637 /// Binder client are dropped the weak reference here will become invalid, and will be removed
638 /// from the list opportunistically the next time `add_vm` is called.
639 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000640
641 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
642 /// This is only used for debugging purposes.
643 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000644}
645
646impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000647 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000648 fn vms(&self) -> Vec<Arc<VmInstance>> {
649 // Attempt to upgrade the weak pointers to strong pointers.
650 self.vms.iter().filter_map(Weak::upgrade).collect()
651 }
652
653 /// Add a new VM to the list.
654 fn add_vm(&mut self, vm: Weak<VmInstance>) {
655 // Garbage collect any entries from the stored list which no longer exist.
656 self.vms.retain(|vm| vm.strong_count() > 0);
657
658 // Actually add the new VM.
659 self.vms.push(vm);
660 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000661
Jiyong Park8611a6c2021-07-09 18:17:44 +0900662 /// Get a VM that corresponds to the given cid
663 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
664 self.vms().into_iter().find(|vm| vm.cid == cid)
665 }
666
David Brazdil3c2ddef2021-03-18 13:09:57 +0000667 /// Store a strong VM reference.
668 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
669 self.debug_held_vms.push(vm);
670 }
671
672 /// Retrieve and remove a strong VM reference.
673 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
674 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
675 Some(self.debug_held_vms.swap_remove(pos))
676 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000677
678 /// Get the next available CID, or an error if we have run out.
679 fn allocate_cid(&mut self) -> binder::Result<Cid> {
680 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
681 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000682 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000683 Ok(cid)
684 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000685}
686
687impl Default for State {
688 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000689 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000690 }
691}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000692
693/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
694fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
695 option.as_ref().map(|t| t.as_ref())
696}
697
698/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000699fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
700 file.as_ref().try_clone().map_err(|e| {
701 new_binder_exception(
702 ExceptionCode::BAD_PARCELABLE,
703 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
704 )
705 })
706}
707
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000708/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
709fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
710 // SAFETY: ownership is transferred from stream to f
711 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
712 ParcelFileDescriptor::new(f)
713}
714
Andrew Walbran806f1542021-06-10 14:07:12 +0000715/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
716fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
717 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000718}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900719
720/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
721/// it doesn't require that T implements Clone.
722enum BorrowedOrOwned<'a, T> {
723 Borrowed(&'a T),
724 Owned(T),
725}
726
727impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
728 fn as_ref(&self) -> &T {
729 match self {
730 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700731 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900732 }
733 }
734}