blob: 7d24a32fb4f8aa33847c51cb59ff2fe3fb03d7ca [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,
Keir Frasercdd4b112022-11-24 14:02:25 +000030 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090031 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000032 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090033 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090034 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010036 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090037 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000038 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090039};
David Brazdil528e0472022-10-10 15:06:02 +010040use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
41 IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
42 IVirtualizationServiceInternal::{BnVirtualizationServiceInternal, IVirtualizationServiceInternal},
43};
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090044use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdil73988ea2022-11-11 15:10:32 +000045 BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090046};
47use anyhow::{anyhow, bail, Context, Result};
48use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010049use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000050 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
David Brazdil73988ea2022-11-11 15:10:32 +000051 Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000052};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000053use disk::QcowFile;
David Brazdila07a1792022-10-25 13:37:57 +010054use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000055use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090056use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
David Brazdil73988ea2022-11-11 15:10:32 +000057use rpcbinder::RpcServer;
Jiyong Parkd50a0242021-09-16 21:00:14 +090058use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090059use semver::VersionReq;
David Brazdil73988ea2022-11-11 15:10:32 +000060use std::collections::HashMap;
Andrew Walbrandff3b942021-06-09 15:20:36 +000061use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000062use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010063use std::fs::{create_dir, File, OpenOptions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000065use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000066use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000067use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000068use std::sync::{Arc, Mutex, Weak};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090069use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000070use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000071use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090072use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073
David Brazdil41d1a872022-10-05 14:44:19 +010074/// The unique ID of a VM used (together with a port number) for vsock communication.
75pub type Cid = u32;
76
Andrew Walbranf6bf6862021-05-21 12:41:13 +000077pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000078
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000079/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000080pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081
David Brazdil41d1a872022-10-05 14:44:19 +010082/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
83/// are reserved for the host or other usage.
David Brazdil73988ea2022-11-11 15:10:32 +000084const GUEST_CID_MIN: Cid = 2048;
85const GUEST_CID_MAX: Cid = 65535;
David Brazdil41d1a872022-10-05 14:44:19 +010086
87const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
Jiyong Park8611a6c2021-07-09 18:17:44 +090088
Jooyung Han95884632021-07-06 22:27:54 +090089/// The size of zero.img.
90/// Gaps in composite disk images are filled with a shared zero.img.
91const ZERO_FILLER_SIZE: u64 = 4096;
92
Jiyong Park9dd389e2021-08-23 20:42:59 +090093/// Magic string for the instance image
94const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
95
96/// Version of the instance image format
97const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
98
Shikha Panwar7afc1392022-03-24 08:54:43 +000099const CHUNK_RECV_MAX_LEN: usize = 1024;
100
Alan Stokes0d1ef782022-09-27 13:46:35 +0100101const MICRODROID_OS_NAME: &str = "microdroid";
102
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000103const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
104
David Brazdil73988ea2022-11-11 15:10:32 +0000105fn is_valid_guest_cid(cid: Cid) -> bool {
106 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
107}
108
109fn next_guest_cid(cid: Cid) -> Cid {
110 assert!(is_valid_guest_cid(cid));
111 if cid == GUEST_CID_MAX {
112 GUEST_CID_MIN
113 } else {
114 cid + 1
115 }
116}
117
David Brazdil528e0472022-10-10 15:06:02 +0100118/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
119/// singleton servers, like tombstone receiver.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900120#[derive(Debug, Default)]
David Brazdil528e0472022-10-10 15:06:02 +0100121pub struct VirtualizationServiceInternal {
122 state: Arc<Mutex<GlobalState>>,
123}
124
125impl VirtualizationServiceInternal {
126 pub fn init() -> VirtualizationServiceInternal {
127 let service = VirtualizationServiceInternal::default();
128
129 std::thread::spawn(|| {
130 if let Err(e) = handle_stream_connection_tombstoned() {
131 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
132 }
133 });
134
135 service
136 }
137}
138
139impl Interface for VirtualizationServiceInternal {}
140
141impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
142 fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
143 let state = &mut *self.state.lock().unwrap();
144 let cid = state.allocate_cid().map_err(|e| {
145 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
146 })?;
147 Ok(GlobalVmContext::create(cid))
148 }
149}
150
151/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
152/// of this struct.
153#[derive(Debug, Default)]
David Brazdil73988ea2022-11-11 15:10:32 +0000154struct GlobalState {
155 /// CIDs currently allocated to running VMs. A CID is never recycled as long
156 /// as there is a strong reference held by a GlobalVmContext.
157 held_cids: HashMap<Cid, Weak<Cid>>,
158}
David Brazdil528e0472022-10-10 15:06:02 +0100159
160impl GlobalState {
161 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
162 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
163 /// Android is up.
David Brazdil73988ea2022-11-11 15:10:32 +0000164 fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
165 // Garbage collect unused CIDs.
166 self.held_cids.retain(|_, cid| cid.strong_count() > 0);
167
168 // Start trying to find a CID from the last used CID + 1. This ensures
David Brazdil8cf8f482022-11-23 14:21:26 +0000169 // that we do not eagerly recycle CIDs. It makes debugging easier but
170 // also means that retrying to allocate a CID, eg. because it is
171 // erroneously occupied by a process, will not recycle the same CID.
David Brazdil73988ea2022-11-11 15:10:32 +0000172 let last_cid_prop =
173 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
174 Ok(num) => {
175 if is_valid_guest_cid(num) {
176 Some(num)
177 } else {
178 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
179 None
180 }
181 }
David Brazdil528e0472022-10-10 15:06:02 +0100182 Err(_) => {
183 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000184 None
David Brazdil528e0472022-10-10 15:06:02 +0100185 }
David Brazdil73988ea2022-11-11 15:10:32 +0000186 });
187
188 let first_cid = if let Some(last_cid) = last_cid_prop {
189 next_guest_cid(last_cid)
190 } else {
191 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100192 };
David Brazdil73988ea2022-11-11 15:10:32 +0000193
194 let cid = self
195 .find_available_cid(first_cid..=GUEST_CID_MAX)
196 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
197
198 if let Some(cid) = cid {
199 let cid_arc = Arc::new(cid);
200 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
201 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
202 Ok(cid_arc)
203 } else {
204 Err(anyhow!("Could not find an available CID."))
205 }
206 }
207
208 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
209 where
210 I: Iterator<Item = Cid>,
211 {
212 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100213 }
214}
215
216/// Implementation of the AIDL `IGlobalVmContext` interface.
217#[derive(Debug, Default)]
218struct GlobalVmContext {
219 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000220 cid: Arc<Cid>,
221 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100222 #[allow(dead_code)]
223 lazy_service_guard: LazyServiceGuard,
224}
225
226impl GlobalVmContext {
David Brazdil73988ea2022-11-11 15:10:32 +0000227 fn create(cid: Arc<Cid>) -> Strong<dyn IGlobalVmContext> {
David Brazdil528e0472022-10-10 15:06:02 +0100228 let binder = GlobalVmContext { cid, ..Default::default() };
229 BnGlobalVmContext::new_binder(binder, BinderFeatures::default())
230 }
231}
232
233impl Interface for GlobalVmContext {}
234
235impl IGlobalVmContext for GlobalVmContext {
236 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000237 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100238 }
239}
240
241/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
242#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000243pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900244 state: Arc<Mutex<State>>,
David Brazdil528e0472022-10-10 15:06:02 +0100245 global_service: Strong<dyn IVirtualizationServiceInternal>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000246}
247
Shikha Panward8e35422021-10-11 13:51:27 +0000248impl Interface for VirtualizationService {
249 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
250 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
251 let state = &mut *self.state.lock().unwrap();
252 let vms = state.vms();
253 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
254 for vm in vms {
255 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
256 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
257 .or(Err(StatusCode::UNKNOWN_ERROR))?;
258 writeln!(file, "\tPayload state {:?}", vm.payload_state())
259 .or(Err(StatusCode::UNKNOWN_ERROR))?;
260 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
261 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
262 .or(Err(StatusCode::UNKNOWN_ERROR))?;
263 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
264 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000265 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
266 .or(Err(StatusCode::UNKNOWN_ERROR))?;
267 }
268 Ok(())
269 }
270}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000271
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000272impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000273 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
274 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000275 ///
276 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000277 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000278 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000279 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900280 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000281 log_fd: Option<&ParcelFileDescriptor>,
282 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000283 let mut is_protected = false;
284 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000285 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000286 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000287 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000288
Andrew Walbrandff3b942021-06-09 15:20:36 +0000289 /// Initialise an empty partition image of the given size to be used as a writable partition.
290 fn initializeWritablePartition(
291 &self,
292 image_fd: &ParcelFileDescriptor,
293 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900294 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000295 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900296 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000297 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000298 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000299 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100300 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000301 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000302 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000303 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900304 // initialize the file. Any data in the file will be erased.
305 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000306 Status::new_service_specific_error_str(
307 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100308 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900309 )
310 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900311 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000312 Status::new_service_specific_error_str(
313 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100314 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000315 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000316 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000317
Jiyong Park9dd389e2021-08-23 20:42:59 +0900318 match partition_type {
319 PartitionType::RAW => Ok(()),
320 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000321 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900322 _ => Err(Error::new(
323 ErrorKind::Unsupported,
324 format!("Unsupported partition type {:?}", partition_type),
325 )),
326 }
327 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000328 Status::new_service_specific_error_str(
329 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100330 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900331 )
332 })?;
333
Andrew Walbrandff3b942021-06-09 15:20:36 +0000334 Ok(())
335 }
336
Jiyong Park0a248432021-08-20 23:32:39 +0900337 /// Creates or update the idsig file by digesting the input APK file.
338 fn createOrUpdateIdsigFile(
339 &self,
340 input_fd: &ParcelFileDescriptor,
341 idsig_fd: &ParcelFileDescriptor,
342 ) -> binder::Result<()> {
343 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
344 // idsig_fd is different from APK digest in input_fd
345
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900346 check_manage_access()?;
347
Jiyong Park0a248432021-08-20 23:32:39 +0900348 let mut input = clone_file(input_fd)?;
349 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
350
351 let mut output = clone_file(idsig_fd)?;
352 output.set_len(0).unwrap();
353 sig.write_into(&mut output).unwrap();
354 Ok(())
355 }
356
Andrew Walbran320b5602021-03-04 16:11:12 +0000357 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
358 /// and as such is only permitted from the shell user.
359 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000360 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000361
362 let state = &mut *self.state.lock().unwrap();
363 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000364 let cids = vms
365 .into_iter()
366 .map(|vm| VirtualMachineDebugInfo {
367 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000368 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000369 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000370 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000371 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000372 })
373 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000374 Ok(cids)
375 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000376
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000377 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
378 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000379 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000380 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000381
David Brazdil3c2ddef2021-03-18 13:09:57 +0000382 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000383 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000384 Ok(())
385 }
386
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000387 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
388 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
389 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000390 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000391 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000392
393 let state = &mut *self.state.lock().unwrap();
394 Ok(state.debug_drop_vm(cid))
395 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000396}
397
Shikha Panwar7afc1392022-03-24 08:54:43 +0000398fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000399 // Should not listen for tombstones on a guest VM's port.
400 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000401 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000402 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000403 for incoming_stream in listener.incoming() {
404 let mut incoming_stream = match incoming_stream {
405 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100406 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000407 continue;
408 }
409 Ok(s) => s,
410 };
411 std::thread::spawn(move || {
412 if let Err(e) = handle_tombstone(&mut incoming_stream) {
413 error!("Failed to write tombstone- {:?}", e);
414 }
415 });
416 }
417 Ok(())
418}
419
420fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000421 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000422 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
423 }
424 let tb_connection =
425 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
426 .context("Failed to connect to tombstoned")?;
427 let mut text_output = tb_connection
428 .text_output
429 .as_ref()
430 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
431 let mut num_bytes_read = 0;
432 loop {
433 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
434 let n = stream
435 .read(&mut chunk_recv)
436 .context("Failed to read tombstone data from Vsock stream")?;
437 if n == 0 {
438 break;
439 }
440 num_bytes_read += n;
441 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
442 }
443 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
444 tb_connection.notify_completion()?;
445 Ok(())
446}
447
Jiyong Park8611a6c2021-07-09 18:17:44 +0900448impl VirtualizationService {
449 pub fn init() -> VirtualizationService {
David Brazdil528e0472022-10-10 15:06:02 +0100450 let global_service = VirtualizationServiceInternal::init();
451 let global_service =
452 BnVirtualizationServiceInternal::new_binder(global_service, BinderFeatures::default());
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900453
David Brazdil73988ea2022-11-11 15:10:32 +0000454 VirtualizationService { global_service, state: Default::default() }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900455 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000456
David Brazdil8cf8f482022-11-23 14:21:26 +0000457 fn create_vm_context(&self) -> Result<(VmContext, Cid)> {
458 const NUM_ATTEMPTS: usize = 5;
459
460 for _ in 0..NUM_ATTEMPTS {
461 let global_context = self.global_service.allocateGlobalVmContext()?;
462 let cid = global_context.getCid()? as Cid;
463 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
464
465 // Start VM service listening for connections from the new CID on port=CID.
466 // TODO(b/245727626): Only accept connections from the new VM.
467 let port = cid;
468 match RpcServer::new_vsock(service, port) {
469 Ok(vm_server) => {
470 vm_server.start();
471 return Ok((VmContext::new(global_context, vm_server), cid));
472 }
473 Err(err) => {
474 warn!("Could not start RpcServer on port {}: {}", port, err);
475 }
476 }
477 }
478 bail!("Too many attempts to create VM context failed.");
479 }
480
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000481 fn create_vm_internal(
482 &self,
483 config: &VirtualMachineConfig,
484 console_fd: Option<&ParcelFileDescriptor>,
485 log_fd: Option<&ParcelFileDescriptor>,
486 is_protected: &mut bool,
487 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
488 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900489
Alan Stokes7bc146c2022-10-20 17:10:32 +0100490 let is_custom = match config {
491 VirtualMachineConfig::RawConfig(_) => true,
492 VirtualMachineConfig::AppConfig(config) => {
493 // Some features are reserved for platform apps only, even when using
494 // VirtualMachineAppConfig:
495 // - controlling CPUs;
496 // - specifying a config file in the APK.
497 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900498 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100499 };
500 if is_custom {
501 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900502 }
503
David Brazdil8cf8f482022-11-23 14:21:26 +0000504 let (vm_context, cid) = self.create_vm_context().map_err(|e| {
505 error!("Failed to create VmContext: {:?}", e);
506 Status::new_service_specific_error_str(
507 -1,
508 Some(format!("Failed to create VmContext: {:?}", e)),
509 )
510 })?;
David Brazdil528e0472022-10-10 15:06:02 +0100511
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000512 let state = &mut *self.state.lock().unwrap();
513 let console_fd = console_fd.map(clone_file).transpose()?;
514 let log_fd = log_fd.map(clone_file).transpose()?;
515 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000516 let requester_debug_pid = ThreadState::get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000517
518 // Counter to generate unique IDs for temporary image files.
519 let mut next_temporary_image_id = 0;
520 // Files which are referred to from composite images. These must be mapped to the crosvm
521 // child process, and not closed before it is started.
522 let mut indirect_files = vec![];
523
524 // Make directory for temporary files.
525 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
526 create_dir(&temporary_directory).map_err(|e| {
527 // At this point, we do not know the protected status of Vm
528 // setting it to false, though this may not be correct.
529 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100530 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000531 temporary_directory, e
532 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000533 Status::new_service_specific_error_str(
534 -1,
535 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100536 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000537 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000538 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000539 )
540 })?;
541
Alan Stokes7bc146c2022-10-20 17:10:32 +0100542 let (is_app_config, config) = match config {
543 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
544 VirtualMachineConfig::AppConfig(config) => {
545 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000546 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100547 let message = format!("Failed to load app config: {:?}", e);
548 error!("{}", message);
549 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100550 })?;
551 (true, BorrowedOrOwned::Owned(config))
552 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000553 };
554 let config = config.as_ref();
555 *is_protected = config.protectedVm;
556
557 // Check if partition images are labeled incorrectly. This is to prevent random images
558 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100559 // being loaded in a pVM. This applies to everything in the raw config, and everything but
560 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000561 config
562 .disks
563 .iter()
564 .flat_map(|disk| disk.partitions.iter())
565 .filter(|partition| {
566 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100567 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000568 } else {
569 true // all partitions are checked
570 }
571 })
572 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100573 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000574
575 let zero_filler_path = temporary_directory.join("zero.img");
576 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100577 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000578 Status::new_service_specific_error_str(
579 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100580 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000581 )
582 })?;
583
584 // Assemble disk images if needed.
585 let disks = config
586 .disks
587 .iter()
588 .map(|disk| {
589 assemble_disk_image(
590 disk,
591 &zero_filler_path,
592 &temporary_directory,
593 &mut next_temporary_image_id,
594 &mut indirect_files,
595 )
596 })
597 .collect::<Result<Vec<DiskFile>, _>>()?;
598
Jiyong Parke558ab12022-07-07 20:18:55 +0900599 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
600 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900601 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900602 // will be sent back to the client (i.e. the VM owner) for readout.
603 let ramdump_path = temporary_directory.join("ramdump");
604 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100605 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000606 Status::new_service_specific_error_str(
607 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100608 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900609 )
610 })?;
611
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000612 // Actually start the VM.
613 let crosvm_config = CrosvmConfig {
614 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000615 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000616 bootloader: maybe_clone_file(&config.bootloader)?,
617 kernel: maybe_clone_file(&config.kernel)?,
618 initrd: maybe_clone_file(&config.initrd)?,
619 disks,
620 params: config.params.to_owned(),
621 protected: *is_protected,
622 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
623 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900624 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000625 console_fd,
626 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900627 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000628 indirect_files,
629 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900630 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000631 };
632 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100633 VmInstance::new(
634 crosvm_config,
635 temporary_directory,
636 requester_uid,
637 requester_debug_pid,
638 vm_context,
639 )
640 .map_err(|e| {
641 error!("Failed to create VM with config {:?}: {:?}", config, e);
642 Status::new_service_specific_error_str(
643 -1,
644 Some(format!("Failed to create VM: {:?}", e)),
645 )
646 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000647 );
648 state.add_vm(Arc::downgrade(&instance));
649 Ok(VirtualMachine::create(instance))
650 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900651}
652
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000653fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900654 let file = OpenOptions::new()
655 .create_new(true)
656 .read(true)
657 .write(true)
658 .open(zero_filler_path)
659 .with_context(|| "Failed to create zero.img")?;
660 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000661 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900662}
663
Jiyong Park9dd389e2021-08-23 20:42:59 +0900664fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
665 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
666 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
667 part.flush()
668}
669
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000670fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
671 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
672 part.flush()
673}
674
Jiyong Parke558ab12022-07-07 20:18:55 +0900675fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800676 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900677}
678
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000679/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
680///
681/// This may involve assembling a composite disk from a set of partition images.
682fn assemble_disk_image(
683 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900684 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000685 temporary_directory: &Path,
686 next_temporary_image_id: &mut u64,
687 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000688) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000689 let image = if !disk.partitions.is_empty() {
690 if disk.image.is_some() {
691 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000692 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000693 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000694 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000695 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696 }
697
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000698 let composite_image_filenames =
699 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
700 let (image, partition_files) = make_composite_image(
701 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900702 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000703 &composite_image_filenames.composite,
704 &composite_image_filenames.header,
705 &composite_image_filenames.footer,
706 )
707 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100708 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000709 Status::new_service_specific_error_str(
710 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100711 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000712 )
713 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000714
715 // Pass the file descriptors for the various partition files to crosvm when it
716 // is run.
717 indirect_files.extend(partition_files);
718
719 image
720 } else if let Some(image) = &disk.image {
721 clone_file(image)?
722 } else {
723 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000724 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000725 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000726 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000727 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000728 };
729
730 Ok(DiskFile { image, writable: disk.writable })
731}
732
Jooyung Han21e9b922021-06-26 04:14:16 +0900733fn load_app_config(
734 config: &VirtualMachineAppConfig,
735 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900736) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000737 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
738 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900739 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900740
Shikha Panwar22e70452022-10-10 18:32:55 +0000741 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
742 Some(clone_file(file)?)
743 } else {
744 None
745 };
746
Alan Stokes0d1ef782022-09-27 13:46:35 +0100747 let vm_payload_config = match &config.payload {
748 Payload::ConfigPath(config_path) => {
749 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
750 .with_context(|| format!("Couldn't read config from {}", config_path))?
751 }
752 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
753 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900754
Alan Stokes0d1ef782022-09-27 13:46:35 +0100755 // For now, the only supported OS is Microdroid
756 let os_name = vm_payload_config.os.name.as_str();
757 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000758 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900759 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000760
761 // It is safe to construct a filename based on the os_name because we've already checked that it
762 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900763 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
764 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000765 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900766
Andrew Walbrancc045902021-07-27 16:06:17 +0000767 if config.memoryMib > 0 {
768 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000769 }
770
Seungjae Yoo62085c02022-08-12 04:44:52 +0000771 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000772 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900773 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900774 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900775
Shikha Panwar22e70452022-10-10 18:32:55 +0000776 // Microdroid takes additional init ramdisk & (optionally) storage image
777 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
778
779 // Include Microdroid payload disk (contains apks, idsigs) in vm config
780 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100781 config,
782 temporary_directory,
783 apk_file,
784 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100785 &vm_payload_config,
786 &mut vm_config,
787 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900788
Andrew Walbrancc0db522021-07-12 17:03:42 +0000789 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900790}
791
Alan Stokes0d1ef782022-09-27 13:46:35 +0100792fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
793 let mut apk_zip = ZipArchive::new(apk_file)?;
794 let config_file = apk_zip.by_name(config_path)?;
795 Ok(serde_json::from_reader(config_file)?)
796}
797
798fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
799 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
800 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
801 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100802 let task =
803 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100804 VmPayloadConfig {
805 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
806 task: Some(task),
807 apexes: vec![],
808 extra_apks: vec![],
809 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100810 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100811 enable_authfs: false,
812 }
813}
814
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000815/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000816fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000817 temporary_directory: &Path,
818 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000819) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000820 let id = *next_temporary_image_id;
821 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000822 CompositeImageFilenames {
823 composite: temporary_directory.join(format!("composite-{}.img", id)),
824 header: temporary_directory.join(format!("composite-{}-header.img", id)),
825 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
826 }
827}
828
829/// Filenames for a composite disk image, including header and footer partitions.
830#[derive(Clone, Debug, Eq, PartialEq)]
831struct CompositeImageFilenames {
832 /// The composite disk image itself.
833 composite: PathBuf,
834 /// The header partition image.
835 header: PathBuf,
836 /// The footer partition image.
837 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000838}
839
Jiyong Park753553b2021-07-12 21:21:09 +0900840/// Checks whether the caller has a specific permission
841fn check_permission(perm: &str) -> binder::Result<()> {
842 let calling_pid = ThreadState::get_calling_pid();
843 let calling_uid = ThreadState::get_calling_uid();
844 // Root can do anything
845 if calling_uid == 0 {
846 return Ok(());
847 }
848 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
849 binder::get_interface("permission")?;
850 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000851 Ok(())
852 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000853 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900854 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000855 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900856 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000857 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000858}
859
Jiyong Park753553b2021-07-12 21:21:09 +0900860/// Check whether the caller of the current Binder method is allowed to call debug methods.
861fn check_debug_access() -> binder::Result<()> {
862 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
863}
864
865/// Check whether the caller of the current Binder method is allowed to manage VMs
866fn check_manage_access() -> binder::Result<()> {
867 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
868}
869
Inseob Kim1119d702022-05-02 18:01:58 +0900870/// Check whether the caller of the current Binder method is allowed to create custom VMs
871fn check_use_custom_virtual_machine() -> binder::Result<()> {
872 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
873}
874
Jiyong Park029977d2021-11-24 21:56:49 +0900875/// Check if a partition has selinux labels that are not allowed
876fn check_label_for_partition(partition: &Partition) -> Result<()> {
877 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100878 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
879}
880
881// Return whether a partition is exempt from selinux label checks, because we know that it does
882// not contain code and is likely to be generated in an app-writable directory.
883fn is_safe_app_partition(label: &str) -> bool {
884 // See make_payload_disk in payload.rs.
885 label == "vm-instance"
886 || label == "microdroid-apk-idsig"
887 || label == "payload-metadata"
888 || label.starts_with("extra-idsig-")
889}
890
891fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
892 // We only want to allow code in a VM payload to be sourced from places that apps, and the
893 // system, do not have write access to.
894 // (Note that sepolicy must also grant read access for these types to both virtualization
895 // service and crosvm.)
896 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
897 // user devices (W^X).
898 match ctx.selinux_type()? {
899 | "system_file" // immutable dm-verity protected partition
900 | "apk_data_file" // APKs of an installed app
901 | "staging_data_file" // updated/staged APEX imagess
902 | "shell_data_file" // test files created via adb shell
903 => Ok(()),
904 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900905 }
906}
907
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000908/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
909#[derive(Debug)]
910struct VirtualMachine {
911 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100912 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800913 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100914 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000915}
916
917impl VirtualMachine {
918 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100919 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000920 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000921 }
922}
923
924impl Interface for VirtualMachine {}
925
926impl IVirtualMachine for VirtualMachine {
927 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900928 // Don't check permission. The owner of the VM might have passed this binder object to
929 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000930 Ok(self.instance.cid as i32)
931 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000932
Andrew Walbran6b650662021-09-07 13:13:23 +0000933 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900934 // Don't check permission. The owner of the VM might have passed this binder object to
935 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000936 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000937 }
938
939 fn registerCallback(
940 &self,
941 callback: &Strong<dyn IVirtualMachineCallback>,
942 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900943 // Don't check permission. The owner of the VM might have passed this binder object to
944 // others.
945 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000946 // TODO: Should this give an error if the VM is already dead?
947 self.instance.callbacks.add(callback.clone());
948 Ok(())
949 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000950
Andrew Walbranf8d94112021-09-07 11:45:36 +0000951 fn start(&self) -> binder::Result<()> {
952 self.instance.start().map_err(|e| {
953 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000954 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000955 })
956 }
957
Inseob Kima446f802022-07-11 19:46:37 +0900958 fn stop(&self) -> binder::Result<()> {
959 self.instance.kill().map_err(|e| {
960 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000961 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900962 })
963 }
964
Keir Frasercdd4b112022-11-24 14:02:25 +0000965 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
966 self.instance.trim_memory(level).map_err(|e| {
967 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
968 Status::new_service_specific_error_str(-1, Some(e.to_string()))
969 })
970 }
971
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000972 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000973 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000974 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000975 }
976 let stream =
977 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000978 Status::new_service_specific_error_str(
979 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100980 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000981 )
982 })?;
983 Ok(vsock_stream_to_pfd(stream))
984 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000985}
986
987impl Drop for VirtualMachine {
988 fn drop(&mut self) {
989 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900990 if let Err(e) = self.instance.kill() {
991 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
992 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000993 }
994}
995
996/// A set of Binders to be called back in response to various events on the VM, such as when it
997/// dies.
998#[derive(Debug, Default)]
999pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1000
1001impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001002 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001003 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001004 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001005 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001006 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001007 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001008 }
1009 }
1010 }
1011
Inseob Kim14cb8692021-08-31 21:50:39 +09001012 /// Call all registered callbacks to notify that the payload is ready to serve.
1013 pub fn notify_payload_ready(&self, cid: Cid) {
1014 let callbacks = &*self.0.lock().unwrap();
1015 for callback in callbacks {
1016 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001017 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001018 }
1019 }
1020 }
1021
Inseob Kim2444af92021-08-31 01:22:50 +09001022 /// Call all registered callbacks to notify that the payload has finished.
1023 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1024 let callbacks = &*self.0.lock().unwrap();
1025 for callback in callbacks {
1026 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001027 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001028 }
1029 }
1030 }
1031
Jooyung Handd0a1732021-11-23 15:26:20 +09001032 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001033 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001034 let callbacks = &*self.0.lock().unwrap();
1035 for callback in callbacks {
1036 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001037 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001038 }
1039 }
1040 }
1041
Andrew Walbrandae07162021-03-12 17:05:20 +00001042 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001043 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001044 let callbacks = &*self.0.lock().unwrap();
1045 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001046 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001047 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001048 }
1049 }
1050 }
1051
Jiyong Parke558ab12022-07-07 20:18:55 +09001052 /// Call all registered callbacks to say that there was a ramdump to download.
1053 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
1054 let callbacks = &*self.0.lock().unwrap();
1055 let pfd = ParcelFileDescriptor::new(ramdump);
1056 for callback in callbacks {
1057 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001058 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +09001059 }
1060 }
1061 }
1062
Andrew Walbrandae07162021-03-12 17:05:20 +00001063 /// Add a new callback to the set.
1064 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1065 self.0.lock().unwrap().push(callback);
1066 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001067}
1068
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001069/// The mutable state of the VirtualizationService. There should only be one instance of this
1070/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001071#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001072struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001073 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1074 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1075 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1076 /// from the list opportunistically the next time `add_vm` is called.
1077 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001078
1079 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1080 /// This is only used for debugging purposes.
1081 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001082}
1083
1084impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001085 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001086 fn vms(&self) -> Vec<Arc<VmInstance>> {
1087 // Attempt to upgrade the weak pointers to strong pointers.
1088 self.vms.iter().filter_map(Weak::upgrade).collect()
1089 }
1090
1091 /// Add a new VM to the list.
1092 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1093 // Garbage collect any entries from the stored list which no longer exist.
1094 self.vms.retain(|vm| vm.strong_count() > 0);
1095
1096 // Actually add the new VM.
1097 self.vms.push(vm);
1098 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001099
Jiyong Park8611a6c2021-07-09 18:17:44 +09001100 /// Get a VM that corresponds to the given cid
1101 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1102 self.vms().into_iter().find(|vm| vm.cid == cid)
1103 }
1104
David Brazdil3c2ddef2021-03-18 13:09:57 +00001105 /// Store a strong VM reference.
1106 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1107 self.debug_held_vms.push(vm);
1108 }
1109
1110 /// Retrieve and remove a strong VM reference.
1111 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1112 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001113 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001114 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001115 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001116}
1117
Andrew Walbran6b650662021-09-07 13:13:23 +00001118/// Gets the `VirtualMachineState` of the given `VmInstance`.
1119fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001120 match &*instance.vm_state.lock().unwrap() {
1121 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1122 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001123 PayloadState::Starting => VirtualMachineState::STARTING,
1124 PayloadState::Started => VirtualMachineState::STARTED,
1125 PayloadState::Ready => VirtualMachineState::READY,
1126 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001127 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001128 },
1129 VmState::Dead => VirtualMachineState::DEAD,
1130 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001131 }
1132}
1133
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001134/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001135pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001136 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001137 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001138 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001139 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001140 )
1141 })
1142}
1143
Andrew Walbrand3a84182021-09-07 14:48:52 +00001144/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1145fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1146 file.as_ref().map(clone_file).transpose()
1147}
1148
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001149/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1150fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1151 // SAFETY: ownership is transferred from stream to f
1152 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1153 ParcelFileDescriptor::new(f)
1154}
1155
Jiyong Parkdcf17412022-02-08 15:07:23 +09001156/// Parses the platform version requirement string.
1157fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1158 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001159 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001160 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001161 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001162 )
1163 })
1164}
1165
Jooyung Han35edb8f2021-07-01 16:17:16 +09001166/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1167/// it doesn't require that T implements Clone.
1168enum BorrowedOrOwned<'a, T> {
1169 Borrowed(&'a T),
1170 Owned(T),
1171}
1172
1173impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1174 fn as_ref(&self) -> &T {
1175 match self {
1176 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001177 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001178 }
1179 }
1180}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001181
1182/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1183#[derive(Debug, Default)]
1184struct VirtualMachineService {
1185 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001186 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001187}
1188
1189impl Interface for VirtualMachineService {}
1190
1191impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001192 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1193 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001194 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001195 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001196 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1197 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1198 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001199 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001200
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001201 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1202 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001203 Ok(())
1204 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001205 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001206 Err(Status::new_service_specific_error_str(
1207 -1,
1208 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001209 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001210 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001211 }
Inseob Kim2444af92021-08-31 01:22:50 +09001212
Inseob Kimc7d28c72021-10-25 14:28:10 +00001213 fn notifyPayloadReady(&self) -> binder::Result<()> {
1214 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001215 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001216 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001217 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1218 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1219 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001220 vm.callbacks.notify_payload_ready(cid);
1221 Ok(())
1222 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001223 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001224 Err(Status::new_service_specific_error_str(
1225 -1,
1226 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001227 ))
1228 }
1229 }
1230
Inseob Kimc7d28c72021-10-25 14:28:10 +00001231 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1232 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001233 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001234 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001235 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1236 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1237 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001238 vm.callbacks.notify_payload_finished(cid, exit_code);
1239 Ok(())
1240 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001241 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001242 Err(Status::new_service_specific_error_str(
1243 -1,
1244 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001245 ))
1246 }
1247 }
1248
Alan Stokes2bead0d2022-09-05 16:58:34 +01001249 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001250 let cid = self.cid;
1251 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001252 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001253 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1254 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1255 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001256 vm.callbacks.notify_error(cid, error_code, message);
1257 Ok(())
1258 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001259 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001260 Err(Status::new_service_specific_error_str(
1261 -1,
1262 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001263 ))
1264 }
1265 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001266}
1267
1268impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001269 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001270 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001271 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001272 BinderFeatures::default(),
1273 )
1274 }
1275}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001276
1277#[cfg(test)]
1278mod tests {
1279 use super::*;
1280
1281 #[test]
1282 fn test_is_allowed_label_for_partition() -> Result<()> {
1283 let expected_results = vec![
1284 ("u:object_r:system_file:s0", true),
1285 ("u:object_r:apk_data_file:s0", true),
1286 ("u:object_r:app_data_file:s0", false),
1287 ("u:object_r:app_data_file:s0:c512,c768", false),
1288 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1289 ("invalid", false),
1290 ("user:role:apk_data_file:severity:categories", true),
1291 ("user:role:apk_data_file:severity:categories:extraneous", false),
1292 ];
1293
1294 for (label, expected_valid) in expected_results {
1295 let context = SeContext::new(label)?;
1296 let result = check_label_is_allowed(&context);
1297 if expected_valid {
1298 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1299 } else if result.is_ok() {
1300 bail!("Expected label {} to be disallowed", label);
1301 }
1302 }
1303 Ok(())
1304 }
1305}