blob: 5283ffe2c68ba0d0c171c6a21dddd47cea489226 [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
David Brazdil1f530702022-10-03 12:18:10 +010017use crate::{get_calling_pid, get_calling_uid};
David Brazdil49f96f52022-12-16 21:29:13 +000018use crate::atom::{
David Brazdil49f96f52022-12-16 21:29:13 +000019 write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020use crate::composite::make_composite_image;
Inseob Kim7307a892023-09-14 13:37:58 +090021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VfioDevice, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090022use crate::debug_config::DebugConfig;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000027 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000028 ErrorCode::ErrorCode,
29};
30use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090031 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000032 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010034 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000035 IVirtualMachineCallback::IVirtualMachineCallback,
36 IVirtualizationService::IVirtualizationService,
Alan Stokes27f3ef02023-09-29 15:09:35 +010037 IVirtualizationService::FEATURE_MULTI_TENANT,
Nikita Ioffe631717e2023-09-05 13:38:07 +010038 IVirtualizationService::FEATURE_VENDOR_MODULES,
Alan Stokes7f27c0d2023-09-07 16:22:58 +010039 IVirtualizationService::FEATURE_DICE_CHANGES,
Keir Frasercdd4b112022-11-24 14:02:25 +000040 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090041 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090043 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010046 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090047 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000048 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090049};
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Alan Stokes25f69362023-03-06 16:51:54 +000054use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090055use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090056use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010057use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000058 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
59 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090060 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000061};
David Brazdilf50c7a62023-04-19 14:22:42 +000062use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000063use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000064use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090065use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090066use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000067use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000068use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090069use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090070use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000071use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000072use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090073use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000074use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000075use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000076use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000077use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000079use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000080use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000081use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090082use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000083
David Brazdil41d1a872022-10-05 14:44:19 +010084/// The unique ID of a VM used (together with a port number) for vsock communication.
85pub type Cid = u32;
86
David Brazdil4b4c5102022-12-19 22:56:20 +000087pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
88
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
David Brazdilf50c7a62023-04-19 14:22:42 +000093/// 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
Alan Stokes0d1ef782022-09-27 13:46:35 +010099const MICRODROID_OS_NAME: &str = "microdroid";
100
David Brazdilf50c7a62023-04-19 14:22:42 +0000101const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
102
103/// crosvm requires all partitions to be a multiple of 4KiB.
104const PARTITION_GRANULARITY_BYTES: u64 = 4096;
105
David Brazdil49f96f52022-12-16 21:29:13 +0000106lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000107 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
108 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
109 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000110}
111
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000112fn create_or_update_idsig_file(
113 input_fd: &ParcelFileDescriptor,
114 idsig_fd: &ParcelFileDescriptor,
115) -> Result<()> {
116 let mut input = clone_file(input_fd)?;
117 let metadata = input.metadata().context("failed to get input metadata")?;
118 if !metadata.is_file() {
119 bail!("input is not a regular file");
120 }
Alan Stokes25f69362023-03-06 16:51:54 +0000121 let mut sig =
122 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
123 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000124
125 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900126
127 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
128 // if the idsig file already has the same APK digest.
129 if output.metadata()?.len() > 0 {
130 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
131 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
132 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
133 return Ok(());
134 }
135 }
136 // if we fail to read v4signature from output, that's fine. User can pass a random file.
137 // We will anyway overwrite the file to the v4signature generated from input_fd.
138 }
139
Nikita Ioffec09b0492022-12-14 20:18:33 +0000140 output.set_len(0).context("failed to set_len on the idsig output")?;
141 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000142 Ok(())
143}
144
Alan Stokes25f69362023-03-06 16:51:54 +0000145fn get_current_sdk() -> Result<u32> {
146 let current_sdk = system_properties::read("ro.build.version.sdk")?;
147 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
148 current_sdk.parse().context("Malformed SDK version")
149}
150
David Brazdil4b4c5102022-12-19 22:56:20 +0000151pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
152 for dir_entry in read_dir(path)? {
153 remove_file(dir_entry?.path())?;
154 }
155 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100156}
157
David Brazdil528e0472022-10-10 15:06:02 +0100158/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000159#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000160pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900161 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000162}
163
Shikha Panward8e35422021-10-11 13:51:27 +0000164impl Interface for VirtualizationService {
165 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
166 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
167 let state = &mut *self.state.lock().unwrap();
168 let vms = state.vms();
169 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
170 for vm in vms {
171 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
172 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
173 .or(Err(StatusCode::UNKNOWN_ERROR))?;
174 writeln!(file, "\tPayload state {:?}", vm.payload_state())
175 .or(Err(StatusCode::UNKNOWN_ERROR))?;
176 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
177 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
178 .or(Err(StatusCode::UNKNOWN_ERROR))?;
179 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
180 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000181 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
182 .or(Err(StatusCode::UNKNOWN_ERROR))?;
183 }
184 Ok(())
185 }
186}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000187impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000188 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
189 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000190 ///
191 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000192 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000193 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000194 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900195 console_out_fd: Option<&ParcelFileDescriptor>,
196 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000197 log_fd: Option<&ParcelFileDescriptor>,
198 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000199 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900200 let ret = self.create_vm_internal(
201 config,
202 console_out_fd,
203 console_in_fd,
204 log_fd,
205 &mut is_protected,
206 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000207 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000208 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000209 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000210
Andrew Walbrandff3b942021-06-09 15:20:36 +0000211 /// Initialise an empty partition image of the given size to be used as a writable partition.
212 fn initializeWritablePartition(
213 &self,
214 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000215 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900216 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000217 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900218 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900219 let size_bytes = size_bytes
220 .try_into()
221 .with_context(|| format!("Invalid size: {}", size_bytes))
222 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000223 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
224 let image = clone_file(image_fd)?;
225 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900226 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
227 let mut part = QcowFile::new(image, size_bytes)
228 .context("Failed to create QCOW2 image")
229 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000230
231 match partition_type {
232 PartitionType::RAW => Ok(()),
233 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
234 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
235 _ => Err(Error::new(
236 ErrorKind::Unsupported,
237 format!("Unsupported partition type {:?}", partition_type),
238 )),
239 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900240 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
241 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000242
243 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000244 }
245
Jiyong Park0a248432021-08-20 23:32:39 +0900246 /// Creates or update the idsig file by digesting the input APK file.
247 fn createOrUpdateIdsigFile(
248 &self,
249 input_fd: &ParcelFileDescriptor,
250 idsig_fd: &ParcelFileDescriptor,
251 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900252 check_manage_access()?;
253
Jiyong Park2227eaa2023-08-04 11:59:18 +0900254 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900255 Ok(())
256 }
257
Andrew Walbran320b5602021-03-04 16:11:12 +0000258 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
259 /// and as such is only permitted from the shell user.
260 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000261 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000262 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000263 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900264
265 /// Get a list of assignable device types.
266 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
267 // Delegate to the global service, including checking the permission.
268 GLOBAL_SERVICE.getAssignableDevices()
269 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100270
271 /// Returns whether given feature is enabled
272 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
273 check_manage_access()?;
274
275 // This approach is quite cumbersome, but will do the work for the short term.
276 // TODO(b/298012279): make this scalable.
277 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100278 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100279 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100280 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100281 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100282 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100283 Ok(false)
284 }
285 }
286 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000287}
288
Jiyong Park8611a6c2021-07-09 18:17:44 +0900289impl VirtualizationService {
290 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000291 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900292 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000293
David Brazdil209074a2023-01-12 16:44:51 +0000294 fn create_vm_context(
295 &self,
296 requester_debug_pid: pid_t,
297 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000298 const NUM_ATTEMPTS: usize = 5;
299
300 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000301 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000302 let cid = vm_context.getCid()? as Cid;
303 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000304 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
305
306 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000307 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000308 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000309 Ok(vm_server) => {
310 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000311 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000312 }
313 Err(err) => {
314 warn!("Could not start RpcServer on port {}: {}", port, err);
315 }
316 }
317 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900318 Err(anyhow!("Too many attempts to create VM context failed"))
319 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000320 }
321
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000322 fn create_vm_internal(
323 &self,
324 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900325 console_out_fd: Option<&ParcelFileDescriptor>,
326 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000327 log_fd: Option<&ParcelFileDescriptor>,
328 is_protected: &mut bool,
329 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000330 let requester_uid = get_calling_uid();
331 let requester_debug_pid = get_calling_pid();
332
Nikita Ioffe631717e2023-09-05 13:38:07 +0100333 check_config_features(config)?;
334
David Brazdil209074a2023-01-12 16:44:51 +0000335 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
336 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900337
Alan Stokes7bc146c2022-10-20 17:10:32 +0100338 let is_custom = match config {
339 VirtualMachineConfig::RawConfig(_) => true,
340 VirtualMachineConfig::AppConfig(config) => {
341 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100342 // VirtualMachineAppConfig. Almost all of these features are grouped in the
343 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100344 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100345 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100346 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900347 // - using anything other than the default kernel;
348 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100349 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900350 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100351 };
352 if is_custom {
353 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900354 }
355
Nikita Ioffe5776f082023-02-10 21:38:26 +0000356 let gdb_port = extract_gdb_port(config);
357
358 // Additional permission checks if caller request gdb.
359 if gdb_port.is_some() {
360 check_gdb_allowed(config)?;
361 }
362
Jaewan Kim61f86142023-03-28 15:12:52 +0900363 let debug_level = match config {
364 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
365 _ => DebugLevel::NONE,
366 };
367 let debug_config = DebugConfig::new(debug_level);
368
369 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900370 Some(prepare_ramdump_file(&temporary_directory)?)
371 } else {
372 None
373 };
374
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000375 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900376 let console_out_fd =
377 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
378 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900379 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000380
381 // Counter to generate unique IDs for temporary image files.
382 let mut next_temporary_image_id = 0;
383 // Files which are referred to from composite images. These must be mapped to the crosvm
384 // child process, and not closed before it is started.
385 let mut indirect_files = vec![];
386
Alan Stokes7bc146c2022-10-20 17:10:32 +0100387 let (is_app_config, config) = match config {
388 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
389 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900390 let config = load_app_config(config, &debug_config, &temporary_directory)
391 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900392 *is_protected = config.protectedVm;
393 let message = format!("Failed to load app config: {:?}", e);
394 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900395 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900396 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100397 (true, BorrowedOrOwned::Owned(config))
398 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000399 };
400 let config = config.as_ref();
401 *is_protected = config.protectedVm;
402
403 // Check if partition images are labeled incorrectly. This is to prevent random images
404 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100405 // being loaded in a pVM. This applies to everything but the instance image in the raw
406 // config, and everything but the non-executable, generated partitions in the app
407 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000408 config
409 .disks
410 .iter()
411 .flat_map(|disk| disk.partitions.iter())
412 .filter(|partition| {
413 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100414 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000415 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000416 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000417 }
418 })
419 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900420 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000421
Alan Stokes185fe112023-01-10 16:20:55 +0000422 let kernel = maybe_clone_file(&config.kernel)?;
423 let initrd = maybe_clone_file(&config.initrd)?;
424
425 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
426 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900427 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000428 }
429
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000430 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900431 write_zero_filler(&zero_filler_path)
432 .context("Failed to make composite image")
433 .with_log()
434 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000435
436 // Assemble disk images if needed.
437 let disks = config
438 .disks
439 .iter()
440 .map(|disk| {
441 assemble_disk_image(
442 disk,
443 &zero_filler_path,
444 &temporary_directory,
445 &mut next_temporary_image_id,
446 &mut indirect_files,
447 )
448 })
449 .collect::<Result<Vec<DiskFile>, _>>()?;
450
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000451 let (cpus, host_cpu_topology) = match config.cpuTopology {
452 CpuTopology::MATCH_HOST => (None, true),
453 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
454 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900455 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
456 .with_log()
457 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000458 }
459 };
460
Inseob Kim7307a892023-09-14 13:37:58 +0900461 let vfio_devices = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900462 let mut set = HashSet::new();
463 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900464 let path = canonicalize(device)
465 .with_context(|| format!("can't canonicalize {device}"))
466 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900467 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900468 return Err(anyhow!("duplicated device {device}"))
469 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900470 }
471 }
Inseob Kim7307a892023-09-14 13:37:58 +0900472 GLOBAL_SERVICE
473 .bindDevicesToVfioDriver(&config.devices)?
474 .into_iter()
475 .map(|x| VfioDevice {
476 sysfs_path: PathBuf::from(&x.sysfsPath),
Jaewan Kim35e818d2023-10-18 05:36:38 +0000477 dtbo_label: x.dtboLabel,
Inseob Kim7307a892023-09-14 13:37:58 +0900478 })
479 .collect::<Vec<_>>()
480 } else {
481 vec![]
482 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900483
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000484 // Actually start the VM.
485 let crosvm_config = CrosvmConfig {
486 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000487 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000488 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000489 kernel,
490 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 disks,
492 params: config.params.to_owned(),
493 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900494 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000495 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000496 cpus,
497 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900498 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900499 console_out_fd,
500 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000501 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900502 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000503 indirect_files,
504 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900505 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000506 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900507 vfio_devices,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000508 };
509 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100510 VmInstance::new(
511 crosvm_config,
512 temporary_directory,
513 requester_uid,
514 requester_debug_pid,
515 vm_context,
516 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900517 .with_context(|| format!("Failed to create VM with config {:?}", config))
518 .with_log()
519 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000520 );
521 state.add_vm(Arc::downgrade(&instance));
522 Ok(VirtualMachine::create(instance))
523 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900524}
525
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000526fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900527 let file = OpenOptions::new()
528 .create_new(true)
529 .read(true)
530 .write(true)
531 .open(zero_filler_path)
532 .with_context(|| "Failed to create zero.img")?;
533 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000534 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900535}
536
David Brazdilf50c7a62023-04-19 14:22:42 +0000537fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
538 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
539 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
540 part.flush()
541}
542
543fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
544 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
545 part.flush()
546}
547
548fn round_up(input: u64, granularity: u64) -> u64 {
549 if granularity == 0 {
550 return input;
551 }
552 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
553 let result = input.checked_add(granularity - 1).unwrap_or(input);
554 (result / granularity) * granularity
555}
556
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000557/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
558///
559/// This may involve assembling a composite disk from a set of partition images.
560fn assemble_disk_image(
561 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900562 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000563 temporary_directory: &Path,
564 next_temporary_image_id: &mut u64,
565 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000566) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000567 let image = if !disk.partitions.is_empty() {
568 if disk.image.is_some() {
569 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900570 return Err(anyhow!("DiskImage contains both image and partitions"))
571 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000572 }
573
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000574 let composite_image_filenames =
575 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
576 let (image, partition_files) = make_composite_image(
577 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900578 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000579 &composite_image_filenames.composite,
580 &composite_image_filenames.header,
581 &composite_image_filenames.footer,
582 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900583 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
584 .with_log()
585 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000586
587 // Pass the file descriptors for the various partition files to crosvm when it
588 // is run.
589 indirect_files.extend(partition_files);
590
591 image
592 } else if let Some(image) = &disk.image {
593 clone_file(image)?
594 } else {
595 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900596 return Err(anyhow!("DiskImage didn't contain image or partitions."))
597 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000598 };
599
600 Ok(DiskFile { image, writable: disk.writable })
601}
602
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100603fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
604 if let Some(ref mut params) = vm_config.params {
605 params.push(' ');
606 params.push_str(param)
607 } else {
608 vm_config.params = Some(param.to_owned())
609 }
610}
611
Jooyung Han21e9b922021-06-26 04:14:16 +0900612fn load_app_config(
613 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900614 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900615 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900616) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000617 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
618 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900619 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900620
Shikha Panwar22e70452022-10-10 18:32:55 +0000621 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
622 Some(clone_file(file)?)
623 } else {
624 None
625 };
626
Alan Stokes0d1ef782022-09-27 13:46:35 +0100627 let vm_payload_config = match &config.payload {
628 Payload::ConfigPath(config_path) => {
629 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
630 .with_context(|| format!("Couldn't read config from {}", config_path))?
631 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000632 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100633 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900634
Alan Stokes0d1ef782022-09-27 13:46:35 +0100635 // For now, the only supported OS is Microdroid
636 let os_name = vm_payload_config.os.name.as_str();
637 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000638 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900639 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000640
641 // It is safe to construct a filename based on the os_name because we've already checked that it
642 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900643 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
644 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000645 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900646
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100647 if let Some(custom_config) = &config.customConfig {
648 if let Some(file) = custom_config.customKernelImage.as_ref() {
649 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
650 }
651 vm_config.taskProfiles = custom_config.taskProfiles.clone();
652 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100653
654 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100655 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
656 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100657 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900658
659 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100660 }
661
Andrew Walbrancc045902021-07-27 16:06:17 +0000662 if config.memoryMib > 0 {
663 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000664 }
665
Seungjae Yoo62085c02022-08-12 04:44:52 +0000666 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000667 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000668 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900669
Shikha Panwar22e70452022-10-10 18:32:55 +0000670 // Microdroid takes additional init ramdisk & (optionally) storage image
671 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
672
673 // Include Microdroid payload disk (contains apks, idsigs) in vm config
674 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100675 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900676 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100677 temporary_directory,
678 apk_file,
679 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100680 &vm_payload_config,
681 &mut vm_config,
682 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900683
Andrew Walbrancc0db522021-07-12 17:03:42 +0000684 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900685}
686
Alan Stokes0d1ef782022-09-27 13:46:35 +0100687fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
688 let mut apk_zip = ZipArchive::new(apk_file)?;
689 let config_file = apk_zip.by_name(config_path)?;
690 Ok(serde_json::from_reader(config_file)?)
691}
692
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000693fn create_vm_payload_config(
694 payload_config: &VirtualMachinePayloadConfig,
695) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100696 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
697 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
698 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000699
700 let payload_binary_name = &payload_config.payloadBinaryName;
701 if payload_binary_name.contains('/') {
702 bail!("Payload binary name must not specify a path: {payload_binary_name}");
703 }
704
705 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
706 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100707 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
708 task: Some(task),
709 apexes: vec![],
710 extra_apks: vec![],
711 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900712 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100713 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000714 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100715}
716
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000717/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000718fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000719 temporary_directory: &Path,
720 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000721) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000722 let id = *next_temporary_image_id;
723 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000724 CompositeImageFilenames {
725 composite: temporary_directory.join(format!("composite-{}.img", id)),
726 header: temporary_directory.join(format!("composite-{}-header.img", id)),
727 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
728 }
729}
730
731/// Filenames for a composite disk image, including header and footer partitions.
732#[derive(Clone, Debug, Eq, PartialEq)]
733struct CompositeImageFilenames {
734 /// The composite disk image itself.
735 composite: PathBuf,
736 /// The header partition image.
737 header: PathBuf,
738 /// The footer partition image.
739 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000740}
741
Jiyong Park753553b2021-07-12 21:21:09 +0900742/// Checks whether the caller has a specific permission
743fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100744 let calling_pid = get_calling_pid();
745 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900746 // Root can do anything
747 if calling_uid == 0 {
748 return Ok(());
749 }
750 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
751 binder::get_interface("permission")?;
752 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000753 Ok(())
754 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900755 Err(anyhow!("does not have the {} permission", perm))
756 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000757 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000758}
759
Jiyong Park753553b2021-07-12 21:21:09 +0900760/// Check whether the caller of the current Binder method is allowed to manage VMs
761fn check_manage_access() -> binder::Result<()> {
762 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
763}
764
Inseob Kim1119d702022-05-02 18:01:58 +0900765/// Check whether the caller of the current Binder method is allowed to create custom VMs
766fn check_use_custom_virtual_machine() -> binder::Result<()> {
767 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
768}
769
Alan Stokes185fe112023-01-10 16:20:55 +0000770/// Return whether a partition is exempt from selinux label checks, because we know that it does
771/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100772fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000773 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100774 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000775 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100776 || label == "microdroid-apk-idsig"
777 || label == "payload-metadata"
778 || label.starts_with("extra-idsig-")
779}
780
Alice Wangc206b9b2023-08-28 14:13:51 +0000781/// Returns whether a partition with the given label is safe for a raw config VM.
782fn is_safe_raw_partition(label: &str) -> bool {
783 label == "vm-instance"
784}
785
Alan Stokes185fe112023-01-10 16:20:55 +0000786/// Check that a file SELinux label is acceptable.
787///
788/// We only want to allow code in a VM to be sourced from places that apps, and the
789/// system, do not have write access to.
790///
791/// Note that sepolicy must also grant read access for these types to both virtualization
792/// service and crosvm.
793///
794/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
795/// user devices (W^X).
796fn check_label_is_allowed(context: &SeContext) -> Result<()> {
797 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100798 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100799 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000800 | "staging_data_file" // updated/staged APEX images
801 | "system_file" // immutable dm-verity protected partition
802 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100803 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000804 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900805 }
806}
807
Alan Stokes185fe112023-01-10 16:20:55 +0000808fn check_label_for_partition(partition: &Partition) -> Result<()> {
809 let file = partition.image.as_ref().unwrap().as_ref();
810 check_label_is_allowed(&getfilecon(file)?)
811 .with_context(|| format!("Partition {} invalid", &partition.label))
812}
813
814fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
815 if let Some(f) = kernel {
816 check_label_for_file(f, "kernel")?;
817 }
818 if let Some(f) = initrd {
819 check_label_for_file(f, "initrd")?;
820 }
821 Ok(())
822}
823fn check_label_for_file(file: &File, name: &str) -> Result<()> {
824 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
825}
826
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000827/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
828#[derive(Debug)]
829struct VirtualMachine {
830 instance: Arc<VmInstance>,
831}
832
833impl VirtualMachine {
834 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000835 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000836 }
837}
838
839impl Interface for VirtualMachine {}
840
841impl IVirtualMachine for VirtualMachine {
842 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900843 // Don't check permission. The owner of the VM might have passed this binder object to
844 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000845 Ok(self.instance.cid as i32)
846 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000847
Andrew Walbran6b650662021-09-07 13:13:23 +0000848 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900849 // Don't check permission. The owner of the VM might have passed this binder object to
850 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000851 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000852 }
853
854 fn registerCallback(
855 &self,
856 callback: &Strong<dyn IVirtualMachineCallback>,
857 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900858 // Don't check permission. The owner of the VM might have passed this binder object to
859 // others.
860 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000861 // TODO: Should this give an error if the VM is already dead?
862 self.instance.callbacks.add(callback.clone());
863 Ok(())
864 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000865
Andrew Walbranf8d94112021-09-07 11:45:36 +0000866 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900867 self.instance
868 .start()
869 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
870 .with_log()
871 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000872 }
873
Inseob Kima446f802022-07-11 19:46:37 +0900874 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900875 self.instance
876 .kill()
877 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
878 .with_log()
879 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900880 }
881
Keir Frasercdd4b112022-11-24 14:02:25 +0000882 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900883 self.instance
884 .trim_memory(level)
885 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
886 .with_log()
887 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000888 }
889
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000890 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000891 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900892 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000893 }
Alan Stokes10c47672022-12-13 17:17:08 +0000894 let port = port as u32;
895 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900896 return Err(anyhow!("Can't connect to privileged port {port}"))
897 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000898 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900899 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
900 .context("Failed to connect")
901 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000902 Ok(vsock_stream_to_pfd(stream))
903 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000904}
905
906impl Drop for VirtualMachine {
907 fn drop(&mut self) {
908 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900909 if let Err(e) = self.instance.kill() {
910 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
911 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000912 }
913}
914
915/// A set of Binders to be called back in response to various events on the VM, such as when it
916/// dies.
917#[derive(Debug, Default)]
918pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
919
920impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900921 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100922 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900923 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900924 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100925 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100926 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900927 }
928 }
929 }
930
Inseob Kim14cb8692021-08-31 21:50:39 +0900931 /// Call all registered callbacks to notify that the payload is ready to serve.
932 pub fn notify_payload_ready(&self, cid: Cid) {
933 let callbacks = &*self.0.lock().unwrap();
934 for callback in callbacks {
935 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100936 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900937 }
938 }
939 }
940
Inseob Kim2444af92021-08-31 01:22:50 +0900941 /// Call all registered callbacks to notify that the payload has finished.
942 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
943 let callbacks = &*self.0.lock().unwrap();
944 for callback in callbacks {
945 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100946 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900947 }
948 }
949 }
950
Jooyung Handd0a1732021-11-23 15:26:20 +0900951 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100952 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900953 let callbacks = &*self.0.lock().unwrap();
954 for callback in callbacks {
955 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100956 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900957 }
958 }
959 }
960
Andrew Walbrandae07162021-03-12 17:05:20 +0000961 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000962 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000963 let callbacks = &*self.0.lock().unwrap();
964 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000965 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100966 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000967 }
968 }
969 }
970
971 /// Add a new callback to the set.
972 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
973 self.0.lock().unwrap().push(callback);
974 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000975}
976
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000977/// The mutable state of the VirtualizationService. There should only be one instance of this
978/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800979#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000980struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +0100981 /// The VMs which have been started. When VMs are started a weak reference is added to this
982 /// list while a strong reference is returned to the caller over Binder. Once all copies of
983 /// the Binder client are dropped the weak reference here will become invalid, and will be
984 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +0000985 vms: Vec<Weak<VmInstance>>,
986}
987
988impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000989 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000990 fn vms(&self) -> Vec<Arc<VmInstance>> {
991 // Attempt to upgrade the weak pointers to strong pointers.
992 self.vms.iter().filter_map(Weak::upgrade).collect()
993 }
994
995 /// Add a new VM to the list.
996 fn add_vm(&mut self, vm: Weak<VmInstance>) {
997 // Garbage collect any entries from the stored list which no longer exist.
998 self.vms.retain(|vm| vm.strong_count() > 0);
999
1000 // Actually add the new VM.
1001 self.vms.push(vm);
1002 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001003
Jiyong Park8611a6c2021-07-09 18:17:44 +09001004 /// Get a VM that corresponds to the given cid
1005 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1006 self.vms().into_iter().find(|vm| vm.cid == cid)
1007 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001008}
1009
Andrew Walbran6b650662021-09-07 13:13:23 +00001010/// Gets the `VirtualMachineState` of the given `VmInstance`.
1011fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001012 match &*instance.vm_state.lock().unwrap() {
1013 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1014 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001015 PayloadState::Starting => VirtualMachineState::STARTING,
1016 PayloadState::Started => VirtualMachineState::STARTED,
1017 PayloadState::Ready => VirtualMachineState::READY,
1018 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001019 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001020 },
1021 VmState::Dead => VirtualMachineState::DEAD,
1022 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001023 }
1024}
1025
David Brazdilf50c7a62023-04-19 14:22:42 +00001026/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001027pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1028 file.as_ref()
1029 .try_clone()
1030 .context("Failed to clone File from ParcelFileDescriptor")
1031 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001032}
1033
Andrew Walbrand3a84182021-09-07 14:48:52 +00001034/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001035fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001036 file.as_ref().map(clone_file).transpose()
1037}
1038
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001039/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1040fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1041 // SAFETY: ownership is transferred from stream to f
1042 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1043 ParcelFileDescriptor::new(f)
1044}
1045
Jiyong Parkdcf17412022-02-08 15:07:23 +09001046/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001047fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1048 VersionReq::parse(s)
1049 .with_context(|| format!("Invalid platform version requirement {}", s))
1050 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001051}
1052
Jiyong Parked180932023-02-24 19:55:41 +09001053/// Create the empty ramdump file
1054fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1055 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1056 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1057 // owner) for readout.
1058 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001059 let ramdump = File::create(ramdump_path)
1060 .context("Failed to prepare ramdump file")
1061 .with_log()
1062 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001063 Ok(ramdump)
1064}
1065
Nikita Ioffe5776f082023-02-10 21:38:26 +00001066fn is_protected(config: &VirtualMachineConfig) -> bool {
1067 match config {
1068 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1069 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1070 }
1071}
1072
1073fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1074 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001075 return Err(anyhow!("Can't use gdb with protected VMs"))
1076 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001077 }
1078
1079 match config {
1080 VirtualMachineConfig::RawConfig(_) => Ok(()),
1081 VirtualMachineConfig::AppConfig(config) => {
1082 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001083 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1084 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001085 } else {
1086 Ok(())
1087 }
1088 }
1089 }
1090}
1091
1092fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1093 match config {
1094 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001095 VirtualMachineConfig::AppConfig(config) => {
1096 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1097 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001098 }
1099}
1100
Nikita Ioffe631717e2023-09-05 13:38:07 +01001101fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1102 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1103 if let Some(custom_config) = &config.customConfig {
1104 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1105 return Err(anyhow!("vendor modules feature is disabled"))
1106 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1107 }
1108 }
1109 Ok(())
1110}
1111
1112fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1113 if !cfg!(vendor_modules) {
1114 check_no_vendor_modules(config)?;
1115 }
1116 Ok(())
1117}
1118
Inseob Kim0168b462022-12-27 14:54:35 +09001119fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001120 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001121 fd: Option<&ParcelFileDescriptor>,
1122 tag: String,
1123) -> Result<Option<File>, Status> {
1124 if let Some(fd) = fd {
1125 return Ok(Some(clone_file(fd)?));
1126 }
1127
Jaewan Kim61f86142023-03-28 15:12:52 +09001128 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001129 return Ok(None);
1130 };
Inseob Kim0168b462022-12-27 14:54:35 +09001131
Jiyong Park2227eaa2023-08-04 11:59:18 +09001132 let (raw_read_fd, raw_write_fd) =
1133 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001134
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001135 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001136 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001137 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001138 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1139
1140 std::thread::spawn(move || loop {
1141 let mut buf = vec![];
1142 match reader.read_until(b'\n', &mut buf) {
1143 Ok(0) => {
1144 // EOF
1145 return;
1146 }
1147 Ok(size) => {
1148 if buf[size - 1] == b'\n' {
1149 buf.pop();
1150 }
1151 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1152 }
1153 Err(e) => {
1154 error!("Could not read console pipe: {:?}", e);
1155 return;
1156 }
1157 };
1158 });
1159
1160 Ok(Some(write_fd))
1161}
1162
Jooyung Han35edb8f2021-07-01 16:17:16 +09001163/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1164/// it doesn't require that T implements Clone.
1165enum BorrowedOrOwned<'a, T> {
1166 Borrowed(&'a T),
1167 Owned(T),
1168}
1169
1170impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1171 fn as_ref(&self) -> &T {
1172 match self {
1173 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001174 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001175 }
1176 }
1177}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001178
1179/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1180#[derive(Debug, Default)]
1181struct VirtualMachineService {
1182 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001183 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001184}
1185
1186impl Interface for VirtualMachineService {}
1187
1188impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001189 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1190 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001191 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001192 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001193 vm.update_payload_state(PayloadState::Started)
1194 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001195 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001196
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001197 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1198 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001199 Ok(())
1200 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001201 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001202 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001203 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001204 }
Inseob Kim2444af92021-08-31 01:22:50 +09001205
Inseob Kimc7d28c72021-10-25 14:28:10 +00001206 fn notifyPayloadReady(&self) -> binder::Result<()> {
1207 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001208 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001209 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001210 vm.update_payload_state(PayloadState::Ready)
1211 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001212 vm.callbacks.notify_payload_ready(cid);
1213 Ok(())
1214 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001215 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001216 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001217 }
1218 }
1219
Inseob Kimc7d28c72021-10-25 14:28:10 +00001220 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1221 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001222 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001223 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001224 vm.update_payload_state(PayloadState::Finished)
1225 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001226 vm.callbacks.notify_payload_finished(cid, exit_code);
1227 Ok(())
1228 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001229 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001230 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001231 }
1232 }
1233
Alan Stokes2bead0d2022-09-05 16:58:34 +01001234 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001235 let cid = self.cid;
1236 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001237 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001238 vm.update_payload_state(PayloadState::Finished)
1239 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001240 vm.callbacks.notify_error(cid, error_code, message);
1241 Ok(())
1242 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001243 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001244 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001245 }
1246 }
Alice Wangc2fec932023-02-23 16:24:02 +00001247
1248 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
Alice Wangc206b9b2023-08-28 14:13:51 +00001249 GLOBAL_SERVICE.requestCertificate(csr)
Alice Wangc2fec932023-02-23 16:24:02 +00001250 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001251}
1252
1253impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001254 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001255 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001256 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001257 BinderFeatures::default(),
1258 )
1259 }
1260}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001261
1262#[cfg(test)]
1263mod tests {
1264 use super::*;
1265
1266 #[test]
1267 fn test_is_allowed_label_for_partition() -> Result<()> {
1268 let expected_results = vec![
1269 ("u:object_r:system_file:s0", true),
1270 ("u:object_r:apk_data_file:s0", true),
1271 ("u:object_r:app_data_file:s0", false),
1272 ("u:object_r:app_data_file:s0:c512,c768", false),
1273 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1274 ("invalid", false),
1275 ("user:role:apk_data_file:severity:categories", true),
1276 ("user:role:apk_data_file:severity:categories:extraneous", false),
1277 ];
1278
1279 for (label, expected_valid) in expected_results {
1280 let context = SeContext::new(label)?;
1281 let result = check_label_is_allowed(&context);
1282 if expected_valid {
1283 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1284 } else if result.is_ok() {
1285 bail!("Expected label {} to be disallowed", label);
1286 }
1287 }
1288 Ok(())
1289 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001290
1291 #[test]
1292 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1293 let apk = tempfile::tempfile().unwrap();
1294 let idsig = tempfile::tempfile().unwrap();
1295
1296 let ret = create_or_update_idsig_file(
1297 &ParcelFileDescriptor::new(apk),
1298 &ParcelFileDescriptor::new(idsig),
1299 );
1300 assert!(ret.is_err(), "should fail");
1301 Ok(())
1302 }
1303
1304 #[test]
1305 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1306 let tmp_dir = tempfile::TempDir::new().unwrap();
1307 let apk = File::open(tmp_dir.path()).unwrap();
1308 let idsig = tempfile::tempfile().unwrap();
1309
1310 let ret = create_or_update_idsig_file(
1311 &ParcelFileDescriptor::new(apk),
1312 &ParcelFileDescriptor::new(idsig),
1313 );
1314 assert!(ret.is_err(), "should fail");
1315 Ok(())
1316 }
1317
1318 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1319 /// on ext4 filesystem is passed.
1320 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1321 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1322 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1323 #[test]
1324 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1325 // APEXes are backed by the ext4.
1326 let apk = File::open("/apex/com.android.virt/").unwrap();
1327 let idsig = tempfile::tempfile().unwrap();
1328
1329 let ret = create_or_update_idsig_file(
1330 &ParcelFileDescriptor::new(apk),
1331 &ParcelFileDescriptor::new(idsig),
1332 );
1333 assert!(ret.is_err(), "should fail");
1334 Ok(())
1335 }
Jiyong Park8d192952023-06-26 14:29:51 +09001336
1337 #[test]
1338 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1339 use std::io::Seek;
1340
1341 // Pick any APK
1342 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1343 let mut idsig = tempfile::tempfile().unwrap();
1344
1345 create_or_update_idsig_file(
1346 &ParcelFileDescriptor::new(apk.try_clone()?),
1347 &ParcelFileDescriptor::new(idsig.try_clone()?),
1348 )?;
1349 let modified_orig = idsig.metadata()?.modified()?;
1350 apk.rewind()?;
1351 idsig.rewind()?;
1352
1353 // Call the function again
1354 create_or_update_idsig_file(
1355 &ParcelFileDescriptor::new(apk.try_clone()?),
1356 &ParcelFileDescriptor::new(idsig.try_clone()?),
1357 )?;
1358 let modified_new = idsig.metadata()?.modified()?;
1359 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1360 Ok(())
1361 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001362
1363 #[test]
1364 fn test_append_kernel_param_first_param() {
1365 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1366 append_kernel_param("foo=1", &mut vm_config);
1367 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1368 }
1369
1370 #[test]
1371 fn test_append_kernel_param() {
1372 let mut vm_config =
1373 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1374 append_kernel_param("bar=42", &mut vm_config);
1375 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1376 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001377}