blob: 297cf6852e8d8c3051e490287c37176c7129a8d9 [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
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090017use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000018use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000019use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000020use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090021use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Seungjae Yoofd9a0622022-10-14 10:01:29 +090023use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000025 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000026 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010027 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000028 IVirtualMachineCallback::IVirtualMachineCallback,
29 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090030 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090032 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010035 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090036 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090038};
David Brazdil528e0472022-10-10 15:06:02 +010039use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
40 IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
41 IVirtualizationServiceInternal::{BnVirtualizationServiceInternal, IVirtualizationServiceInternal},
42};
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdil73988ea2022-11-11 15:10:32 +000044 BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090045};
46use anyhow::{anyhow, bail, Context, Result};
47use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010048use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000049 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
David Brazdil73988ea2022-11-11 15:10:32 +000050 Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000051};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000052use disk::QcowFile;
David Brazdila07a1792022-10-25 13:37:57 +010053use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000054use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090055use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
David Brazdil73988ea2022-11-11 15:10:32 +000056use rpcbinder::RpcServer;
Jiyong Parkd50a0242021-09-16 21:00:14 +090057use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090058use semver::VersionReq;
David Brazdil73988ea2022-11-11 15:10:32 +000059use std::collections::HashMap;
Andrew Walbrandff3b942021-06-09 15:20:36 +000060use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000061use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010062use std::fs::{create_dir, File, OpenOptions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090063use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000064use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000065use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000066use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000067use std::sync::{Arc, Mutex, Weak};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090068use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000069use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000070use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090071use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000072
David Brazdil41d1a872022-10-05 14:44:19 +010073/// The unique ID of a VM used (together with a port number) for vsock communication.
74pub type Cid = u32;
75
Andrew Walbranf6bf6862021-05-21 12:41:13 +000076pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000079pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000080
David Brazdil41d1a872022-10-05 14:44:19 +010081/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
82/// are reserved for the host or other usage.
David Brazdil73988ea2022-11-11 15:10:32 +000083const GUEST_CID_MIN: Cid = 2048;
84const GUEST_CID_MAX: Cid = 65535;
David Brazdil41d1a872022-10-05 14:44:19 +010085
86const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
Jiyong Park8611a6c2021-07-09 18:17:44 +090087
Jooyung Han95884632021-07-06 22:27:54 +090088/// The size of zero.img.
89/// Gaps in composite disk images are filled with a shared zero.img.
90const ZERO_FILLER_SIZE: u64 = 4096;
91
Jiyong Park9dd389e2021-08-23 20:42:59 +090092/// Magic string for the instance image
93const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
94
95/// Version of the instance image format
96const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
97
Shikha Panwar7afc1392022-03-24 08:54:43 +000098const CHUNK_RECV_MAX_LEN: usize = 1024;
99
Alan Stokes0d1ef782022-09-27 13:46:35 +0100100const MICRODROID_OS_NAME: &str = "microdroid";
101
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000102const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
103
David Brazdil73988ea2022-11-11 15:10:32 +0000104fn is_valid_guest_cid(cid: Cid) -> bool {
105 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
106}
107
108fn next_guest_cid(cid: Cid) -> Cid {
109 assert!(is_valid_guest_cid(cid));
110 if cid == GUEST_CID_MAX {
111 GUEST_CID_MIN
112 } else {
113 cid + 1
114 }
115}
116
David Brazdil528e0472022-10-10 15:06:02 +0100117/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
118/// singleton servers, like tombstone receiver.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900119#[derive(Debug, Default)]
David Brazdil528e0472022-10-10 15:06:02 +0100120pub struct VirtualizationServiceInternal {
121 state: Arc<Mutex<GlobalState>>,
122}
123
124impl VirtualizationServiceInternal {
125 pub fn init() -> VirtualizationServiceInternal {
126 let service = VirtualizationServiceInternal::default();
127
128 std::thread::spawn(|| {
129 if let Err(e) = handle_stream_connection_tombstoned() {
130 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
131 }
132 });
133
134 service
135 }
136}
137
138impl Interface for VirtualizationServiceInternal {}
139
140impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
141 fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
142 let state = &mut *self.state.lock().unwrap();
143 let cid = state.allocate_cid().map_err(|e| {
144 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
145 })?;
146 Ok(GlobalVmContext::create(cid))
147 }
148}
149
150/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
151/// of this struct.
152#[derive(Debug, Default)]
David Brazdil73988ea2022-11-11 15:10:32 +0000153struct GlobalState {
154 /// CIDs currently allocated to running VMs. A CID is never recycled as long
155 /// as there is a strong reference held by a GlobalVmContext.
156 held_cids: HashMap<Cid, Weak<Cid>>,
157}
David Brazdil528e0472022-10-10 15:06:02 +0100158
159impl GlobalState {
160 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
161 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
162 /// Android is up.
David Brazdil73988ea2022-11-11 15:10:32 +0000163 fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
164 // Garbage collect unused CIDs.
165 self.held_cids.retain(|_, cid| cid.strong_count() > 0);
166
167 // Start trying to find a CID from the last used CID + 1. This ensures
168 // that we do not eagerly recycle CIDs, which makes debugging easier.
169 let last_cid_prop =
170 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
171 Ok(num) => {
172 if is_valid_guest_cid(num) {
173 Some(num)
174 } else {
175 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
176 None
177 }
178 }
David Brazdil528e0472022-10-10 15:06:02 +0100179 Err(_) => {
180 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000181 None
David Brazdil528e0472022-10-10 15:06:02 +0100182 }
David Brazdil73988ea2022-11-11 15:10:32 +0000183 });
184
185 let first_cid = if let Some(last_cid) = last_cid_prop {
186 next_guest_cid(last_cid)
187 } else {
188 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100189 };
David Brazdil73988ea2022-11-11 15:10:32 +0000190
191 let cid = self
192 .find_available_cid(first_cid..=GUEST_CID_MAX)
193 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
194
195 if let Some(cid) = cid {
196 let cid_arc = Arc::new(cid);
197 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
198 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
199 Ok(cid_arc)
200 } else {
201 Err(anyhow!("Could not find an available CID."))
202 }
203 }
204
205 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
206 where
207 I: Iterator<Item = Cid>,
208 {
209 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100210 }
211}
212
213/// Implementation of the AIDL `IGlobalVmContext` interface.
214#[derive(Debug, Default)]
215struct GlobalVmContext {
216 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000217 cid: Arc<Cid>,
218 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100219 #[allow(dead_code)]
220 lazy_service_guard: LazyServiceGuard,
221}
222
223impl GlobalVmContext {
David Brazdil73988ea2022-11-11 15:10:32 +0000224 fn create(cid: Arc<Cid>) -> Strong<dyn IGlobalVmContext> {
David Brazdil528e0472022-10-10 15:06:02 +0100225 let binder = GlobalVmContext { cid, ..Default::default() };
226 BnGlobalVmContext::new_binder(binder, BinderFeatures::default())
227 }
228}
229
230impl Interface for GlobalVmContext {}
231
232impl IGlobalVmContext for GlobalVmContext {
233 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000234 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100235 }
236}
237
238/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
239#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000240pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900241 state: Arc<Mutex<State>>,
David Brazdil528e0472022-10-10 15:06:02 +0100242 global_service: Strong<dyn IVirtualizationServiceInternal>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000243}
244
Shikha Panward8e35422021-10-11 13:51:27 +0000245impl Interface for VirtualizationService {
246 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
247 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
248 let state = &mut *self.state.lock().unwrap();
249 let vms = state.vms();
250 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
251 for vm in vms {
252 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
253 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
254 .or(Err(StatusCode::UNKNOWN_ERROR))?;
255 writeln!(file, "\tPayload state {:?}", vm.payload_state())
256 .or(Err(StatusCode::UNKNOWN_ERROR))?;
257 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
258 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
259 .or(Err(StatusCode::UNKNOWN_ERROR))?;
260 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
261 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000262 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
263 .or(Err(StatusCode::UNKNOWN_ERROR))?;
264 }
265 Ok(())
266 }
267}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000268
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000269impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000270 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
271 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000272 ///
273 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000274 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000275 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000276 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900277 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000278 log_fd: Option<&ParcelFileDescriptor>,
279 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000280 let mut is_protected = false;
281 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000282 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000283 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000284 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000285
Andrew Walbrandff3b942021-06-09 15:20:36 +0000286 /// Initialise an empty partition image of the given size to be used as a writable partition.
287 fn initializeWritablePartition(
288 &self,
289 image_fd: &ParcelFileDescriptor,
290 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900291 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000292 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900293 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000294 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000295 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000296 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100297 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000298 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000299 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000300 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900301 // initialize the file. Any data in the file will be erased.
302 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000303 Status::new_service_specific_error_str(
304 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100305 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900306 )
307 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900308 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000309 Status::new_service_specific_error_str(
310 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100311 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000312 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000313 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000314
Jiyong Park9dd389e2021-08-23 20:42:59 +0900315 match partition_type {
316 PartitionType::RAW => Ok(()),
317 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000318 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900319 _ => Err(Error::new(
320 ErrorKind::Unsupported,
321 format!("Unsupported partition type {:?}", partition_type),
322 )),
323 }
324 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000325 Status::new_service_specific_error_str(
326 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100327 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900328 )
329 })?;
330
Andrew Walbrandff3b942021-06-09 15:20:36 +0000331 Ok(())
332 }
333
Jiyong Park0a248432021-08-20 23:32:39 +0900334 /// Creates or update the idsig file by digesting the input APK file.
335 fn createOrUpdateIdsigFile(
336 &self,
337 input_fd: &ParcelFileDescriptor,
338 idsig_fd: &ParcelFileDescriptor,
339 ) -> binder::Result<()> {
340 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
341 // idsig_fd is different from APK digest in input_fd
342
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900343 check_manage_access()?;
344
Jiyong Park0a248432021-08-20 23:32:39 +0900345 let mut input = clone_file(input_fd)?;
346 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
347
348 let mut output = clone_file(idsig_fd)?;
349 output.set_len(0).unwrap();
350 sig.write_into(&mut output).unwrap();
351 Ok(())
352 }
353
Andrew Walbran320b5602021-03-04 16:11:12 +0000354 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
355 /// and as such is only permitted from the shell user.
356 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000357 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000358
359 let state = &mut *self.state.lock().unwrap();
360 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000361 let cids = vms
362 .into_iter()
363 .map(|vm| VirtualMachineDebugInfo {
364 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000365 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000366 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000367 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000368 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000369 })
370 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000371 Ok(cids)
372 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000373
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000374 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
375 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000376 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000377 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000378
David Brazdil3c2ddef2021-03-18 13:09:57 +0000379 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000380 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000381 Ok(())
382 }
383
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000384 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
385 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
386 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000387 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000388 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000389
390 let state = &mut *self.state.lock().unwrap();
391 Ok(state.debug_drop_vm(cid))
392 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000393}
394
Shikha Panwar7afc1392022-03-24 08:54:43 +0000395fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000396 // Should not listen for tombstones on a guest VM's port.
397 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000398 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000399 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000400 for incoming_stream in listener.incoming() {
401 let mut incoming_stream = match incoming_stream {
402 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100403 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000404 continue;
405 }
406 Ok(s) => s,
407 };
408 std::thread::spawn(move || {
409 if let Err(e) = handle_tombstone(&mut incoming_stream) {
410 error!("Failed to write tombstone- {:?}", e);
411 }
412 });
413 }
414 Ok(())
415}
416
417fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000418 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000419 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
420 }
421 let tb_connection =
422 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
423 .context("Failed to connect to tombstoned")?;
424 let mut text_output = tb_connection
425 .text_output
426 .as_ref()
427 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
428 let mut num_bytes_read = 0;
429 loop {
430 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
431 let n = stream
432 .read(&mut chunk_recv)
433 .context("Failed to read tombstone data from Vsock stream")?;
434 if n == 0 {
435 break;
436 }
437 num_bytes_read += n;
438 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
439 }
440 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
441 tb_connection.notify_completion()?;
442 Ok(())
443}
444
Jiyong Park8611a6c2021-07-09 18:17:44 +0900445impl VirtualizationService {
446 pub fn init() -> VirtualizationService {
David Brazdil528e0472022-10-10 15:06:02 +0100447 let global_service = VirtualizationServiceInternal::init();
448 let global_service =
449 BnVirtualizationServiceInternal::new_binder(global_service, BinderFeatures::default());
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900450
David Brazdil73988ea2022-11-11 15:10:32 +0000451 VirtualizationService { global_service, state: Default::default() }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900452 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000453
454 fn create_vm_internal(
455 &self,
456 config: &VirtualMachineConfig,
457 console_fd: Option<&ParcelFileDescriptor>,
458 log_fd: Option<&ParcelFileDescriptor>,
459 is_protected: &mut bool,
460 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
461 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900462
Alan Stokes7bc146c2022-10-20 17:10:32 +0100463 let is_custom = match config {
464 VirtualMachineConfig::RawConfig(_) => true,
465 VirtualMachineConfig::AppConfig(config) => {
466 // Some features are reserved for platform apps only, even when using
467 // VirtualMachineAppConfig:
468 // - controlling CPUs;
469 // - specifying a config file in the APK.
470 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900471 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100472 };
473 if is_custom {
474 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900475 }
476
David Brazdil528e0472022-10-10 15:06:02 +0100477 let vm_context = self.global_service.allocateGlobalVmContext()?;
478 let cid = vm_context.getCid()? as Cid;
479
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000480 let state = &mut *self.state.lock().unwrap();
481 let console_fd = console_fd.map(clone_file).transpose()?;
482 let log_fd = log_fd.map(clone_file).transpose()?;
483 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000484 let requester_debug_pid = ThreadState::get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000485
486 // Counter to generate unique IDs for temporary image files.
487 let mut next_temporary_image_id = 0;
488 // Files which are referred to from composite images. These must be mapped to the crosvm
489 // child process, and not closed before it is started.
490 let mut indirect_files = vec![];
491
492 // Make directory for temporary files.
493 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
494 create_dir(&temporary_directory).map_err(|e| {
495 // At this point, we do not know the protected status of Vm
496 // setting it to false, though this may not be correct.
497 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100498 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000499 temporary_directory, e
500 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000501 Status::new_service_specific_error_str(
502 -1,
503 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100504 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000505 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000506 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000507 )
508 })?;
509
Alan Stokes7bc146c2022-10-20 17:10:32 +0100510 let (is_app_config, config) = match config {
511 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
512 VirtualMachineConfig::AppConfig(config) => {
513 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000514 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100515 let message = format!("Failed to load app config: {:?}", e);
516 error!("{}", message);
517 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100518 })?;
519 (true, BorrowedOrOwned::Owned(config))
520 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000521 };
522 let config = config.as_ref();
523 *is_protected = config.protectedVm;
524
525 // Check if partition images are labeled incorrectly. This is to prevent random images
526 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100527 // being loaded in a pVM. This applies to everything in the raw config, and everything but
528 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000529 config
530 .disks
531 .iter()
532 .flat_map(|disk| disk.partitions.iter())
533 .filter(|partition| {
534 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100535 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000536 } else {
537 true // all partitions are checked
538 }
539 })
540 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100541 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000542
543 let zero_filler_path = temporary_directory.join("zero.img");
544 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100545 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000546 Status::new_service_specific_error_str(
547 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100548 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000549 )
550 })?;
551
552 // Assemble disk images if needed.
553 let disks = config
554 .disks
555 .iter()
556 .map(|disk| {
557 assemble_disk_image(
558 disk,
559 &zero_filler_path,
560 &temporary_directory,
561 &mut next_temporary_image_id,
562 &mut indirect_files,
563 )
564 })
565 .collect::<Result<Vec<DiskFile>, _>>()?;
566
Jiyong Parke558ab12022-07-07 20:18:55 +0900567 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
568 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900569 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900570 // will be sent back to the client (i.e. the VM owner) for readout.
571 let ramdump_path = temporary_directory.join("ramdump");
572 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100573 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000574 Status::new_service_specific_error_str(
575 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100576 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900577 )
578 })?;
579
David Brazdil73988ea2022-11-11 15:10:32 +0000580 // Start VM service listening for connections from the new CID on port=CID.
581 // TODO(b/245727626): Only accept connections from the new VM.
582 let vm_service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
583 let vm_server = RpcServer::new_vsock(vm_service, cid).map_err(|e| {
584 error!("Failed to start VirtualMachineService: {:?}", e);
585 Status::new_service_specific_error_str(
586 -1,
587 Some(format!("Failed to start VirtualMachineService: {:?}", e)),
588 )
589 })?;
590 vm_server.start();
591
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000592 // Actually start the VM.
593 let crosvm_config = CrosvmConfig {
594 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000595 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000596 bootloader: maybe_clone_file(&config.bootloader)?,
597 kernel: maybe_clone_file(&config.kernel)?,
598 initrd: maybe_clone_file(&config.initrd)?,
599 disks,
600 params: config.params.to_owned(),
601 protected: *is_protected,
602 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
603 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900604 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000605 console_fd,
606 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900607 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000608 indirect_files,
609 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900610 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000611 };
612 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100613 VmInstance::new(
614 crosvm_config,
615 temporary_directory,
616 requester_uid,
617 requester_debug_pid,
618 vm_context,
David Brazdil73988ea2022-11-11 15:10:32 +0000619 vm_server,
David Brazdil528e0472022-10-10 15:06:02 +0100620 )
621 .map_err(|e| {
622 error!("Failed to create VM with config {:?}: {:?}", config, e);
623 Status::new_service_specific_error_str(
624 -1,
625 Some(format!("Failed to create VM: {:?}", e)),
626 )
627 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000628 );
629 state.add_vm(Arc::downgrade(&instance));
630 Ok(VirtualMachine::create(instance))
631 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900632}
633
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000634fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900635 let file = OpenOptions::new()
636 .create_new(true)
637 .read(true)
638 .write(true)
639 .open(zero_filler_path)
640 .with_context(|| "Failed to create zero.img")?;
641 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000642 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900643}
644
Jiyong Park9dd389e2021-08-23 20:42:59 +0900645fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
646 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
647 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
648 part.flush()
649}
650
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000651fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
652 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
653 part.flush()
654}
655
Jiyong Parke558ab12022-07-07 20:18:55 +0900656fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800657 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900658}
659
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000660/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
661///
662/// This may involve assembling a composite disk from a set of partition images.
663fn assemble_disk_image(
664 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900665 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000666 temporary_directory: &Path,
667 next_temporary_image_id: &mut u64,
668 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000669) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000670 let image = if !disk.partitions.is_empty() {
671 if disk.image.is_some() {
672 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000673 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000674 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000675 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000676 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000677 }
678
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000679 let composite_image_filenames =
680 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
681 let (image, partition_files) = make_composite_image(
682 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900683 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000684 &composite_image_filenames.composite,
685 &composite_image_filenames.header,
686 &composite_image_filenames.footer,
687 )
688 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100689 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000690 Status::new_service_specific_error_str(
691 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100692 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000693 )
694 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000695
696 // Pass the file descriptors for the various partition files to crosvm when it
697 // is run.
698 indirect_files.extend(partition_files);
699
700 image
701 } else if let Some(image) = &disk.image {
702 clone_file(image)?
703 } else {
704 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000705 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000706 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000707 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000708 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000709 };
710
711 Ok(DiskFile { image, writable: disk.writable })
712}
713
Jooyung Han21e9b922021-06-26 04:14:16 +0900714fn load_app_config(
715 config: &VirtualMachineAppConfig,
716 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900717) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000718 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
719 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900720 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900721
Shikha Panwar22e70452022-10-10 18:32:55 +0000722 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
723 Some(clone_file(file)?)
724 } else {
725 None
726 };
727
Alan Stokes0d1ef782022-09-27 13:46:35 +0100728 let vm_payload_config = match &config.payload {
729 Payload::ConfigPath(config_path) => {
730 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
731 .with_context(|| format!("Couldn't read config from {}", config_path))?
732 }
733 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
734 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900735
Alan Stokes0d1ef782022-09-27 13:46:35 +0100736 // For now, the only supported OS is Microdroid
737 let os_name = vm_payload_config.os.name.as_str();
738 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000739 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900740 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000741
742 // It is safe to construct a filename based on the os_name because we've already checked that it
743 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900744 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
745 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000746 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900747
Andrew Walbrancc045902021-07-27 16:06:17 +0000748 if config.memoryMib > 0 {
749 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000750 }
751
Seungjae Yoo62085c02022-08-12 04:44:52 +0000752 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000753 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900754 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900755 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900756
Shikha Panwar22e70452022-10-10 18:32:55 +0000757 // Microdroid takes additional init ramdisk & (optionally) storage image
758 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
759
760 // Include Microdroid payload disk (contains apks, idsigs) in vm config
761 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100762 config,
763 temporary_directory,
764 apk_file,
765 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100766 &vm_payload_config,
767 &mut vm_config,
768 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900769
Andrew Walbrancc0db522021-07-12 17:03:42 +0000770 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900771}
772
Alan Stokes0d1ef782022-09-27 13:46:35 +0100773fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
774 let mut apk_zip = ZipArchive::new(apk_file)?;
775 let config_file = apk_zip.by_name(config_path)?;
776 Ok(serde_json::from_reader(config_file)?)
777}
778
779fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
780 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
781 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
782 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100783 let task =
784 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100785 VmPayloadConfig {
786 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
787 task: Some(task),
788 apexes: vec![],
789 extra_apks: vec![],
790 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100791 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100792 enable_authfs: false,
793 }
794}
795
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000796/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000797fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000798 temporary_directory: &Path,
799 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000800) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000801 let id = *next_temporary_image_id;
802 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000803 CompositeImageFilenames {
804 composite: temporary_directory.join(format!("composite-{}.img", id)),
805 header: temporary_directory.join(format!("composite-{}-header.img", id)),
806 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
807 }
808}
809
810/// Filenames for a composite disk image, including header and footer partitions.
811#[derive(Clone, Debug, Eq, PartialEq)]
812struct CompositeImageFilenames {
813 /// The composite disk image itself.
814 composite: PathBuf,
815 /// The header partition image.
816 header: PathBuf,
817 /// The footer partition image.
818 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000819}
820
Jiyong Park753553b2021-07-12 21:21:09 +0900821/// Checks whether the caller has a specific permission
822fn check_permission(perm: &str) -> binder::Result<()> {
823 let calling_pid = ThreadState::get_calling_pid();
824 let calling_uid = ThreadState::get_calling_uid();
825 // Root can do anything
826 if calling_uid == 0 {
827 return Ok(());
828 }
829 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
830 binder::get_interface("permission")?;
831 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000832 Ok(())
833 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000834 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900835 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000836 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900837 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000838 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000839}
840
Jiyong Park753553b2021-07-12 21:21:09 +0900841/// Check whether the caller of the current Binder method is allowed to call debug methods.
842fn check_debug_access() -> binder::Result<()> {
843 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
844}
845
846/// Check whether the caller of the current Binder method is allowed to manage VMs
847fn check_manage_access() -> binder::Result<()> {
848 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
849}
850
Inseob Kim1119d702022-05-02 18:01:58 +0900851/// Check whether the caller of the current Binder method is allowed to create custom VMs
852fn check_use_custom_virtual_machine() -> binder::Result<()> {
853 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
854}
855
Jiyong Park029977d2021-11-24 21:56:49 +0900856/// Check if a partition has selinux labels that are not allowed
857fn check_label_for_partition(partition: &Partition) -> Result<()> {
858 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100859 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
860}
861
862// Return whether a partition is exempt from selinux label checks, because we know that it does
863// not contain code and is likely to be generated in an app-writable directory.
864fn is_safe_app_partition(label: &str) -> bool {
865 // See make_payload_disk in payload.rs.
866 label == "vm-instance"
867 || label == "microdroid-apk-idsig"
868 || label == "payload-metadata"
869 || label.starts_with("extra-idsig-")
870}
871
872fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
873 // We only want to allow code in a VM payload to be sourced from places that apps, and the
874 // system, do not have write access to.
875 // (Note that sepolicy must also grant read access for these types to both virtualization
876 // service and crosvm.)
877 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
878 // user devices (W^X).
879 match ctx.selinux_type()? {
880 | "system_file" // immutable dm-verity protected partition
881 | "apk_data_file" // APKs of an installed app
882 | "staging_data_file" // updated/staged APEX imagess
883 | "shell_data_file" // test files created via adb shell
884 => Ok(()),
885 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900886 }
887}
888
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000889/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
890#[derive(Debug)]
891struct VirtualMachine {
892 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100893 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800894 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100895 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000896}
897
898impl VirtualMachine {
899 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100900 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000901 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000902 }
903}
904
905impl Interface for VirtualMachine {}
906
907impl IVirtualMachine for VirtualMachine {
908 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900909 // Don't check permission. The owner of the VM might have passed this binder object to
910 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000911 Ok(self.instance.cid as i32)
912 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000913
Andrew Walbran6b650662021-09-07 13:13:23 +0000914 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900915 // Don't check permission. The owner of the VM might have passed this binder object to
916 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000917 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000918 }
919
920 fn registerCallback(
921 &self,
922 callback: &Strong<dyn IVirtualMachineCallback>,
923 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900924 // Don't check permission. The owner of the VM might have passed this binder object to
925 // others.
926 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000927 // TODO: Should this give an error if the VM is already dead?
928 self.instance.callbacks.add(callback.clone());
929 Ok(())
930 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000931
Andrew Walbranf8d94112021-09-07 11:45:36 +0000932 fn start(&self) -> binder::Result<()> {
933 self.instance.start().map_err(|e| {
934 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000935 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000936 })
937 }
938
Inseob Kima446f802022-07-11 19:46:37 +0900939 fn stop(&self) -> binder::Result<()> {
940 self.instance.kill().map_err(|e| {
941 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000942 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900943 })
944 }
945
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000946 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000947 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000948 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000949 }
950 let stream =
951 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000952 Status::new_service_specific_error_str(
953 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100954 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000955 )
956 })?;
957 Ok(vsock_stream_to_pfd(stream))
958 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000959}
960
961impl Drop for VirtualMachine {
962 fn drop(&mut self) {
963 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900964 if let Err(e) = self.instance.kill() {
965 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
966 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000967 }
968}
969
970/// A set of Binders to be called back in response to various events on the VM, such as when it
971/// dies.
972#[derive(Debug, Default)]
973pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
974
975impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900976 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100977 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900978 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900979 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100980 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100981 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900982 }
983 }
984 }
985
Inseob Kim14cb8692021-08-31 21:50:39 +0900986 /// Call all registered callbacks to notify that the payload is ready to serve.
987 pub fn notify_payload_ready(&self, cid: Cid) {
988 let callbacks = &*self.0.lock().unwrap();
989 for callback in callbacks {
990 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100991 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900992 }
993 }
994 }
995
Inseob Kim2444af92021-08-31 01:22:50 +0900996 /// Call all registered callbacks to notify that the payload has finished.
997 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
998 let callbacks = &*self.0.lock().unwrap();
999 for callback in callbacks {
1000 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001001 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001002 }
1003 }
1004 }
1005
Jooyung Handd0a1732021-11-23 15:26:20 +09001006 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001007 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001008 let callbacks = &*self.0.lock().unwrap();
1009 for callback in callbacks {
1010 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001011 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001012 }
1013 }
1014 }
1015
Andrew Walbrandae07162021-03-12 17:05:20 +00001016 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001017 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001018 let callbacks = &*self.0.lock().unwrap();
1019 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001020 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001021 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001022 }
1023 }
1024 }
1025
Jiyong Parke558ab12022-07-07 20:18:55 +09001026 /// Call all registered callbacks to say that there was a ramdump to download.
1027 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
1028 let callbacks = &*self.0.lock().unwrap();
1029 let pfd = ParcelFileDescriptor::new(ramdump);
1030 for callback in callbacks {
1031 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001032 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +09001033 }
1034 }
1035 }
1036
Andrew Walbrandae07162021-03-12 17:05:20 +00001037 /// Add a new callback to the set.
1038 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1039 self.0.lock().unwrap().push(callback);
1040 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001041}
1042
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001043/// The mutable state of the VirtualizationService. There should only be one instance of this
1044/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001045#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001046struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001047 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1048 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1049 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1050 /// from the list opportunistically the next time `add_vm` is called.
1051 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001052
1053 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1054 /// This is only used for debugging purposes.
1055 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001056}
1057
1058impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001059 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001060 fn vms(&self) -> Vec<Arc<VmInstance>> {
1061 // Attempt to upgrade the weak pointers to strong pointers.
1062 self.vms.iter().filter_map(Weak::upgrade).collect()
1063 }
1064
1065 /// Add a new VM to the list.
1066 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1067 // Garbage collect any entries from the stored list which no longer exist.
1068 self.vms.retain(|vm| vm.strong_count() > 0);
1069
1070 // Actually add the new VM.
1071 self.vms.push(vm);
1072 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001073
Jiyong Park8611a6c2021-07-09 18:17:44 +09001074 /// Get a VM that corresponds to the given cid
1075 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1076 self.vms().into_iter().find(|vm| vm.cid == cid)
1077 }
1078
David Brazdil3c2ddef2021-03-18 13:09:57 +00001079 /// Store a strong VM reference.
1080 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1081 self.debug_held_vms.push(vm);
1082 }
1083
1084 /// Retrieve and remove a strong VM reference.
1085 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1086 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001087 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001088 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001089 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001090}
1091
Andrew Walbran6b650662021-09-07 13:13:23 +00001092/// Gets the `VirtualMachineState` of the given `VmInstance`.
1093fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001094 match &*instance.vm_state.lock().unwrap() {
1095 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1096 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001097 PayloadState::Starting => VirtualMachineState::STARTING,
1098 PayloadState::Started => VirtualMachineState::STARTED,
1099 PayloadState::Ready => VirtualMachineState::READY,
1100 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001101 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001102 },
1103 VmState::Dead => VirtualMachineState::DEAD,
1104 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001105 }
1106}
1107
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001108/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001109pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001110 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001111 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001112 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001113 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001114 )
1115 })
1116}
1117
Andrew Walbrand3a84182021-09-07 14:48:52 +00001118/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1119fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1120 file.as_ref().map(clone_file).transpose()
1121}
1122
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001123/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1124fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1125 // SAFETY: ownership is transferred from stream to f
1126 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1127 ParcelFileDescriptor::new(f)
1128}
1129
Jiyong Parkdcf17412022-02-08 15:07:23 +09001130/// Parses the platform version requirement string.
1131fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1132 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001133 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001134 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001135 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001136 )
1137 })
1138}
1139
Jooyung Han35edb8f2021-07-01 16:17:16 +09001140/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1141/// it doesn't require that T implements Clone.
1142enum BorrowedOrOwned<'a, T> {
1143 Borrowed(&'a T),
1144 Owned(T),
1145}
1146
1147impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1148 fn as_ref(&self) -> &T {
1149 match self {
1150 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001151 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001152 }
1153 }
1154}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001155
1156/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1157#[derive(Debug, Default)]
1158struct VirtualMachineService {
1159 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001160 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001161}
1162
1163impl Interface for VirtualMachineService {}
1164
1165impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001166 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1167 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001168 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001169 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001170 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1171 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1172 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001173 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001174
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001175 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1176 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001177 Ok(())
1178 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001179 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001180 Err(Status::new_service_specific_error_str(
1181 -1,
1182 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001183 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001184 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001185 }
Inseob Kim2444af92021-08-31 01:22:50 +09001186
Inseob Kimc7d28c72021-10-25 14:28:10 +00001187 fn notifyPayloadReady(&self) -> binder::Result<()> {
1188 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001189 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001190 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001191 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1192 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1193 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001194 vm.callbacks.notify_payload_ready(cid);
1195 Ok(())
1196 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001197 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001198 Err(Status::new_service_specific_error_str(
1199 -1,
1200 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001201 ))
1202 }
1203 }
1204
Inseob Kimc7d28c72021-10-25 14:28:10 +00001205 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1206 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001207 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001208 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001209 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1210 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1211 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001212 vm.callbacks.notify_payload_finished(cid, exit_code);
1213 Ok(())
1214 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001215 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001216 Err(Status::new_service_specific_error_str(
1217 -1,
1218 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001219 ))
1220 }
1221 }
1222
Alan Stokes2bead0d2022-09-05 16:58:34 +01001223 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001224 let cid = self.cid;
1225 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001226 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001227 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1228 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1229 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001230 vm.callbacks.notify_error(cid, error_code, message);
1231 Ok(())
1232 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001233 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001234 Err(Status::new_service_specific_error_str(
1235 -1,
1236 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001237 ))
1238 }
1239 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001240}
1241
1242impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001243 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001244 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001245 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001246 BinderFeatures::default(),
1247 )
1248 }
1249}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001250
1251#[cfg(test)]
1252mod tests {
1253 use super::*;
1254
1255 #[test]
1256 fn test_is_allowed_label_for_partition() -> Result<()> {
1257 let expected_results = vec![
1258 ("u:object_r:system_file:s0", true),
1259 ("u:object_r:apk_data_file:s0", true),
1260 ("u:object_r:app_data_file:s0", false),
1261 ("u:object_r:app_data_file:s0:c512,c768", false),
1262 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1263 ("invalid", false),
1264 ("user:role:apk_data_file:severity:categories", true),
1265 ("user:role:apk_data_file:severity:categories:extraneous", false),
1266 ];
1267
1268 for (label, expected_valid) in expected_results {
1269 let context = SeContext::new(label)?;
1270 let result = check_label_is_allowed(&context);
1271 if expected_valid {
1272 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1273 } else if result.is_ok() {
1274 bail!("Expected label {} to be disallowed", label);
1275 }
1276 }
1277 Ok(())
1278 }
1279}