blob: a35c2acfa39bb16f2f8645fba20866fefc6f714a [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
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000118fn create_or_update_idsig_file(
119 input_fd: &ParcelFileDescriptor,
120 idsig_fd: &ParcelFileDescriptor,
121) -> Result<()> {
122 let mut input = clone_file(input_fd)?;
123 let metadata = input.metadata().context("failed to get input metadata")?;
124 if !metadata.is_file() {
125 bail!("input is not a regular file");
126 }
127 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
128 .context("failed to create idsig")?;
129
130 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000131 output.set_len(0).context("failed to set_len on the idsig output")?;
132 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000133 Ok(())
134}
135
David Brazdil528e0472022-10-10 15:06:02 +0100136/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
137/// singleton servers, like tombstone receiver.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900138#[derive(Debug, Default)]
David Brazdil528e0472022-10-10 15:06:02 +0100139pub struct VirtualizationServiceInternal {
140 state: Arc<Mutex<GlobalState>>,
141}
142
143impl VirtualizationServiceInternal {
144 pub fn init() -> VirtualizationServiceInternal {
145 let service = VirtualizationServiceInternal::default();
146
147 std::thread::spawn(|| {
148 if let Err(e) = handle_stream_connection_tombstoned() {
149 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
150 }
151 });
152
153 service
154 }
155}
156
157impl Interface for VirtualizationServiceInternal {}
158
159impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
160 fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
161 let state = &mut *self.state.lock().unwrap();
162 let cid = state.allocate_cid().map_err(|e| {
163 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
164 })?;
165 Ok(GlobalVmContext::create(cid))
166 }
167}
168
169/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
170/// of this struct.
171#[derive(Debug, Default)]
David Brazdil73988ea2022-11-11 15:10:32 +0000172struct GlobalState {
173 /// CIDs currently allocated to running VMs. A CID is never recycled as long
174 /// as there is a strong reference held by a GlobalVmContext.
175 held_cids: HashMap<Cid, Weak<Cid>>,
176}
David Brazdil528e0472022-10-10 15:06:02 +0100177
178impl GlobalState {
179 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
180 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
181 /// Android is up.
David Brazdil73988ea2022-11-11 15:10:32 +0000182 fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
183 // Garbage collect unused CIDs.
184 self.held_cids.retain(|_, cid| cid.strong_count() > 0);
185
186 // Start trying to find a CID from the last used CID + 1. This ensures
David Brazdil8cf8f482022-11-23 14:21:26 +0000187 // that we do not eagerly recycle CIDs. It makes debugging easier but
188 // also means that retrying to allocate a CID, eg. because it is
189 // erroneously occupied by a process, will not recycle the same CID.
David Brazdil73988ea2022-11-11 15:10:32 +0000190 let last_cid_prop =
191 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
192 Ok(num) => {
193 if is_valid_guest_cid(num) {
194 Some(num)
195 } else {
196 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
197 None
198 }
199 }
David Brazdil528e0472022-10-10 15:06:02 +0100200 Err(_) => {
201 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000202 None
David Brazdil528e0472022-10-10 15:06:02 +0100203 }
David Brazdil73988ea2022-11-11 15:10:32 +0000204 });
205
206 let first_cid = if let Some(last_cid) = last_cid_prop {
207 next_guest_cid(last_cid)
208 } else {
209 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100210 };
David Brazdil73988ea2022-11-11 15:10:32 +0000211
212 let cid = self
213 .find_available_cid(first_cid..=GUEST_CID_MAX)
214 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
215
216 if let Some(cid) = cid {
217 let cid_arc = Arc::new(cid);
218 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
219 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
220 Ok(cid_arc)
221 } else {
222 Err(anyhow!("Could not find an available CID."))
223 }
224 }
225
226 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
227 where
228 I: Iterator<Item = Cid>,
229 {
230 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100231 }
232}
233
234/// Implementation of the AIDL `IGlobalVmContext` interface.
235#[derive(Debug, Default)]
236struct GlobalVmContext {
237 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000238 cid: Arc<Cid>,
239 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100240 #[allow(dead_code)]
241 lazy_service_guard: LazyServiceGuard,
242}
243
244impl GlobalVmContext {
David Brazdil73988ea2022-11-11 15:10:32 +0000245 fn create(cid: Arc<Cid>) -> Strong<dyn IGlobalVmContext> {
David Brazdil528e0472022-10-10 15:06:02 +0100246 let binder = GlobalVmContext { cid, ..Default::default() };
247 BnGlobalVmContext::new_binder(binder, BinderFeatures::default())
248 }
249}
250
251impl Interface for GlobalVmContext {}
252
253impl IGlobalVmContext for GlobalVmContext {
254 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000255 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100256 }
257}
258
259/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
260#[derive(Debug)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000261pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900262 state: Arc<Mutex<State>>,
David Brazdil528e0472022-10-10 15:06:02 +0100263 global_service: Strong<dyn IVirtualizationServiceInternal>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000264}
265
Shikha Panward8e35422021-10-11 13:51:27 +0000266impl Interface for VirtualizationService {
267 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
268 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
269 let state = &mut *self.state.lock().unwrap();
270 let vms = state.vms();
271 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
272 for vm in vms {
273 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
274 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
275 .or(Err(StatusCode::UNKNOWN_ERROR))?;
276 writeln!(file, "\tPayload state {:?}", vm.payload_state())
277 .or(Err(StatusCode::UNKNOWN_ERROR))?;
278 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
279 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
280 .or(Err(StatusCode::UNKNOWN_ERROR))?;
281 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
282 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000283 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
284 .or(Err(StatusCode::UNKNOWN_ERROR))?;
285 }
286 Ok(())
287 }
288}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000289
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000290impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000291 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
292 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000293 ///
294 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000295 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000296 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000297 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900298 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000299 log_fd: Option<&ParcelFileDescriptor>,
300 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000301 let mut is_protected = false;
302 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000303 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000304 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000305 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000306
Andrew Walbrandff3b942021-06-09 15:20:36 +0000307 /// Initialise an empty partition image of the given size to be used as a writable partition.
308 fn initializeWritablePartition(
309 &self,
310 image_fd: &ParcelFileDescriptor,
311 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900312 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000313 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900314 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000315 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000316 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000317 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100318 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000319 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000320 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000321 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900322 // initialize the file. Any data in the file will be erased.
323 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000324 Status::new_service_specific_error_str(
325 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100326 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900327 )
328 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900329 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000330 Status::new_service_specific_error_str(
331 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100332 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000333 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000334 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000335
Jiyong Park9dd389e2021-08-23 20:42:59 +0900336 match partition_type {
337 PartitionType::RAW => Ok(()),
338 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000339 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900340 _ => Err(Error::new(
341 ErrorKind::Unsupported,
342 format!("Unsupported partition type {:?}", partition_type),
343 )),
344 }
345 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000346 Status::new_service_specific_error_str(
347 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100348 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900349 )
350 })?;
351
Andrew Walbrandff3b942021-06-09 15:20:36 +0000352 Ok(())
353 }
354
Jiyong Park0a248432021-08-20 23:32:39 +0900355 /// Creates or update the idsig file by digesting the input APK file.
356 fn createOrUpdateIdsigFile(
357 &self,
358 input_fd: &ParcelFileDescriptor,
359 idsig_fd: &ParcelFileDescriptor,
360 ) -> binder::Result<()> {
361 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
362 // idsig_fd is different from APK digest in input_fd
363
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900364 check_manage_access()?;
365
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000366 create_or_update_idsig_file(input_fd, idsig_fd)
367 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900368 Ok(())
369 }
370
Andrew Walbran320b5602021-03-04 16:11:12 +0000371 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
372 /// and as such is only permitted from the shell user.
373 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000374 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000375
376 let state = &mut *self.state.lock().unwrap();
377 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000378 let cids = vms
379 .into_iter()
380 .map(|vm| VirtualMachineDebugInfo {
381 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000382 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000383 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000384 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000385 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000386 })
387 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000388 Ok(cids)
389 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000390
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000391 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
392 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000393 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000394 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000395
David Brazdil3c2ddef2021-03-18 13:09:57 +0000396 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000397 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000398 Ok(())
399 }
400
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000401 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
402 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
403 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000404 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000405 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000406
407 let state = &mut *self.state.lock().unwrap();
408 Ok(state.debug_drop_vm(cid))
409 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000410}
411
Shikha Panwar7afc1392022-03-24 08:54:43 +0000412fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000413 // Should not listen for tombstones on a guest VM's port.
414 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000415 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000416 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000417 for incoming_stream in listener.incoming() {
418 let mut incoming_stream = match incoming_stream {
419 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100420 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000421 continue;
422 }
423 Ok(s) => s,
424 };
425 std::thread::spawn(move || {
426 if let Err(e) = handle_tombstone(&mut incoming_stream) {
427 error!("Failed to write tombstone- {:?}", e);
428 }
429 });
430 }
431 Ok(())
432}
433
434fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000435 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000436 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
437 }
438 let tb_connection =
439 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
440 .context("Failed to connect to tombstoned")?;
441 let mut text_output = tb_connection
442 .text_output
443 .as_ref()
444 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
445 let mut num_bytes_read = 0;
446 loop {
447 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
448 let n = stream
449 .read(&mut chunk_recv)
450 .context("Failed to read tombstone data from Vsock stream")?;
451 if n == 0 {
452 break;
453 }
454 num_bytes_read += n;
455 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
456 }
457 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
458 tb_connection.notify_completion()?;
459 Ok(())
460}
461
Jiyong Park8611a6c2021-07-09 18:17:44 +0900462impl VirtualizationService {
463 pub fn init() -> VirtualizationService {
David Brazdil528e0472022-10-10 15:06:02 +0100464 let global_service = VirtualizationServiceInternal::init();
465 let global_service =
466 BnVirtualizationServiceInternal::new_binder(global_service, BinderFeatures::default());
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900467
David Brazdil73988ea2022-11-11 15:10:32 +0000468 VirtualizationService { global_service, state: Default::default() }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900469 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470
David Brazdil8cf8f482022-11-23 14:21:26 +0000471 fn create_vm_context(&self) -> Result<(VmContext, Cid)> {
472 const NUM_ATTEMPTS: usize = 5;
473
474 for _ in 0..NUM_ATTEMPTS {
475 let global_context = self.global_service.allocateGlobalVmContext()?;
476 let cid = global_context.getCid()? as Cid;
477 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
478
479 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000480 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000481 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000482 Ok(vm_server) => {
483 vm_server.start();
484 return Ok((VmContext::new(global_context, vm_server), cid));
485 }
486 Err(err) => {
487 warn!("Could not start RpcServer on port {}: {}", port, err);
488 }
489 }
490 }
491 bail!("Too many attempts to create VM context failed.");
492 }
493
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000494 fn create_vm_internal(
495 &self,
496 config: &VirtualMachineConfig,
497 console_fd: Option<&ParcelFileDescriptor>,
498 log_fd: Option<&ParcelFileDescriptor>,
499 is_protected: &mut bool,
500 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
501 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900502
Alan Stokes7bc146c2022-10-20 17:10:32 +0100503 let is_custom = match config {
504 VirtualMachineConfig::RawConfig(_) => true,
505 VirtualMachineConfig::AppConfig(config) => {
506 // Some features are reserved for platform apps only, even when using
507 // VirtualMachineAppConfig:
508 // - controlling CPUs;
509 // - specifying a config file in the APK.
510 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900511 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100512 };
513 if is_custom {
514 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900515 }
516
David Brazdil8cf8f482022-11-23 14:21:26 +0000517 let (vm_context, cid) = self.create_vm_context().map_err(|e| {
518 error!("Failed to create VmContext: {:?}", e);
519 Status::new_service_specific_error_str(
520 -1,
521 Some(format!("Failed to create VmContext: {:?}", e)),
522 )
523 })?;
David Brazdil528e0472022-10-10 15:06:02 +0100524
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000525 let state = &mut *self.state.lock().unwrap();
526 let console_fd = console_fd.map(clone_file).transpose()?;
527 let log_fd = log_fd.map(clone_file).transpose()?;
528 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000529 let requester_debug_pid = ThreadState::get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000530
531 // Counter to generate unique IDs for temporary image files.
532 let mut next_temporary_image_id = 0;
533 // Files which are referred to from composite images. These must be mapped to the crosvm
534 // child process, and not closed before it is started.
535 let mut indirect_files = vec![];
536
537 // Make directory for temporary files.
538 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
539 create_dir(&temporary_directory).map_err(|e| {
540 // At this point, we do not know the protected status of Vm
541 // setting it to false, though this may not be correct.
542 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100543 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000544 temporary_directory, e
545 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000546 Status::new_service_specific_error_str(
547 -1,
548 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100549 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000550 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000551 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000552 )
553 })?;
554
Alan Stokes7bc146c2022-10-20 17:10:32 +0100555 let (is_app_config, config) = match config {
556 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
557 VirtualMachineConfig::AppConfig(config) => {
558 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000559 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100560 let message = format!("Failed to load app config: {:?}", e);
561 error!("{}", message);
562 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100563 })?;
564 (true, BorrowedOrOwned::Owned(config))
565 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000566 };
567 let config = config.as_ref();
568 *is_protected = config.protectedVm;
569
570 // Check if partition images are labeled incorrectly. This is to prevent random images
571 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100572 // being loaded in a pVM. This applies to everything in the raw config, and everything but
573 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000574 config
575 .disks
576 .iter()
577 .flat_map(|disk| disk.partitions.iter())
578 .filter(|partition| {
579 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100580 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000581 } else {
582 true // all partitions are checked
583 }
584 })
585 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100586 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000587
588 let zero_filler_path = temporary_directory.join("zero.img");
589 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100590 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000591 Status::new_service_specific_error_str(
592 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100593 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000594 )
595 })?;
596
597 // Assemble disk images if needed.
598 let disks = config
599 .disks
600 .iter()
601 .map(|disk| {
602 assemble_disk_image(
603 disk,
604 &zero_filler_path,
605 &temporary_directory,
606 &mut next_temporary_image_id,
607 &mut indirect_files,
608 )
609 })
610 .collect::<Result<Vec<DiskFile>, _>>()?;
611
Jiyong Parke558ab12022-07-07 20:18:55 +0900612 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
613 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900614 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900615 // will be sent back to the client (i.e. the VM owner) for readout.
616 let ramdump_path = temporary_directory.join("ramdump");
617 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100618 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000619 Status::new_service_specific_error_str(
620 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100621 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900622 )
623 })?;
624
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000625 // Actually start the VM.
626 let crosvm_config = CrosvmConfig {
627 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000628 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000629 bootloader: maybe_clone_file(&config.bootloader)?,
630 kernel: maybe_clone_file(&config.kernel)?,
631 initrd: maybe_clone_file(&config.initrd)?,
632 disks,
633 params: config.params.to_owned(),
634 protected: *is_protected,
635 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
636 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900637 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000638 console_fd,
639 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900640 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000641 indirect_files,
642 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900643 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000644 };
645 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100646 VmInstance::new(
647 crosvm_config,
648 temporary_directory,
649 requester_uid,
650 requester_debug_pid,
651 vm_context,
652 )
653 .map_err(|e| {
654 error!("Failed to create VM with config {:?}: {:?}", config, e);
655 Status::new_service_specific_error_str(
656 -1,
657 Some(format!("Failed to create VM: {:?}", e)),
658 )
659 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000660 );
661 state.add_vm(Arc::downgrade(&instance));
662 Ok(VirtualMachine::create(instance))
663 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900664}
665
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000666fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900667 let file = OpenOptions::new()
668 .create_new(true)
669 .read(true)
670 .write(true)
671 .open(zero_filler_path)
672 .with_context(|| "Failed to create zero.img")?;
673 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000674 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900675}
676
Jiyong Park9dd389e2021-08-23 20:42:59 +0900677fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
678 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
679 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
680 part.flush()
681}
682
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000683fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
684 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
685 part.flush()
686}
687
Jiyong Parke558ab12022-07-07 20:18:55 +0900688fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800689 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900690}
691
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000692/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
693///
694/// This may involve assembling a composite disk from a set of partition images.
695fn assemble_disk_image(
696 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900697 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000698 temporary_directory: &Path,
699 next_temporary_image_id: &mut u64,
700 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000701) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000702 let image = if !disk.partitions.is_empty() {
703 if disk.image.is_some() {
704 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000705 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000706 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000707 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000708 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000709 }
710
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000711 let composite_image_filenames =
712 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
713 let (image, partition_files) = make_composite_image(
714 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900715 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000716 &composite_image_filenames.composite,
717 &composite_image_filenames.header,
718 &composite_image_filenames.footer,
719 )
720 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100721 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000722 Status::new_service_specific_error_str(
723 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100724 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000725 )
726 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000727
728 // Pass the file descriptors for the various partition files to crosvm when it
729 // is run.
730 indirect_files.extend(partition_files);
731
732 image
733 } else if let Some(image) = &disk.image {
734 clone_file(image)?
735 } else {
736 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000737 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000738 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000739 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000740 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000741 };
742
743 Ok(DiskFile { image, writable: disk.writable })
744}
745
Jooyung Han21e9b922021-06-26 04:14:16 +0900746fn load_app_config(
747 config: &VirtualMachineAppConfig,
748 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900749) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000750 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
751 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900752 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900753
Shikha Panwar22e70452022-10-10 18:32:55 +0000754 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
755 Some(clone_file(file)?)
756 } else {
757 None
758 };
759
Alan Stokes0d1ef782022-09-27 13:46:35 +0100760 let vm_payload_config = match &config.payload {
761 Payload::ConfigPath(config_path) => {
762 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
763 .with_context(|| format!("Couldn't read config from {}", config_path))?
764 }
765 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
766 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900767
Alan Stokes0d1ef782022-09-27 13:46:35 +0100768 // For now, the only supported OS is Microdroid
769 let os_name = vm_payload_config.os.name.as_str();
770 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000771 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900772 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000773
774 // It is safe to construct a filename based on the os_name because we've already checked that it
775 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900776 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
777 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000778 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900779
Andrew Walbrancc045902021-07-27 16:06:17 +0000780 if config.memoryMib > 0 {
781 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000782 }
783
Seungjae Yoo62085c02022-08-12 04:44:52 +0000784 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000785 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900786 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900787 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900788
Shikha Panwar22e70452022-10-10 18:32:55 +0000789 // Microdroid takes additional init ramdisk & (optionally) storage image
790 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
791
792 // Include Microdroid payload disk (contains apks, idsigs) in vm config
793 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100794 config,
795 temporary_directory,
796 apk_file,
797 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100798 &vm_payload_config,
799 &mut vm_config,
800 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900801
Andrew Walbrancc0db522021-07-12 17:03:42 +0000802 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900803}
804
Alan Stokes0d1ef782022-09-27 13:46:35 +0100805fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
806 let mut apk_zip = ZipArchive::new(apk_file)?;
807 let config_file = apk_zip.by_name(config_path)?;
808 Ok(serde_json::from_reader(config_file)?)
809}
810
811fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
812 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
813 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
814 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100815 let task =
816 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100817 VmPayloadConfig {
818 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
819 task: Some(task),
820 apexes: vec![],
821 extra_apks: vec![],
822 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100823 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100824 enable_authfs: false,
825 }
826}
827
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000828/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000829fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000830 temporary_directory: &Path,
831 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000832) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000833 let id = *next_temporary_image_id;
834 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000835 CompositeImageFilenames {
836 composite: temporary_directory.join(format!("composite-{}.img", id)),
837 header: temporary_directory.join(format!("composite-{}-header.img", id)),
838 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
839 }
840}
841
842/// Filenames for a composite disk image, including header and footer partitions.
843#[derive(Clone, Debug, Eq, PartialEq)]
844struct CompositeImageFilenames {
845 /// The composite disk image itself.
846 composite: PathBuf,
847 /// The header partition image.
848 header: PathBuf,
849 /// The footer partition image.
850 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000851}
852
Jiyong Park753553b2021-07-12 21:21:09 +0900853/// Checks whether the caller has a specific permission
854fn check_permission(perm: &str) -> binder::Result<()> {
855 let calling_pid = ThreadState::get_calling_pid();
856 let calling_uid = ThreadState::get_calling_uid();
857 // Root can do anything
858 if calling_uid == 0 {
859 return Ok(());
860 }
861 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
862 binder::get_interface("permission")?;
863 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000864 Ok(())
865 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000866 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900867 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000868 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900869 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000870 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000871}
872
Jiyong Park753553b2021-07-12 21:21:09 +0900873/// Check whether the caller of the current Binder method is allowed to call debug methods.
874fn check_debug_access() -> binder::Result<()> {
875 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
876}
877
878/// Check whether the caller of the current Binder method is allowed to manage VMs
879fn check_manage_access() -> binder::Result<()> {
880 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
881}
882
Inseob Kim1119d702022-05-02 18:01:58 +0900883/// Check whether the caller of the current Binder method is allowed to create custom VMs
884fn check_use_custom_virtual_machine() -> binder::Result<()> {
885 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
886}
887
Jiyong Park029977d2021-11-24 21:56:49 +0900888/// Check if a partition has selinux labels that are not allowed
889fn check_label_for_partition(partition: &Partition) -> Result<()> {
890 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100891 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
892}
893
894// Return whether a partition is exempt from selinux label checks, because we know that it does
895// not contain code and is likely to be generated in an app-writable directory.
896fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000897 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100898 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000899 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100900 || label == "microdroid-apk-idsig"
901 || label == "payload-metadata"
902 || label.starts_with("extra-idsig-")
903}
904
905fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
906 // We only want to allow code in a VM payload to be sourced from places that apps, and the
907 // system, do not have write access to.
908 // (Note that sepolicy must also grant read access for these types to both virtualization
909 // service and crosvm.)
910 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
911 // user devices (W^X).
912 match ctx.selinux_type()? {
913 | "system_file" // immutable dm-verity protected partition
914 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000915 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100916 | "shell_data_file" // test files created via adb shell
917 => Ok(()),
918 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900919 }
920}
921
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000922/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
923#[derive(Debug)]
924struct VirtualMachine {
925 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100926 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800927 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100928 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000929}
930
931impl VirtualMachine {
932 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100933 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000934 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000935 }
936}
937
938impl Interface for VirtualMachine {}
939
940impl IVirtualMachine for VirtualMachine {
941 fn getCid(&self) -> binder::Result<i32> {
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.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000944 Ok(self.instance.cid as i32)
945 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000946
Andrew Walbran6b650662021-09-07 13:13:23 +0000947 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900948 // Don't check permission. The owner of the VM might have passed this binder object to
949 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000950 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000951 }
952
953 fn registerCallback(
954 &self,
955 callback: &Strong<dyn IVirtualMachineCallback>,
956 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900957 // Don't check permission. The owner of the VM might have passed this binder object to
958 // others.
959 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000960 // TODO: Should this give an error if the VM is already dead?
961 self.instance.callbacks.add(callback.clone());
962 Ok(())
963 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000964
Andrew Walbranf8d94112021-09-07 11:45:36 +0000965 fn start(&self) -> binder::Result<()> {
966 self.instance.start().map_err(|e| {
967 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000968 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000969 })
970 }
971
Inseob Kima446f802022-07-11 19:46:37 +0900972 fn stop(&self) -> binder::Result<()> {
973 self.instance.kill().map_err(|e| {
974 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000975 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900976 })
977 }
978
Keir Frasercdd4b112022-11-24 14:02:25 +0000979 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
980 self.instance.trim_memory(level).map_err(|e| {
981 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
982 Status::new_service_specific_error_str(-1, Some(e.to_string()))
983 })
984 }
985
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000986 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000987 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000988 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000989 }
Alan Stokes10c47672022-12-13 17:17:08 +0000990 let port = port as u32;
991 if port < 1024 {
992 return Err(Status::new_service_specific_error_str(
993 -1,
994 Some(format!("Can't connect to privileged port {port}")),
995 ));
996 }
997 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
998 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
999 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001000 Ok(vsock_stream_to_pfd(stream))
1001 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001002}
1003
1004impl Drop for VirtualMachine {
1005 fn drop(&mut self) {
1006 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001007 if let Err(e) = self.instance.kill() {
1008 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1009 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001010 }
1011}
1012
1013/// A set of Binders to be called back in response to various events on the VM, such as when it
1014/// dies.
1015#[derive(Debug, Default)]
1016pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1017
1018impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001019 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001020 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001021 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001022 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001023 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001024 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001025 }
1026 }
1027 }
1028
Inseob Kim14cb8692021-08-31 21:50:39 +09001029 /// Call all registered callbacks to notify that the payload is ready to serve.
1030 pub fn notify_payload_ready(&self, cid: Cid) {
1031 let callbacks = &*self.0.lock().unwrap();
1032 for callback in callbacks {
1033 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001034 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001035 }
1036 }
1037 }
1038
Inseob Kim2444af92021-08-31 01:22:50 +09001039 /// Call all registered callbacks to notify that the payload has finished.
1040 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1041 let callbacks = &*self.0.lock().unwrap();
1042 for callback in callbacks {
1043 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001044 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001045 }
1046 }
1047 }
1048
Jooyung Handd0a1732021-11-23 15:26:20 +09001049 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001050 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001051 let callbacks = &*self.0.lock().unwrap();
1052 for callback in callbacks {
1053 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001054 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001055 }
1056 }
1057 }
1058
Andrew Walbrandae07162021-03-12 17:05:20 +00001059 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001060 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001061 let callbacks = &*self.0.lock().unwrap();
1062 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001063 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001064 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001065 }
1066 }
1067 }
1068
1069 /// Add a new callback to the set.
1070 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1071 self.0.lock().unwrap().push(callback);
1072 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001073}
1074
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001075/// The mutable state of the VirtualizationService. There should only be one instance of this
1076/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001077#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001078struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001079 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1080 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1081 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1082 /// from the list opportunistically the next time `add_vm` is called.
1083 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001084
1085 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1086 /// This is only used for debugging purposes.
1087 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001088}
1089
1090impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001091 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001092 fn vms(&self) -> Vec<Arc<VmInstance>> {
1093 // Attempt to upgrade the weak pointers to strong pointers.
1094 self.vms.iter().filter_map(Weak::upgrade).collect()
1095 }
1096
1097 /// Add a new VM to the list.
1098 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1099 // Garbage collect any entries from the stored list which no longer exist.
1100 self.vms.retain(|vm| vm.strong_count() > 0);
1101
1102 // Actually add the new VM.
1103 self.vms.push(vm);
1104 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001105
Jiyong Park8611a6c2021-07-09 18:17:44 +09001106 /// Get a VM that corresponds to the given cid
1107 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1108 self.vms().into_iter().find(|vm| vm.cid == cid)
1109 }
1110
David Brazdil3c2ddef2021-03-18 13:09:57 +00001111 /// Store a strong VM reference.
1112 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1113 self.debug_held_vms.push(vm);
1114 }
1115
1116 /// Retrieve and remove a strong VM reference.
1117 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1118 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001119 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001120 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001121 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001122}
1123
Andrew Walbran6b650662021-09-07 13:13:23 +00001124/// Gets the `VirtualMachineState` of the given `VmInstance`.
1125fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001126 match &*instance.vm_state.lock().unwrap() {
1127 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1128 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001129 PayloadState::Starting => VirtualMachineState::STARTING,
1130 PayloadState::Started => VirtualMachineState::STARTED,
1131 PayloadState::Ready => VirtualMachineState::READY,
1132 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001133 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001134 },
1135 VmState::Dead => VirtualMachineState::DEAD,
1136 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001137 }
1138}
1139
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001140/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001141pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001142 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001143 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001144 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001145 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001146 )
1147 })
1148}
1149
Andrew Walbrand3a84182021-09-07 14:48:52 +00001150/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1151fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1152 file.as_ref().map(clone_file).transpose()
1153}
1154
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001155/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1156fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1157 // SAFETY: ownership is transferred from stream to f
1158 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1159 ParcelFileDescriptor::new(f)
1160}
1161
Jiyong Parkdcf17412022-02-08 15:07:23 +09001162/// Parses the platform version requirement string.
1163fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1164 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001165 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001166 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001167 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001168 )
1169 })
1170}
1171
Jooyung Han35edb8f2021-07-01 16:17:16 +09001172/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1173/// it doesn't require that T implements Clone.
1174enum BorrowedOrOwned<'a, T> {
1175 Borrowed(&'a T),
1176 Owned(T),
1177}
1178
1179impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1180 fn as_ref(&self) -> &T {
1181 match self {
1182 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001183 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001184 }
1185 }
1186}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001187
1188/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1189#[derive(Debug, Default)]
1190struct VirtualMachineService {
1191 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001192 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001193}
1194
1195impl Interface for VirtualMachineService {}
1196
1197impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001198 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1199 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001200 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001201 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001202 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1203 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1204 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001205 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001206
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001207 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1208 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001209 Ok(())
1210 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001211 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001212 Err(Status::new_service_specific_error_str(
1213 -1,
1214 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001215 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001216 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001217 }
Inseob Kim2444af92021-08-31 01:22:50 +09001218
Inseob Kimc7d28c72021-10-25 14:28:10 +00001219 fn notifyPayloadReady(&self) -> binder::Result<()> {
1220 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001221 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001222 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001223 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1224 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1225 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001226 vm.callbacks.notify_payload_ready(cid);
1227 Ok(())
1228 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001229 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001230 Err(Status::new_service_specific_error_str(
1231 -1,
1232 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001233 ))
1234 }
1235 }
1236
Inseob Kimc7d28c72021-10-25 14:28:10 +00001237 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1238 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001239 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001240 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001241 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1242 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1243 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001244 vm.callbacks.notify_payload_finished(cid, exit_code);
1245 Ok(())
1246 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001247 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001248 Err(Status::new_service_specific_error_str(
1249 -1,
1250 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001251 ))
1252 }
1253 }
1254
Alan Stokes2bead0d2022-09-05 16:58:34 +01001255 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001256 let cid = self.cid;
1257 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001258 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001259 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1260 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1261 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001262 vm.callbacks.notify_error(cid, error_code, message);
1263 Ok(())
1264 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001265 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001266 Err(Status::new_service_specific_error_str(
1267 -1,
1268 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001269 ))
1270 }
1271 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001272}
1273
1274impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001275 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001276 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001277 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001278 BinderFeatures::default(),
1279 )
1280 }
1281}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001282
1283#[cfg(test)]
1284mod tests {
1285 use super::*;
1286
1287 #[test]
1288 fn test_is_allowed_label_for_partition() -> Result<()> {
1289 let expected_results = vec![
1290 ("u:object_r:system_file:s0", true),
1291 ("u:object_r:apk_data_file:s0", true),
1292 ("u:object_r:app_data_file:s0", false),
1293 ("u:object_r:app_data_file:s0:c512,c768", false),
1294 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1295 ("invalid", false),
1296 ("user:role:apk_data_file:severity:categories", true),
1297 ("user:role:apk_data_file:severity:categories:extraneous", false),
1298 ];
1299
1300 for (label, expected_valid) in expected_results {
1301 let context = SeContext::new(label)?;
1302 let result = check_label_is_allowed(&context);
1303 if expected_valid {
1304 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1305 } else if result.is_ok() {
1306 bail!("Expected label {} to be disallowed", label);
1307 }
1308 }
1309 Ok(())
1310 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001311
1312 #[test]
1313 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1314 let apk = tempfile::tempfile().unwrap();
1315 let idsig = tempfile::tempfile().unwrap();
1316
1317 let ret = create_or_update_idsig_file(
1318 &ParcelFileDescriptor::new(apk),
1319 &ParcelFileDescriptor::new(idsig),
1320 );
1321 assert!(ret.is_err(), "should fail");
1322 Ok(())
1323 }
1324
1325 #[test]
1326 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1327 let tmp_dir = tempfile::TempDir::new().unwrap();
1328 let apk = File::open(tmp_dir.path()).unwrap();
1329 let idsig = tempfile::tempfile().unwrap();
1330
1331 let ret = create_or_update_idsig_file(
1332 &ParcelFileDescriptor::new(apk),
1333 &ParcelFileDescriptor::new(idsig),
1334 );
1335 assert!(ret.is_err(), "should fail");
1336 Ok(())
1337 }
1338
1339 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1340 /// on ext4 filesystem is passed.
1341 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1342 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1343 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1344 #[test]
1345 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1346 // APEXes are backed by the ext4.
1347 let apk = File::open("/apex/com.android.virt/").unwrap();
1348 let idsig = tempfile::tempfile().unwrap();
1349
1350 let ret = create_or_update_idsig_file(
1351 &ParcelFileDescriptor::new(apk),
1352 &ParcelFileDescriptor::new(idsig),
1353 );
1354 assert!(ret.is_err(), "should fail");
1355 Ok(())
1356 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001357}