blob: 040c0d83bd7fad0d874d88fe8301ebbefb2f0b45 [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;
David Brazdil8cf8f482022-11-23 14:21:26 +000019use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, 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
David Brazdil8cf8f482022-11-23 14:21:26 +0000168 // that we do not eagerly recycle CIDs. It makes debugging easier but
169 // also means that retrying to allocate a CID, eg. because it is
170 // erroneously occupied by a process, will not recycle the same CID.
David Brazdil73988ea2022-11-11 15:10:32 +0000171 let last_cid_prop =
172 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
173 Ok(num) => {
174 if is_valid_guest_cid(num) {
175 Some(num)
176 } else {
177 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
178 None
179 }
180 }
David Brazdil528e0472022-10-10 15:06:02 +0100181 Err(_) => {
182 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000183 None
David Brazdil528e0472022-10-10 15:06:02 +0100184 }
David Brazdil73988ea2022-11-11 15:10:32 +0000185 });
186
187 let first_cid = if let Some(last_cid) = last_cid_prop {
188 next_guest_cid(last_cid)
189 } else {
190 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100191 };
David Brazdil73988ea2022-11-11 15:10:32 +0000192
193 let cid = self
194 .find_available_cid(first_cid..=GUEST_CID_MAX)
195 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
196
197 if let Some(cid) = cid {
198 let cid_arc = Arc::new(cid);
199 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
200 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
201 Ok(cid_arc)
202 } else {
203 Err(anyhow!("Could not find an available CID."))
204 }
205 }
206
207 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
208 where
209 I: Iterator<Item = Cid>,
210 {
211 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100212 }
213}
214
215/// Implementation of the AIDL `IGlobalVmContext` interface.
216#[derive(Debug, Default)]
217struct GlobalVmContext {
218 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000219 cid: Arc<Cid>,
220 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100221 #[allow(dead_code)]
222 lazy_service_guard: LazyServiceGuard,
223}
224
225impl GlobalVmContext {
David Brazdil73988ea2022-11-11 15:10:32 +0000226 fn create(cid: Arc<Cid>) -> Strong<dyn IGlobalVmContext> {
David Brazdil528e0472022-10-10 15:06:02 +0100227 let binder = GlobalVmContext { cid, ..Default::default() };
228 BnGlobalVmContext::new_binder(binder, BinderFeatures::default())
229 }
230}
231
232impl Interface for GlobalVmContext {}
233
234impl IGlobalVmContext for GlobalVmContext {
235 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000236 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100237 }
238}
239
240/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
241#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000242pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900243 state: Arc<Mutex<State>>,
David Brazdil528e0472022-10-10 15:06:02 +0100244 global_service: Strong<dyn IVirtualizationServiceInternal>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000245}
246
Shikha Panward8e35422021-10-11 13:51:27 +0000247impl Interface for VirtualizationService {
248 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
249 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
250 let state = &mut *self.state.lock().unwrap();
251 let vms = state.vms();
252 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
253 for vm in vms {
254 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
255 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
256 .or(Err(StatusCode::UNKNOWN_ERROR))?;
257 writeln!(file, "\tPayload state {:?}", vm.payload_state())
258 .or(Err(StatusCode::UNKNOWN_ERROR))?;
259 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
260 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
261 .or(Err(StatusCode::UNKNOWN_ERROR))?;
262 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
263 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000264 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
265 .or(Err(StatusCode::UNKNOWN_ERROR))?;
266 }
267 Ok(())
268 }
269}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000270
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000271impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000272 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
273 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000274 ///
275 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000276 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000277 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000278 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900279 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000280 log_fd: Option<&ParcelFileDescriptor>,
281 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000282 let mut is_protected = false;
283 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000284 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000285 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000286 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000287
Andrew Walbrandff3b942021-06-09 15:20:36 +0000288 /// Initialise an empty partition image of the given size to be used as a writable partition.
289 fn initializeWritablePartition(
290 &self,
291 image_fd: &ParcelFileDescriptor,
292 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900293 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000294 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900295 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000296 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000297 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000298 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100299 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000300 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000301 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000302 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900303 // initialize the file. Any data in the file will be erased.
304 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000305 Status::new_service_specific_error_str(
306 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100307 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900308 )
309 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900310 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000311 Status::new_service_specific_error_str(
312 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100313 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000314 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000315 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000316
Jiyong Park9dd389e2021-08-23 20:42:59 +0900317 match partition_type {
318 PartitionType::RAW => Ok(()),
319 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000320 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900321 _ => Err(Error::new(
322 ErrorKind::Unsupported,
323 format!("Unsupported partition type {:?}", partition_type),
324 )),
325 }
326 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000327 Status::new_service_specific_error_str(
328 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100329 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900330 )
331 })?;
332
Andrew Walbrandff3b942021-06-09 15:20:36 +0000333 Ok(())
334 }
335
Jiyong Park0a248432021-08-20 23:32:39 +0900336 /// Creates or update the idsig file by digesting the input APK file.
337 fn createOrUpdateIdsigFile(
338 &self,
339 input_fd: &ParcelFileDescriptor,
340 idsig_fd: &ParcelFileDescriptor,
341 ) -> binder::Result<()> {
342 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
343 // idsig_fd is different from APK digest in input_fd
344
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900345 check_manage_access()?;
346
Jiyong Park0a248432021-08-20 23:32:39 +0900347 let mut input = clone_file(input_fd)?;
348 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
349
350 let mut output = clone_file(idsig_fd)?;
351 output.set_len(0).unwrap();
352 sig.write_into(&mut output).unwrap();
353 Ok(())
354 }
355
Andrew Walbran320b5602021-03-04 16:11:12 +0000356 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
357 /// and as such is only permitted from the shell user.
358 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000359 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000360
361 let state = &mut *self.state.lock().unwrap();
362 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000363 let cids = vms
364 .into_iter()
365 .map(|vm| VirtualMachineDebugInfo {
366 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000367 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000368 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000369 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000370 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000371 })
372 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000373 Ok(cids)
374 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000375
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000376 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
377 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000378 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000379 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000380
David Brazdil3c2ddef2021-03-18 13:09:57 +0000381 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000382 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000383 Ok(())
384 }
385
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000386 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
387 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
388 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000389 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000390 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000391
392 let state = &mut *self.state.lock().unwrap();
393 Ok(state.debug_drop_vm(cid))
394 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000395}
396
Shikha Panwar7afc1392022-03-24 08:54:43 +0000397fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000398 // Should not listen for tombstones on a guest VM's port.
399 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000400 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000401 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000402 for incoming_stream in listener.incoming() {
403 let mut incoming_stream = match incoming_stream {
404 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100405 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000406 continue;
407 }
408 Ok(s) => s,
409 };
410 std::thread::spawn(move || {
411 if let Err(e) = handle_tombstone(&mut incoming_stream) {
412 error!("Failed to write tombstone- {:?}", e);
413 }
414 });
415 }
416 Ok(())
417}
418
419fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000420 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000421 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
422 }
423 let tb_connection =
424 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
425 .context("Failed to connect to tombstoned")?;
426 let mut text_output = tb_connection
427 .text_output
428 .as_ref()
429 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
430 let mut num_bytes_read = 0;
431 loop {
432 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
433 let n = stream
434 .read(&mut chunk_recv)
435 .context("Failed to read tombstone data from Vsock stream")?;
436 if n == 0 {
437 break;
438 }
439 num_bytes_read += n;
440 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
441 }
442 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
443 tb_connection.notify_completion()?;
444 Ok(())
445}
446
Jiyong Park8611a6c2021-07-09 18:17:44 +0900447impl VirtualizationService {
448 pub fn init() -> VirtualizationService {
David Brazdil528e0472022-10-10 15:06:02 +0100449 let global_service = VirtualizationServiceInternal::init();
450 let global_service =
451 BnVirtualizationServiceInternal::new_binder(global_service, BinderFeatures::default());
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900452
David Brazdil73988ea2022-11-11 15:10:32 +0000453 VirtualizationService { global_service, state: Default::default() }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900454 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000455
David Brazdil8cf8f482022-11-23 14:21:26 +0000456 fn create_vm_context(&self) -> Result<(VmContext, Cid)> {
457 const NUM_ATTEMPTS: usize = 5;
458
459 for _ in 0..NUM_ATTEMPTS {
460 let global_context = self.global_service.allocateGlobalVmContext()?;
461 let cid = global_context.getCid()? as Cid;
462 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
463
464 // Start VM service listening for connections from the new CID on port=CID.
465 // TODO(b/245727626): Only accept connections from the new VM.
466 let port = cid;
467 match RpcServer::new_vsock(service, port) {
468 Ok(vm_server) => {
469 vm_server.start();
470 return Ok((VmContext::new(global_context, vm_server), cid));
471 }
472 Err(err) => {
473 warn!("Could not start RpcServer on port {}: {}", port, err);
474 }
475 }
476 }
477 bail!("Too many attempts to create VM context failed.");
478 }
479
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000480 fn create_vm_internal(
481 &self,
482 config: &VirtualMachineConfig,
483 console_fd: Option<&ParcelFileDescriptor>,
484 log_fd: Option<&ParcelFileDescriptor>,
485 is_protected: &mut bool,
486 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
487 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900488
Alan Stokes7bc146c2022-10-20 17:10:32 +0100489 let is_custom = match config {
490 VirtualMachineConfig::RawConfig(_) => true,
491 VirtualMachineConfig::AppConfig(config) => {
492 // Some features are reserved for platform apps only, even when using
493 // VirtualMachineAppConfig:
494 // - controlling CPUs;
495 // - specifying a config file in the APK.
496 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900497 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100498 };
499 if is_custom {
500 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900501 }
502
David Brazdil8cf8f482022-11-23 14:21:26 +0000503 let (vm_context, cid) = self.create_vm_context().map_err(|e| {
504 error!("Failed to create VmContext: {:?}", e);
505 Status::new_service_specific_error_str(
506 -1,
507 Some(format!("Failed to create VmContext: {:?}", e)),
508 )
509 })?;
David Brazdil528e0472022-10-10 15:06:02 +0100510
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000511 let state = &mut *self.state.lock().unwrap();
512 let console_fd = console_fd.map(clone_file).transpose()?;
513 let log_fd = log_fd.map(clone_file).transpose()?;
514 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000515 let requester_debug_pid = ThreadState::get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000516
517 // Counter to generate unique IDs for temporary image files.
518 let mut next_temporary_image_id = 0;
519 // Files which are referred to from composite images. These must be mapped to the crosvm
520 // child process, and not closed before it is started.
521 let mut indirect_files = vec![];
522
523 // Make directory for temporary files.
524 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
525 create_dir(&temporary_directory).map_err(|e| {
526 // At this point, we do not know the protected status of Vm
527 // setting it to false, though this may not be correct.
528 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100529 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000530 temporary_directory, e
531 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000532 Status::new_service_specific_error_str(
533 -1,
534 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100535 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000536 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000537 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000538 )
539 })?;
540
Alan Stokes7bc146c2022-10-20 17:10:32 +0100541 let (is_app_config, config) = match config {
542 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
543 VirtualMachineConfig::AppConfig(config) => {
544 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000545 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100546 let message = format!("Failed to load app config: {:?}", e);
547 error!("{}", message);
548 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100549 })?;
550 (true, BorrowedOrOwned::Owned(config))
551 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000552 };
553 let config = config.as_ref();
554 *is_protected = config.protectedVm;
555
556 // Check if partition images are labeled incorrectly. This is to prevent random images
557 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100558 // being loaded in a pVM. This applies to everything in the raw config, and everything but
559 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000560 config
561 .disks
562 .iter()
563 .flat_map(|disk| disk.partitions.iter())
564 .filter(|partition| {
565 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100566 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000567 } else {
568 true // all partitions are checked
569 }
570 })
571 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100572 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000573
574 let zero_filler_path = temporary_directory.join("zero.img");
575 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100576 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000577 Status::new_service_specific_error_str(
578 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100579 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000580 )
581 })?;
582
583 // Assemble disk images if needed.
584 let disks = config
585 .disks
586 .iter()
587 .map(|disk| {
588 assemble_disk_image(
589 disk,
590 &zero_filler_path,
591 &temporary_directory,
592 &mut next_temporary_image_id,
593 &mut indirect_files,
594 )
595 })
596 .collect::<Result<Vec<DiskFile>, _>>()?;
597
Jiyong Parke558ab12022-07-07 20:18:55 +0900598 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
599 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900600 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900601 // will be sent back to the client (i.e. the VM owner) for readout.
602 let ramdump_path = temporary_directory.join("ramdump");
603 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100604 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000605 Status::new_service_specific_error_str(
606 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100607 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900608 )
609 })?;
610
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000611 // Actually start the VM.
612 let crosvm_config = CrosvmConfig {
613 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000614 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000615 bootloader: maybe_clone_file(&config.bootloader)?,
616 kernel: maybe_clone_file(&config.kernel)?,
617 initrd: maybe_clone_file(&config.initrd)?,
618 disks,
619 params: config.params.to_owned(),
620 protected: *is_protected,
621 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
622 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900623 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000624 console_fd,
625 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900626 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000627 indirect_files,
628 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900629 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000630 };
631 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100632 VmInstance::new(
633 crosvm_config,
634 temporary_directory,
635 requester_uid,
636 requester_debug_pid,
637 vm_context,
638 )
639 .map_err(|e| {
640 error!("Failed to create VM with config {:?}: {:?}", config, e);
641 Status::new_service_specific_error_str(
642 -1,
643 Some(format!("Failed to create VM: {:?}", e)),
644 )
645 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000646 );
647 state.add_vm(Arc::downgrade(&instance));
648 Ok(VirtualMachine::create(instance))
649 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900650}
651
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000652fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900653 let file = OpenOptions::new()
654 .create_new(true)
655 .read(true)
656 .write(true)
657 .open(zero_filler_path)
658 .with_context(|| "Failed to create zero.img")?;
659 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000660 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900661}
662
Jiyong Park9dd389e2021-08-23 20:42:59 +0900663fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
664 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
665 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
666 part.flush()
667}
668
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000669fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
670 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
671 part.flush()
672}
673
Jiyong Parke558ab12022-07-07 20:18:55 +0900674fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800675 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900676}
677
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000678/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
679///
680/// This may involve assembling a composite disk from a set of partition images.
681fn assemble_disk_image(
682 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900683 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000684 temporary_directory: &Path,
685 next_temporary_image_id: &mut u64,
686 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000687) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000688 let image = if !disk.partitions.is_empty() {
689 if disk.image.is_some() {
690 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000691 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000692 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000693 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000694 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000695 }
696
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000697 let composite_image_filenames =
698 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
699 let (image, partition_files) = make_composite_image(
700 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900701 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000702 &composite_image_filenames.composite,
703 &composite_image_filenames.header,
704 &composite_image_filenames.footer,
705 )
706 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100707 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000708 Status::new_service_specific_error_str(
709 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100710 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000711 )
712 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000713
714 // Pass the file descriptors for the various partition files to crosvm when it
715 // is run.
716 indirect_files.extend(partition_files);
717
718 image
719 } else if let Some(image) = &disk.image {
720 clone_file(image)?
721 } else {
722 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000723 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000724 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000725 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000726 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000727 };
728
729 Ok(DiskFile { image, writable: disk.writable })
730}
731
Jooyung Han21e9b922021-06-26 04:14:16 +0900732fn load_app_config(
733 config: &VirtualMachineAppConfig,
734 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900735) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000736 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
737 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900738 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900739
Shikha Panwar22e70452022-10-10 18:32:55 +0000740 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
741 Some(clone_file(file)?)
742 } else {
743 None
744 };
745
Alan Stokes0d1ef782022-09-27 13:46:35 +0100746 let vm_payload_config = match &config.payload {
747 Payload::ConfigPath(config_path) => {
748 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
749 .with_context(|| format!("Couldn't read config from {}", config_path))?
750 }
751 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
752 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900753
Alan Stokes0d1ef782022-09-27 13:46:35 +0100754 // For now, the only supported OS is Microdroid
755 let os_name = vm_payload_config.os.name.as_str();
756 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000757 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900758 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000759
760 // It is safe to construct a filename based on the os_name because we've already checked that it
761 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900762 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
763 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000764 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900765
Andrew Walbrancc045902021-07-27 16:06:17 +0000766 if config.memoryMib > 0 {
767 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000768 }
769
Seungjae Yoo62085c02022-08-12 04:44:52 +0000770 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000771 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900772 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900773 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900774
Shikha Panwar22e70452022-10-10 18:32:55 +0000775 // Microdroid takes additional init ramdisk & (optionally) storage image
776 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
777
778 // Include Microdroid payload disk (contains apks, idsigs) in vm config
779 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100780 config,
781 temporary_directory,
782 apk_file,
783 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100784 &vm_payload_config,
785 &mut vm_config,
786 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900787
Andrew Walbrancc0db522021-07-12 17:03:42 +0000788 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900789}
790
Alan Stokes0d1ef782022-09-27 13:46:35 +0100791fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
792 let mut apk_zip = ZipArchive::new(apk_file)?;
793 let config_file = apk_zip.by_name(config_path)?;
794 Ok(serde_json::from_reader(config_file)?)
795}
796
797fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
798 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
799 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
800 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100801 let task =
802 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100803 VmPayloadConfig {
804 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
805 task: Some(task),
806 apexes: vec![],
807 extra_apks: vec![],
808 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100809 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100810 enable_authfs: false,
811 }
812}
813
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000814/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000815fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000816 temporary_directory: &Path,
817 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000818) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000819 let id = *next_temporary_image_id;
820 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000821 CompositeImageFilenames {
822 composite: temporary_directory.join(format!("composite-{}.img", id)),
823 header: temporary_directory.join(format!("composite-{}-header.img", id)),
824 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
825 }
826}
827
828/// Filenames for a composite disk image, including header and footer partitions.
829#[derive(Clone, Debug, Eq, PartialEq)]
830struct CompositeImageFilenames {
831 /// The composite disk image itself.
832 composite: PathBuf,
833 /// The header partition image.
834 header: PathBuf,
835 /// The footer partition image.
836 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000837}
838
Jiyong Park753553b2021-07-12 21:21:09 +0900839/// Checks whether the caller has a specific permission
840fn check_permission(perm: &str) -> binder::Result<()> {
841 let calling_pid = ThreadState::get_calling_pid();
842 let calling_uid = ThreadState::get_calling_uid();
843 // Root can do anything
844 if calling_uid == 0 {
845 return Ok(());
846 }
847 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
848 binder::get_interface("permission")?;
849 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000850 Ok(())
851 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000852 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900853 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000854 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900855 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000856 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000857}
858
Jiyong Park753553b2021-07-12 21:21:09 +0900859/// Check whether the caller of the current Binder method is allowed to call debug methods.
860fn check_debug_access() -> binder::Result<()> {
861 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
862}
863
864/// Check whether the caller of the current Binder method is allowed to manage VMs
865fn check_manage_access() -> binder::Result<()> {
866 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
867}
868
Inseob Kim1119d702022-05-02 18:01:58 +0900869/// Check whether the caller of the current Binder method is allowed to create custom VMs
870fn check_use_custom_virtual_machine() -> binder::Result<()> {
871 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
872}
873
Jiyong Park029977d2021-11-24 21:56:49 +0900874/// Check if a partition has selinux labels that are not allowed
875fn check_label_for_partition(partition: &Partition) -> Result<()> {
876 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100877 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
878}
879
880// Return whether a partition is exempt from selinux label checks, because we know that it does
881// not contain code and is likely to be generated in an app-writable directory.
882fn is_safe_app_partition(label: &str) -> bool {
883 // See make_payload_disk in payload.rs.
884 label == "vm-instance"
885 || label == "microdroid-apk-idsig"
886 || label == "payload-metadata"
887 || label.starts_with("extra-idsig-")
888}
889
890fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
891 // We only want to allow code in a VM payload to be sourced from places that apps, and the
892 // system, do not have write access to.
893 // (Note that sepolicy must also grant read access for these types to both virtualization
894 // service and crosvm.)
895 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
896 // user devices (W^X).
897 match ctx.selinux_type()? {
898 | "system_file" // immutable dm-verity protected partition
899 | "apk_data_file" // APKs of an installed app
900 | "staging_data_file" // updated/staged APEX imagess
901 | "shell_data_file" // test files created via adb shell
902 => Ok(()),
903 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900904 }
905}
906
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000907/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
908#[derive(Debug)]
909struct VirtualMachine {
910 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100911 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800912 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100913 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000914}
915
916impl VirtualMachine {
917 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100918 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000919 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000920 }
921}
922
923impl Interface for VirtualMachine {}
924
925impl IVirtualMachine for VirtualMachine {
926 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900927 // Don't check permission. The owner of the VM might have passed this binder object to
928 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000929 Ok(self.instance.cid as i32)
930 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000931
Andrew Walbran6b650662021-09-07 13:13:23 +0000932 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900933 // Don't check permission. The owner of the VM might have passed this binder object to
934 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000935 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000936 }
937
938 fn registerCallback(
939 &self,
940 callback: &Strong<dyn IVirtualMachineCallback>,
941 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900942 // Don't check permission. The owner of the VM might have passed this binder object to
943 // others.
944 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000945 // TODO: Should this give an error if the VM is already dead?
946 self.instance.callbacks.add(callback.clone());
947 Ok(())
948 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000949
Andrew Walbranf8d94112021-09-07 11:45:36 +0000950 fn start(&self) -> binder::Result<()> {
951 self.instance.start().map_err(|e| {
952 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000953 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000954 })
955 }
956
Inseob Kima446f802022-07-11 19:46:37 +0900957 fn stop(&self) -> binder::Result<()> {
958 self.instance.kill().map_err(|e| {
959 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000960 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900961 })
962 }
963
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000964 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000965 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000966 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000967 }
968 let stream =
969 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000970 Status::new_service_specific_error_str(
971 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100972 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000973 )
974 })?;
975 Ok(vsock_stream_to_pfd(stream))
976 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000977}
978
979impl Drop for VirtualMachine {
980 fn drop(&mut self) {
981 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900982 if let Err(e) = self.instance.kill() {
983 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
984 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000985 }
986}
987
988/// A set of Binders to be called back in response to various events on the VM, such as when it
989/// dies.
990#[derive(Debug, Default)]
991pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
992
993impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900994 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100995 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900996 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900997 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100998 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100999 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001000 }
1001 }
1002 }
1003
Inseob Kim14cb8692021-08-31 21:50:39 +09001004 /// Call all registered callbacks to notify that the payload is ready to serve.
1005 pub fn notify_payload_ready(&self, cid: Cid) {
1006 let callbacks = &*self.0.lock().unwrap();
1007 for callback in callbacks {
1008 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001009 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001010 }
1011 }
1012 }
1013
Inseob Kim2444af92021-08-31 01:22:50 +09001014 /// Call all registered callbacks to notify that the payload has finished.
1015 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1016 let callbacks = &*self.0.lock().unwrap();
1017 for callback in callbacks {
1018 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001019 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001020 }
1021 }
1022 }
1023
Jooyung Handd0a1732021-11-23 15:26:20 +09001024 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001025 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001026 let callbacks = &*self.0.lock().unwrap();
1027 for callback in callbacks {
1028 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001029 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001030 }
1031 }
1032 }
1033
Andrew Walbrandae07162021-03-12 17:05:20 +00001034 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001035 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001036 let callbacks = &*self.0.lock().unwrap();
1037 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001038 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001039 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001040 }
1041 }
1042 }
1043
Jiyong Parke558ab12022-07-07 20:18:55 +09001044 /// Call all registered callbacks to say that there was a ramdump to download.
1045 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
1046 let callbacks = &*self.0.lock().unwrap();
1047 let pfd = ParcelFileDescriptor::new(ramdump);
1048 for callback in callbacks {
1049 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001050 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +09001051 }
1052 }
1053 }
1054
Andrew Walbrandae07162021-03-12 17:05:20 +00001055 /// Add a new callback to the set.
1056 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1057 self.0.lock().unwrap().push(callback);
1058 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001059}
1060
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001061/// The mutable state of the VirtualizationService. There should only be one instance of this
1062/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001063#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001064struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001065 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1066 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1067 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1068 /// from the list opportunistically the next time `add_vm` is called.
1069 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001070
1071 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1072 /// This is only used for debugging purposes.
1073 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001074}
1075
1076impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001077 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001078 fn vms(&self) -> Vec<Arc<VmInstance>> {
1079 // Attempt to upgrade the weak pointers to strong pointers.
1080 self.vms.iter().filter_map(Weak::upgrade).collect()
1081 }
1082
1083 /// Add a new VM to the list.
1084 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1085 // Garbage collect any entries from the stored list which no longer exist.
1086 self.vms.retain(|vm| vm.strong_count() > 0);
1087
1088 // Actually add the new VM.
1089 self.vms.push(vm);
1090 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001091
Jiyong Park8611a6c2021-07-09 18:17:44 +09001092 /// Get a VM that corresponds to the given cid
1093 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1094 self.vms().into_iter().find(|vm| vm.cid == cid)
1095 }
1096
David Brazdil3c2ddef2021-03-18 13:09:57 +00001097 /// Store a strong VM reference.
1098 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1099 self.debug_held_vms.push(vm);
1100 }
1101
1102 /// Retrieve and remove a strong VM reference.
1103 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1104 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001105 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001106 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001107 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001108}
1109
Andrew Walbran6b650662021-09-07 13:13:23 +00001110/// Gets the `VirtualMachineState` of the given `VmInstance`.
1111fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001112 match &*instance.vm_state.lock().unwrap() {
1113 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1114 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001115 PayloadState::Starting => VirtualMachineState::STARTING,
1116 PayloadState::Started => VirtualMachineState::STARTED,
1117 PayloadState::Ready => VirtualMachineState::READY,
1118 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001119 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001120 },
1121 VmState::Dead => VirtualMachineState::DEAD,
1122 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001123 }
1124}
1125
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001126/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001127pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001128 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001129 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001130 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001131 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001132 )
1133 })
1134}
1135
Andrew Walbrand3a84182021-09-07 14:48:52 +00001136/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1137fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1138 file.as_ref().map(clone_file).transpose()
1139}
1140
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001141/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1142fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1143 // SAFETY: ownership is transferred from stream to f
1144 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1145 ParcelFileDescriptor::new(f)
1146}
1147
Jiyong Parkdcf17412022-02-08 15:07:23 +09001148/// Parses the platform version requirement string.
1149fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1150 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001151 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001152 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001153 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001154 )
1155 })
1156}
1157
Jooyung Han35edb8f2021-07-01 16:17:16 +09001158/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1159/// it doesn't require that T implements Clone.
1160enum BorrowedOrOwned<'a, T> {
1161 Borrowed(&'a T),
1162 Owned(T),
1163}
1164
1165impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1166 fn as_ref(&self) -> &T {
1167 match self {
1168 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001169 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001170 }
1171 }
1172}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001173
1174/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1175#[derive(Debug, Default)]
1176struct VirtualMachineService {
1177 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001178 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001179}
1180
1181impl Interface for VirtualMachineService {}
1182
1183impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001184 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1185 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001186 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001187 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001188 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1189 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1190 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001191 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001192
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001193 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1194 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001195 Ok(())
1196 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001197 error!("notifyPayloadStarted 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 Kim7f61fe72021-08-20 20:50:47 +09001201 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001202 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001203 }
Inseob Kim2444af92021-08-31 01:22:50 +09001204
Inseob Kimc7d28c72021-10-25 14:28:10 +00001205 fn notifyPayloadReady(&self) -> binder::Result<()> {
1206 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001207 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001208 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001209 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1210 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1211 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001212 vm.callbacks.notify_payload_ready(cid);
1213 Ok(())
1214 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001215 error!("notifyPayloadReady 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)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001219 ))
1220 }
1221 }
1222
Inseob Kimc7d28c72021-10-25 14:28:10 +00001223 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1224 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001225 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001226 info!("VM with CID {} finished payload", 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 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001230 vm.callbacks.notify_payload_finished(cid, exit_code);
1231 Ok(())
1232 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001233 error!("notifyPayloadFinished 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)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001237 ))
1238 }
1239 }
1240
Alan Stokes2bead0d2022-09-05 16:58:34 +01001241 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001242 let cid = self.cid;
1243 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001244 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001245 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1246 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1247 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001248 vm.callbacks.notify_error(cid, error_code, message);
1249 Ok(())
1250 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001251 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001252 Err(Status::new_service_specific_error_str(
1253 -1,
1254 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001255 ))
1256 }
1257 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001258}
1259
1260impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001261 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001262 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001263 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001264 BinderFeatures::default(),
1265 )
1266 }
1267}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001268
1269#[cfg(test)]
1270mod tests {
1271 use super::*;
1272
1273 #[test]
1274 fn test_is_allowed_label_for_partition() -> Result<()> {
1275 let expected_results = vec![
1276 ("u:object_r:system_file:s0", true),
1277 ("u:object_r:apk_data_file:s0", true),
1278 ("u:object_r:app_data_file:s0", false),
1279 ("u:object_r:app_data_file:s0:c512,c768", false),
1280 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1281 ("invalid", false),
1282 ("user:role:apk_data_file:severity:categories", true),
1283 ("user:role:apk_data_file:severity:categories:extraneous", false),
1284 ];
1285
1286 for (label, expected_valid) in expected_results {
1287 let context = SeContext::new(label)?;
1288 let result = check_label_is_allowed(&context);
1289 if expected_valid {
1290 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1291 } else if result.is_ok() {
1292 bail!("Expected label {} to be disallowed", label);
1293 }
1294 }
1295 Ok(())
1296 }
1297}