blob: 19e4877b308534bed28db7b4c328bf922115905b [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;
35use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000036 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000037};
Jooyung Han95884632021-07-06 22:27:54 +090038use anyhow::{bail, Context, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000039use disk::QcowFile;
Jiyong Park8611a6c2021-07-09 18:17:44 +090040use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000041use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000042use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000043use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090044use std::fs::{File, OpenOptions, create_dir};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000045use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090046use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000047use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000048use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000049use vmconfig::VmConfig;
Jiyong Park8611a6c2021-07-09 18:17:44 +090050use vsock::{VsockListener, SockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090051use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000052
Andrew Walbranf6bf6862021-05-21 12:41:13 +000053pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000055/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000056pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000057
Jiyong Park8611a6c2021-07-09 18:17:44 +090058/// The CID representing the host VM
59const VMADDR_CID_HOST: u32 = 2;
60
61/// Port number that virtualizationservice listens on connections from the guest VMs for the
62/// payload output
63const PORT_VIRT_SERVICE: u32 = 3000;
64
Jooyung Han95884632021-07-06 22:27:54 +090065/// The size of zero.img.
66/// Gaps in composite disk images are filled with a shared zero.img.
67const ZERO_FILLER_SIZE: u64 = 4096;
68
Andrew Walbranf6bf6862021-05-21 12:41:13 +000069/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090070#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000071pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090072 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073}
74
Andrew Walbranf6bf6862021-05-21 12:41:13 +000075impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000076
Andrew Walbranf6bf6862021-05-21 12:41:13 +000077impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000078 /// Create and start a new VM with the given configuration, assigning it the next available CID.
79 ///
80 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000081 fn startVm(
82 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000083 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000084 log_fd: Option<&ParcelFileDescriptor>,
85 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090086 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000088 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000089 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000091 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000092 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093
94 // Counter to generate unique IDs for temporary image files.
95 let mut next_temporary_image_id = 0;
96 // Files which are referred to from composite images. These must be mapped to the crosvm
97 // child process, and not closed before it is started.
98 let mut indirect_files = vec![];
99
100 // Make directory for temporary files.
101 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
102 create_dir(&temporary_directory).map_err(|e| {
103 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000104 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105 temporary_directory, e
106 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000107 new_binder_exception(
108 ExceptionCode::SERVICE_SPECIFIC,
109 format!(
110 "Failed to create temporary directory {:?} for VM files: {}",
111 temporary_directory, e
112 ),
113 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000114 })?;
115
Jooyung Han21e9b922021-06-26 04:14:16 +0900116 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900117 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900118 load_app_config(config, &temporary_directory).map_err(|e| {
119 error!("Failed to load app config from {}: {}", &config.configPath, e);
120 new_binder_exception(
121 ExceptionCode::SERVICE_SPECIFIC,
122 format!("Failed to load app config from {}: {}", &config.configPath, e),
123 )
124 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900125 ),
126 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900127 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900128 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900129
Jooyung Han95884632021-07-06 22:27:54 +0900130 let zero_filler_path = temporary_directory.join("zero.img");
131 let zero_filler_file = write_zero_filler(&zero_filler_path).map_err(|e| {
132 error!("Failed to make composite image: {}", e);
133 new_binder_exception(
134 ExceptionCode::SERVICE_SPECIFIC,
135 format!("Failed to make composite image: {}", e),
136 )
137 })?;
138 indirect_files.push(zero_filler_file);
139
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000140 // Assemble disk images if needed.
141 let disks = config
142 .disks
143 .iter()
144 .map(|disk| {
145 assemble_disk_image(
146 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900147 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 &temporary_directory,
149 &mut next_temporary_image_id,
150 &mut indirect_files,
151 )
152 })
153 .collect::<Result<Vec<DiskFile>, _>>()?;
154
155 // Actually start the VM.
156 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000157 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158 bootloader: as_asref(&config.bootloader),
159 kernel: as_asref(&config.kernel),
160 initrd: as_asref(&config.initrd),
161 disks,
162 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000163 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000164 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000165 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000166 let composite_disk_fds: Vec<_> =
167 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000168 let instance = VmInstance::start(
169 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000170 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000171 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000173 requester_uid,
174 requester_sid,
175 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000176 )
177 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000178 error!("Failed to start VM with config {:?}: {}", config, e);
179 new_binder_exception(
180 ExceptionCode::SERVICE_SPECIFIC,
181 format!("Failed to start VM: {}", e),
182 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000183 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000184 state.add_vm(Arc::downgrade(&instance));
185 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000186 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000187
Andrew Walbrandff3b942021-06-09 15:20:36 +0000188 /// Initialise an empty partition image of the given size to be used as a writable partition.
189 fn initializeWritablePartition(
190 &self,
191 image_fd: &ParcelFileDescriptor,
192 size: i64,
193 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900194 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000195 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000196 new_binder_exception(
197 ExceptionCode::ILLEGAL_ARGUMENT,
198 format!("Invalid size {}: {}", size, e),
199 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000200 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000201 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000202
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000203 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000204 new_binder_exception(
205 ExceptionCode::SERVICE_SPECIFIC,
206 format!("Failed to create QCOW2 image: {}", e),
207 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000208 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000209
210 Ok(())
211 }
212
Andrew Walbran320b5602021-03-04 16:11:12 +0000213 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
214 /// and as such is only permitted from the shell user.
215 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000216 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000217
218 let state = &mut *self.state.lock().unwrap();
219 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000220 let cids = vms
221 .into_iter()
222 .map(|vm| VirtualMachineDebugInfo {
223 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000224 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000225 requesterUid: vm.requester_uid as i32,
226 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000227 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000228 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000229 })
230 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000231 Ok(cids)
232 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000233
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000234 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
235 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000236 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000237 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000238
David Brazdil3c2ddef2021-03-18 13:09:57 +0000239 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000240 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000241 Ok(())
242 }
243
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000244 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
245 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
246 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000247 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000248 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000249
250 let state = &mut *self.state.lock().unwrap();
251 Ok(state.debug_drop_vm(cid))
252 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000253}
254
Jiyong Park8611a6c2021-07-09 18:17:44 +0900255impl VirtualizationService {
256 pub fn init() -> VirtualizationService {
257 let service = VirtualizationService::default();
258 let state = service.state.clone(); // reference to state (not the state itself) is copied
259 std::thread::spawn(move || {
260 handle_connection_from_vm(state).unwrap();
261 });
262 service
263 }
264}
265
266/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
267/// client via the callback (if registered).
268fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
269 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
270 for stream in listener.incoming() {
271 let stream = match stream {
272 Err(e) => {
273 warn!("invalid incoming connection: {}", e);
274 continue;
275 }
276 Ok(s) => s,
277 };
278 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
279 let cid = addr.cid();
280 let port = addr.port();
281 info!("connected from cid={}, port={}", cid, port);
282 if cid < FIRST_GUEST_CID {
283 warn!("connection is not from a guest VM");
284 continue;
285 }
286 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
287 vm.callbacks.notify_payload_started(cid, stream);
288 }
289 }
290 }
291 Ok(())
292}
293
Jooyung Han95884632021-07-06 22:27:54 +0900294fn write_zero_filler(zero_filler_path: &Path) -> Result<File> {
295 let file = OpenOptions::new()
296 .create_new(true)
297 .read(true)
298 .write(true)
299 .open(zero_filler_path)
300 .with_context(|| "Failed to create zero.img")?;
301 file.set_len(ZERO_FILLER_SIZE)?;
302 Ok(file)
303}
304
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000305/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
306///
307/// This may involve assembling a composite disk from a set of partition images.
308fn assemble_disk_image(
309 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900310 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000311 temporary_directory: &Path,
312 next_temporary_image_id: &mut u64,
313 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000314) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000315 let image = if !disk.partitions.is_empty() {
316 if disk.image.is_some() {
317 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000318 return Err(new_binder_exception(
319 ExceptionCode::ILLEGAL_ARGUMENT,
320 "DiskImage contains both image and partitions.",
321 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000322 }
323
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000324 let composite_image_filenames =
325 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
326 let (image, partition_files) = make_composite_image(
327 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900328 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000329 &composite_image_filenames.composite,
330 &composite_image_filenames.header,
331 &composite_image_filenames.footer,
332 )
333 .map_err(|e| {
334 error!("Failed to make composite image with config {:?}: {}", disk, e);
335 new_binder_exception(
336 ExceptionCode::SERVICE_SPECIFIC,
337 format!("Failed to make composite image: {}", e),
338 )
339 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000340
341 // Pass the file descriptors for the various partition files to crosvm when it
342 // is run.
343 indirect_files.extend(partition_files);
344
345 image
346 } else if let Some(image) = &disk.image {
347 clone_file(image)?
348 } else {
349 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000350 return Err(new_binder_exception(
351 ExceptionCode::ILLEGAL_ARGUMENT,
352 "DiskImage didn't contain image or partitions.",
353 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000354 };
355
356 Ok(DiskFile { image, writable: disk.writable })
357}
358
Jooyung Han21e9b922021-06-26 04:14:16 +0900359fn load_app_config(
360 config: &VirtualMachineAppConfig,
361 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900362) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000363 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
364 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park48b354d2021-07-15 15:04:38 +0900365 // TODO(b/193504400) pass this to crosvm
Andrew Walbrancc0db522021-07-12 17:03:42 +0000366 let _instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900367 let config_path = &config.configPath;
368
Andrew Walbrancc0db522021-07-12 17:03:42 +0000369 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900370 let config_file = apk_zip.by_name(config_path)?;
371 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
372
373 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000374
Jooyung Han35edb8f2021-07-01 16:17:16 +0900375 // For now, the only supported "os" value is "microdroid"
376 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000377 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900378 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000379
380 // It is safe to construct a filename based on the os_name because we've already checked that it
381 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900382 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
383 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000384 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900385
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000386 if config.memory_mib > 0 {
387 vm_config.memory_mib = config.memory_mib;
388 }
389
Andrew Walbrancc0db522021-07-12 17:03:42 +0000390 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900391 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000392 let apexes = vm_payload_config.apexes.clone();
393 add_microdroid_images(
394 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900395 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000396 apk_file,
397 idsig_file,
398 apexes,
399 &mut vm_config,
400 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900401 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900402
Andrew Walbrancc0db522021-07-12 17:03:42 +0000403 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900404}
405
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000406/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000407fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000408 temporary_directory: &Path,
409 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000410) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000411 let id = *next_temporary_image_id;
412 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000413 CompositeImageFilenames {
414 composite: temporary_directory.join(format!("composite-{}.img", id)),
415 header: temporary_directory.join(format!("composite-{}-header.img", id)),
416 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
417 }
418}
419
420/// Filenames for a composite disk image, including header and footer partitions.
421#[derive(Clone, Debug, Eq, PartialEq)]
422struct CompositeImageFilenames {
423 /// The composite disk image itself.
424 composite: PathBuf,
425 /// The header partition image.
426 header: PathBuf,
427 /// The footer partition image.
428 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000429}
430
431/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000432fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000433 ThreadState::with_calling_sid(|sid| {
434 if let Some(sid) = sid {
435 match sid.to_str() {
436 Ok(sid) => Ok(sid.to_owned()),
437 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000438 error!("SID was not valid UTF-8: {}", e);
439 Err(new_binder_exception(
440 ExceptionCode::ILLEGAL_ARGUMENT,
441 format!("SID was not valid UTF-8: {}", e),
442 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000443 }
444 }
445 } else {
446 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000447 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000448 }
449 })
450}
451
Jiyong Park753553b2021-07-12 21:21:09 +0900452/// Checks whether the caller has a specific permission
453fn check_permission(perm: &str) -> binder::Result<()> {
454 let calling_pid = ThreadState::get_calling_pid();
455 let calling_uid = ThreadState::get_calling_uid();
456 // Root can do anything
457 if calling_uid == 0 {
458 return Ok(());
459 }
460 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
461 binder::get_interface("permission")?;
462 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000463 Ok(())
464 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900465 Err(new_binder_exception(
466 ExceptionCode::SECURITY,
467 format!("does not have the {} permission", perm),
468 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000469 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000470}
471
Jiyong Park753553b2021-07-12 21:21:09 +0900472/// Check whether the caller of the current Binder method is allowed to call debug methods.
473fn check_debug_access() -> binder::Result<()> {
474 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
475}
476
477/// Check whether the caller of the current Binder method is allowed to manage VMs
478fn check_manage_access() -> binder::Result<()> {
479 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
480}
481
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000482/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
483#[derive(Debug)]
484struct VirtualMachine {
485 instance: Arc<VmInstance>,
486}
487
488impl VirtualMachine {
489 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
490 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000491 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000492 }
493}
494
495impl Interface for VirtualMachine {}
496
497impl IVirtualMachine for VirtualMachine {
498 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900499 // Don't check permission. The owner of the VM might have passed this binder object to
500 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000501 Ok(self.instance.cid as i32)
502 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000503
504 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900505 // Don't check permission. The owner of the VM might have passed this binder object to
506 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000507 Ok(self.instance.running())
508 }
509
510 fn registerCallback(
511 &self,
512 callback: &Strong<dyn IVirtualMachineCallback>,
513 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900514 // Don't check permission. The owner of the VM might have passed this binder object to
515 // others.
516 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000517 // TODO: Should this give an error if the VM is already dead?
518 self.instance.callbacks.add(callback.clone());
519 Ok(())
520 }
521}
522
523impl Drop for VirtualMachine {
524 fn drop(&mut self) {
525 debug!("Dropping {:?}", self);
526 self.instance.kill();
527 }
528}
529
530/// A set of Binders to be called back in response to various events on the VM, such as when it
531/// dies.
532#[derive(Debug, Default)]
533pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
534
535impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900536 /// Call all registered callbacks to notify that the payload has started.
537 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
538 let callbacks = &*self.0.lock().unwrap();
539 // SAFETY: ownership is transferred from stream to f
540 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
541 let pfd = ParcelFileDescriptor::new(f);
542 for callback in callbacks {
543 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
544 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
545 }
546 }
547 }
548
Andrew Walbrandae07162021-03-12 17:05:20 +0000549 /// Call all registered callbacks to say that the VM has died.
550 pub fn callback_on_died(&self, cid: Cid) {
551 let callbacks = &*self.0.lock().unwrap();
552 for callback in callbacks {
553 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900554 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000555 }
556 }
557 }
558
559 /// Add a new callback to the set.
560 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
561 self.0.lock().unwrap().push(callback);
562 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000563}
564
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000565/// The mutable state of the VirtualizationService. There should only be one instance of this
566/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000567#[derive(Debug)]
568struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000569 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000570 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000571
572 /// The VMs which have been started. When VMs are started a weak reference is added to this list
573 /// while a strong reference is returned to the caller over Binder. Once all copies of the
574 /// Binder client are dropped the weak reference here will become invalid, and will be removed
575 /// from the list opportunistically the next time `add_vm` is called.
576 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000577
578 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
579 /// This is only used for debugging purposes.
580 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000581}
582
583impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000584 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000585 fn vms(&self) -> Vec<Arc<VmInstance>> {
586 // Attempt to upgrade the weak pointers to strong pointers.
587 self.vms.iter().filter_map(Weak::upgrade).collect()
588 }
589
590 /// Add a new VM to the list.
591 fn add_vm(&mut self, vm: Weak<VmInstance>) {
592 // Garbage collect any entries from the stored list which no longer exist.
593 self.vms.retain(|vm| vm.strong_count() > 0);
594
595 // Actually add the new VM.
596 self.vms.push(vm);
597 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000598
Jiyong Park8611a6c2021-07-09 18:17:44 +0900599 /// Get a VM that corresponds to the given cid
600 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
601 self.vms().into_iter().find(|vm| vm.cid == cid)
602 }
603
David Brazdil3c2ddef2021-03-18 13:09:57 +0000604 /// Store a strong VM reference.
605 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
606 self.debug_held_vms.push(vm);
607 }
608
609 /// Retrieve and remove a strong VM reference.
610 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
611 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
612 Some(self.debug_held_vms.swap_remove(pos))
613 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000614
615 /// Get the next available CID, or an error if we have run out.
616 fn allocate_cid(&mut self) -> binder::Result<Cid> {
617 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
618 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000619 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000620 Ok(cid)
621 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000622}
623
624impl Default for State {
625 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000626 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000627 }
628}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629
630/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
631fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
632 option.as_ref().map(|t| t.as_ref())
633}
634
635/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000636fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
637 file.as_ref().try_clone().map_err(|e| {
638 new_binder_exception(
639 ExceptionCode::BAD_PARCELABLE,
640 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
641 )
642 })
643}
644
645/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
646fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
647 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000648}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900649
650/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
651/// it doesn't require that T implements Clone.
652enum BorrowedOrOwned<'a, T> {
653 Borrowed(&'a T),
654 Owned(T),
655}
656
657impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
658 fn as_ref(&self) -> &T {
659 match self {
660 Self::Borrowed(b) => b,
661 Self::Owned(o) => &o,
662 }
663 }
664}