blob: 1f5673147c076bb6da5505d2cf16ceb39aad20dc [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};
Jooyung Han9900f3d2021-07-06 10:27:54 +090019use crate::payload::make_payload_disk;
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 Han35edb8f2021-07-01 16:17:16 +090038use anyhow::{bail, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000039use disk::QcowFile;
Jiyong Park8611a6c2021-07-09 18:17:44 +090040use log::{debug, error, warn, info};
Jooyung Hanadfb76c2021-06-28 17:29:30 +090041use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Andrew Walbrandff3b942021-06-09 15:20:36 +000042use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000043use std::ffi::CString;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000044use std::fs::{File, 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};
Jiyong Park23601142021-07-05 13:15:32 +090049use vmconfig::{VmConfig, Partition};
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.
56const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
57
Jooyung Han35edb8f2021-07-01 16:17:16 +090058/// The list of APEXes which microdroid requires.
59/// TODO(b/192200378) move this to microdroid.json?
Jooyung Han1a72c6f2021-07-09 13:47:10 +090060const MICRODROID_REQUIRED_APEXES: [&str; 3] =
61 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
Jooyung Han35edb8f2021-07-01 16:17:16 +090062
Jiyong Park8611a6c2021-07-09 18:17:44 +090063/// The CID representing the host VM
64const VMADDR_CID_HOST: u32 = 2;
65
66/// Port number that virtualizationservice listens on connections from the guest VMs for the
67/// payload output
68const PORT_VIRT_SERVICE: u32 = 3000;
69
Andrew Walbranf6bf6862021-05-21 12:41:13 +000070/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090071#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000072pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090073 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000074}
75
Andrew Walbranf6bf6862021-05-21 12:41:13 +000076impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077
Andrew Walbranf6bf6862021-05-21 12:41:13 +000078impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000079 /// Create and start a new VM with the given configuration, assigning it the next available CID.
80 ///
81 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000082 fn startVm(
83 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000084 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000085 log_fd: Option<&ParcelFileDescriptor>,
86 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090087 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000088 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000090 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000092 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000093 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000094
95 // Counter to generate unique IDs for temporary image files.
96 let mut next_temporary_image_id = 0;
97 // Files which are referred to from composite images. These must be mapped to the crosvm
98 // child process, and not closed before it is started.
99 let mut indirect_files = vec![];
100
101 // Make directory for temporary files.
102 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
103 create_dir(&temporary_directory).map_err(|e| {
104 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000105 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 temporary_directory, e
107 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000108 new_binder_exception(
109 ExceptionCode::SERVICE_SPECIFIC,
110 format!(
111 "Failed to create temporary directory {:?} for VM files: {}",
112 temporary_directory, e
113 ),
114 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000115 })?;
116
Jooyung Han21e9b922021-06-26 04:14:16 +0900117 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900118 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900119 load_app_config(config, &temporary_directory).map_err(|e| {
120 error!("Failed to load app config from {}: {}", &config.configPath, e);
121 new_binder_exception(
122 ExceptionCode::SERVICE_SPECIFIC,
123 format!("Failed to load app config from {}: {}", &config.configPath, e),
124 )
125 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900126 ),
127 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900128 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900129 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900130
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000131 // Assemble disk images if needed.
132 let disks = config
133 .disks
134 .iter()
135 .map(|disk| {
136 assemble_disk_image(
137 disk,
138 &temporary_directory,
139 &mut next_temporary_image_id,
140 &mut indirect_files,
141 )
142 })
143 .collect::<Result<Vec<DiskFile>, _>>()?;
144
145 // Actually start the VM.
146 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000147 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 bootloader: as_asref(&config.bootloader),
149 kernel: as_asref(&config.kernel),
150 initrd: as_asref(&config.initrd),
151 disks,
152 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000153 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000154 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000155 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000156 let composite_disk_fds: Vec<_> =
157 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158 let instance = VmInstance::start(
159 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000160 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000161 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000162 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000163 requester_uid,
164 requester_sid,
165 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000166 )
167 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000168 error!("Failed to start VM with config {:?}: {}", config, e);
169 new_binder_exception(
170 ExceptionCode::SERVICE_SPECIFIC,
171 format!("Failed to start VM: {}", e),
172 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000173 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000174 state.add_vm(Arc::downgrade(&instance));
175 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000176 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000177
Andrew Walbrandff3b942021-06-09 15:20:36 +0000178 /// Initialise an empty partition image of the given size to be used as a writable partition.
179 fn initializeWritablePartition(
180 &self,
181 image_fd: &ParcelFileDescriptor,
182 size: i64,
183 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900184 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000185 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000186 new_binder_exception(
187 ExceptionCode::ILLEGAL_ARGUMENT,
188 format!("Invalid size {}: {}", size, e),
189 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000190 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000191 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000192
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000193 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000194 new_binder_exception(
195 ExceptionCode::SERVICE_SPECIFIC,
196 format!("Failed to create QCOW2 image: {}", e),
197 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000198 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000199
200 Ok(())
201 }
202
Andrew Walbran320b5602021-03-04 16:11:12 +0000203 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
204 /// and as such is only permitted from the shell user.
205 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000206 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000207
208 let state = &mut *self.state.lock().unwrap();
209 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000210 let cids = vms
211 .into_iter()
212 .map(|vm| VirtualMachineDebugInfo {
213 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000214 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000215 requesterUid: vm.requester_uid as i32,
216 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000217 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000218 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000219 })
220 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000221 Ok(cids)
222 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000223
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000224 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
225 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000226 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000227 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000228
David Brazdil3c2ddef2021-03-18 13:09:57 +0000229 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000230 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000231 Ok(())
232 }
233
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000234 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
235 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
236 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000237 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000238 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000239
240 let state = &mut *self.state.lock().unwrap();
241 Ok(state.debug_drop_vm(cid))
242 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000243}
244
Jiyong Park8611a6c2021-07-09 18:17:44 +0900245impl VirtualizationService {
246 pub fn init() -> VirtualizationService {
247 let service = VirtualizationService::default();
248 let state = service.state.clone(); // reference to state (not the state itself) is copied
249 std::thread::spawn(move || {
250 handle_connection_from_vm(state).unwrap();
251 });
252 service
253 }
254}
255
256/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
257/// client via the callback (if registered).
258fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
259 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
260 for stream in listener.incoming() {
261 let stream = match stream {
262 Err(e) => {
263 warn!("invalid incoming connection: {}", e);
264 continue;
265 }
266 Ok(s) => s,
267 };
268 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
269 let cid = addr.cid();
270 let port = addr.port();
271 info!("connected from cid={}, port={}", cid, port);
272 if cid < FIRST_GUEST_CID {
273 warn!("connection is not from a guest VM");
274 continue;
275 }
276 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
277 vm.callbacks.notify_payload_started(cid, stream);
278 }
279 }
280 }
281 Ok(())
282}
283
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000284/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
285///
286/// This may involve assembling a composite disk from a set of partition images.
287fn assemble_disk_image(
288 disk: &DiskImage,
289 temporary_directory: &Path,
290 next_temporary_image_id: &mut u64,
291 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000292) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000293 let image = if !disk.partitions.is_empty() {
294 if disk.image.is_some() {
295 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000296 return Err(new_binder_exception(
297 ExceptionCode::ILLEGAL_ARGUMENT,
298 "DiskImage contains both image and partitions.",
299 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000300 }
301
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000302 let composite_image_filenames =
303 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
304 let (image, partition_files) = make_composite_image(
305 &disk.partitions,
306 &composite_image_filenames.composite,
307 &composite_image_filenames.header,
308 &composite_image_filenames.footer,
309 )
310 .map_err(|e| {
311 error!("Failed to make composite image with config {:?}: {}", disk, e);
312 new_binder_exception(
313 ExceptionCode::SERVICE_SPECIFIC,
314 format!("Failed to make composite image: {}", e),
315 )
316 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000317
318 // Pass the file descriptors for the various partition files to crosvm when it
319 // is run.
320 indirect_files.extend(partition_files);
321
322 image
323 } else if let Some(image) = &disk.image {
324 clone_file(image)?
325 } else {
326 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000327 return Err(new_binder_exception(
328 ExceptionCode::ILLEGAL_ARGUMENT,
329 "DiskImage didn't contain image or partitions.",
330 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000331 };
332
333 Ok(DiskFile { image, writable: disk.writable })
334}
335
Jooyung Han21e9b922021-06-26 04:14:16 +0900336fn load_app_config(
337 config: &VirtualMachineAppConfig,
338 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900339) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900340 let apk_file = config.apk.as_ref().unwrap().as_ref();
341 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
342 let config_path = &config.configPath;
343
Jooyung Han35edb8f2021-07-01 16:17:16 +0900344 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900345 let config_file = apk_zip.by_name(config_path)?;
346 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
347
348 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900349 // For now, the only supported "os" value is "microdroid"
350 if os_name != "microdroid" {
351 bail!("unknown os: {}", os_name);
352 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900353 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
354 let vm_config_file = File::open(vm_config_path)?;
355 let mut vm_config = VmConfig::load(&vm_config_file)?;
356
Jiyong Park23601142021-07-05 13:15:32 +0900357 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900358 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900359 let mut apexes = vm_payload_config.apexes.clone();
360 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900361 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900362 );
363 apexes.dedup_by(|a, b| a.name == b.name);
364
Jooyung Han73bac242021-07-02 10:25:49 +0900365 vm_config.disks.push(make_payload_disk(
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900366 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
367 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
368 config_path,
369 &apexes,
370 temporary_directory,
371 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900372
373 if config.debug {
374 vm_config.disks[1].partitions.push(Partition {
375 label: "bootconfig".to_owned(),
376 paths: vec![PathBuf::from(
377 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
378 )],
379 writable: false,
380 });
381 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900382 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900383
384 vm_config.to_parcelable()
385}
386
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000387/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000388fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000389 temporary_directory: &Path,
390 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000391) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392 let id = *next_temporary_image_id;
393 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000394 CompositeImageFilenames {
395 composite: temporary_directory.join(format!("composite-{}.img", id)),
396 header: temporary_directory.join(format!("composite-{}-header.img", id)),
397 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
398 }
399}
400
401/// Filenames for a composite disk image, including header and footer partitions.
402#[derive(Clone, Debug, Eq, PartialEq)]
403struct CompositeImageFilenames {
404 /// The composite disk image itself.
405 composite: PathBuf,
406 /// The header partition image.
407 header: PathBuf,
408 /// The footer partition image.
409 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000410}
411
412/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000413fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000414 ThreadState::with_calling_sid(|sid| {
415 if let Some(sid) = sid {
416 match sid.to_str() {
417 Ok(sid) => Ok(sid.to_owned()),
418 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000419 error!("SID was not valid UTF-8: {}", e);
420 Err(new_binder_exception(
421 ExceptionCode::ILLEGAL_ARGUMENT,
422 format!("SID was not valid UTF-8: {}", e),
423 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000424 }
425 }
426 } else {
427 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000428 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000429 }
430 })
431}
432
Jiyong Park753553b2021-07-12 21:21:09 +0900433/// Checks whether the caller has a specific permission
434fn check_permission(perm: &str) -> binder::Result<()> {
435 let calling_pid = ThreadState::get_calling_pid();
436 let calling_uid = ThreadState::get_calling_uid();
437 // Root can do anything
438 if calling_uid == 0 {
439 return Ok(());
440 }
441 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
442 binder::get_interface("permission")?;
443 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000444 Ok(())
445 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900446 Err(new_binder_exception(
447 ExceptionCode::SECURITY,
448 format!("does not have the {} permission", perm),
449 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000450 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000451}
452
Jiyong Park753553b2021-07-12 21:21:09 +0900453/// Check whether the caller of the current Binder method is allowed to call debug methods.
454fn check_debug_access() -> binder::Result<()> {
455 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
456}
457
458/// Check whether the caller of the current Binder method is allowed to manage VMs
459fn check_manage_access() -> binder::Result<()> {
460 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
461}
462
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000463/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
464#[derive(Debug)]
465struct VirtualMachine {
466 instance: Arc<VmInstance>,
467}
468
469impl VirtualMachine {
470 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
471 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000472 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000473 }
474}
475
476impl Interface for VirtualMachine {}
477
478impl IVirtualMachine for VirtualMachine {
479 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900480 // Don't check permission. The owner of the VM might have passed this binder object to
481 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000482 Ok(self.instance.cid as i32)
483 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000484
485 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900486 // Don't check permission. The owner of the VM might have passed this binder object to
487 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000488 Ok(self.instance.running())
489 }
490
491 fn registerCallback(
492 &self,
493 callback: &Strong<dyn IVirtualMachineCallback>,
494 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900495 // Don't check permission. The owner of the VM might have passed this binder object to
496 // others.
497 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000498 // TODO: Should this give an error if the VM is already dead?
499 self.instance.callbacks.add(callback.clone());
500 Ok(())
501 }
502}
503
504impl Drop for VirtualMachine {
505 fn drop(&mut self) {
506 debug!("Dropping {:?}", self);
507 self.instance.kill();
508 }
509}
510
511/// A set of Binders to be called back in response to various events on the VM, such as when it
512/// dies.
513#[derive(Debug, Default)]
514pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
515
516impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900517 /// Call all registered callbacks to notify that the payload has started.
518 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
519 let callbacks = &*self.0.lock().unwrap();
520 // SAFETY: ownership is transferred from stream to f
521 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
522 let pfd = ParcelFileDescriptor::new(f);
523 for callback in callbacks {
524 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
525 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
526 }
527 }
528 }
529
Andrew Walbrandae07162021-03-12 17:05:20 +0000530 /// Call all registered callbacks to say that the VM has died.
531 pub fn callback_on_died(&self, cid: Cid) {
532 let callbacks = &*self.0.lock().unwrap();
533 for callback in callbacks {
534 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900535 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000536 }
537 }
538 }
539
540 /// Add a new callback to the set.
541 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
542 self.0.lock().unwrap().push(callback);
543 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000544}
545
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000546/// The mutable state of the VirtualizationService. There should only be one instance of this
547/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000548#[derive(Debug)]
549struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000550 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000551 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000552
553 /// The VMs which have been started. When VMs are started a weak reference is added to this list
554 /// while a strong reference is returned to the caller over Binder. Once all copies of the
555 /// Binder client are dropped the weak reference here will become invalid, and will be removed
556 /// from the list opportunistically the next time `add_vm` is called.
557 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000558
559 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
560 /// This is only used for debugging purposes.
561 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000562}
563
564impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000565 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000566 fn vms(&self) -> Vec<Arc<VmInstance>> {
567 // Attempt to upgrade the weak pointers to strong pointers.
568 self.vms.iter().filter_map(Weak::upgrade).collect()
569 }
570
571 /// Add a new VM to the list.
572 fn add_vm(&mut self, vm: Weak<VmInstance>) {
573 // Garbage collect any entries from the stored list which no longer exist.
574 self.vms.retain(|vm| vm.strong_count() > 0);
575
576 // Actually add the new VM.
577 self.vms.push(vm);
578 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000579
Jiyong Park8611a6c2021-07-09 18:17:44 +0900580 /// Get a VM that corresponds to the given cid
581 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
582 self.vms().into_iter().find(|vm| vm.cid == cid)
583 }
584
David Brazdil3c2ddef2021-03-18 13:09:57 +0000585 /// Store a strong VM reference.
586 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
587 self.debug_held_vms.push(vm);
588 }
589
590 /// Retrieve and remove a strong VM reference.
591 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
592 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
593 Some(self.debug_held_vms.swap_remove(pos))
594 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000595
596 /// Get the next available CID, or an error if we have run out.
597 fn allocate_cid(&mut self) -> binder::Result<Cid> {
598 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
599 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000600 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000601 Ok(cid)
602 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000603}
604
605impl Default for State {
606 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000607 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000608 }
609}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000610
611/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
612fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
613 option.as_ref().map(|t| t.as_ref())
614}
615
616/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000617fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
618 file.as_ref().try_clone().map_err(|e| {
619 new_binder_exception(
620 ExceptionCode::BAD_PARCELABLE,
621 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
622 )
623 })
624}
625
626/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
627fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
628 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900630
631/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
632/// it doesn't require that T implements Clone.
633enum BorrowedOrOwned<'a, T> {
634 Borrowed(&'a T),
635 Owned(T),
636}
637
638impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
639 fn as_ref(&self) -> &T {
640 match self {
641 Self::Borrowed(b) => b,
642 Self::Owned(o) => &o,
643 }
644 }
645}