blob: b54b37b0b910fd7383b47eecb79c1fc023ef6a1d [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 Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Mu-Le Leeb2d5a312024-06-05 10:52:47 +080020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090021use crate::debug_config::DebugConfig;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
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::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Jeongik Chac181be72024-03-27 00:18:30 +090035 InputDevice::InputDevice,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010036 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000037 IVirtualMachineCallback::IVirtualMachineCallback,
38 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090039 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090041 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010044 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090047};
Inseob Kimecde8c02024-09-03 13:11:08 +090048use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090050use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000051 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052};
Shikha Panware45e9422024-02-28 21:18:10 +000053use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
55use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
56 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
57 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
58 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
59 SessionInitiationInfo::SessionInitiationInfo,
60};
Alan Stokes25f69362023-03-06 16:51:54 +000061use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090062use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090063use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010064use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000065 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
66 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090067 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000068};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000069use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000071use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090072use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090073use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000074use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000075use rustutils::system_properties;
Jiyong Parkba3099e2024-08-20 18:19:12 +090076use safe_ownedfd::take_fd_ownership;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim6ef80972023-07-20 17:23:36 +090079use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkba3099e2024-08-20 18:19:12 +090088use std::os::unix::io::{AsRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
David Brazdilafc9a9e2023-01-12 16:08:10 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Jooyung Han95884632021-07-06 22:27:54 +0900102/// The size of zero.img.
103/// Gaps in composite disk images are filled with a shared zero.img.
104const ZERO_FILLER_SIZE: u64 = 4096;
105
David Brazdilf50c7a62023-04-19 14:22:42 +0000106/// Magic string for the instance image
107const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
108
109/// Version of the instance image format
110const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
111
Alan Stokes0d1ef782022-09-27 13:46:35 +0100112const MICRODROID_OS_NAME: &str = "microdroid";
113
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000114const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000115 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000116
David Brazdilf50c7a62023-04-19 14:22:42 +0000117const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
118
119/// crosvm requires all partitions to be a multiple of 4KiB.
120const PARTITION_GRANULARITY_BYTES: u64 = 4096;
121
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000122const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
123
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100124pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
125 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900126 if cfg!(early) {
127 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
128 } else {
129 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
130 .expect("Could not connect to VirtualizationServiceInternal")
131 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100132 });
133static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
134 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000135
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000136fn create_or_update_idsig_file(
137 input_fd: &ParcelFileDescriptor,
138 idsig_fd: &ParcelFileDescriptor,
139) -> Result<()> {
140 let mut input = clone_file(input_fd)?;
141 let metadata = input.metadata().context("failed to get input metadata")?;
142 if !metadata.is_file() {
143 bail!("input is not a regular file");
144 }
Alan Stokes25f69362023-03-06 16:51:54 +0000145 let mut sig =
146 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
147 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000148
149 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900150
151 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
152 // if the idsig file already has the same APK digest.
153 if output.metadata()?.len() > 0 {
154 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
155 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
156 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
157 return Ok(());
158 }
159 }
160 // if we fail to read v4signature from output, that's fine. User can pass a random file.
161 // We will anyway overwrite the file to the v4signature generated from input_fd.
162 }
163
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000164 output
165 .seek(SeekFrom::Start(0))
166 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000167 output.set_len(0).context("failed to set_len on the idsig output")?;
168 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000169 Ok(())
170}
171
Alan Stokes25f69362023-03-06 16:51:54 +0000172fn get_current_sdk() -> Result<u32> {
173 let current_sdk = system_properties::read("ro.build.version.sdk")?;
174 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
175 current_sdk.parse().context("Malformed SDK version")
176}
177
David Brazdil4b4c5102022-12-19 22:56:20 +0000178pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
179 for dir_entry in read_dir(path)? {
180 remove_file(dir_entry?.path())?;
181 }
182 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100183}
184
David Brazdil528e0472022-10-10 15:06:02 +0100185/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000186#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000187pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900188 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000189}
190
Shikha Panward8e35422021-10-11 13:51:27 +0000191impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000192 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000193 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
194 let state = &mut *self.state.lock().unwrap();
195 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000197 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000198 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
199 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000200 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000201 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000202 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000203 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
204 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000205 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000206 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000207 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000208 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000209 .or(Err(StatusCode::UNKNOWN_ERROR))?;
210 }
211 Ok(())
212 }
213}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000214impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000215 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
216 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000217 ///
218 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000220 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000221 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900222 console_out_fd: Option<&ParcelFileDescriptor>,
223 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000224 log_fd: Option<&ParcelFileDescriptor>,
225 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000226 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900227 let ret = self.create_vm_internal(
228 config,
229 console_out_fd,
230 console_in_fd,
231 log_fd,
232 &mut is_protected,
233 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000234 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000235 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000236 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000237
Shikha Panwar61a74b52024-02-16 13:17:01 +0000238 /// Allocate a new instance_id to the VM
239 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000240 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000241 GLOBAL_SERVICE.allocateInstanceId()
242 }
243
Andrew Walbrandff3b942021-06-09 15:20:36 +0000244 /// Initialise an empty partition image of the given size to be used as a writable partition.
245 fn initializeWritablePartition(
246 &self,
247 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000248 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900249 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900251 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900252 let size_bytes = size_bytes
253 .try_into()
254 .with_context(|| format!("Invalid size: {}", size_bytes))
255 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000256 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000257 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000258 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000259 image
260 .seek(SeekFrom::Start(0))
261 .context("failed to move cursor to start")
262 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900263 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700264 // Set the file length. In most filesystems, this will not allocate any physical disk
265 // space, it will only change the logical size.
266 image
267 .set_len(size_bytes)
268 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900269 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000270
271 match partition_type {
272 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700273 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
274 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000275 _ => Err(Error::new(
276 ErrorKind::Unsupported,
277 format!("Unsupported partition type {:?}", partition_type),
278 )),
279 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900280 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
281 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000282
283 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000284 }
285
Jiyong Park0a248432021-08-20 23:32:39 +0900286 /// Creates or update the idsig file by digesting the input APK file.
287 fn createOrUpdateIdsigFile(
288 &self,
289 input_fd: &ParcelFileDescriptor,
290 idsig_fd: &ParcelFileDescriptor,
291 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900292 check_manage_access()?;
293
Jiyong Park2227eaa2023-08-04 11:59:18 +0900294 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900295 Ok(())
296 }
297
Andrew Walbran320b5602021-03-04 16:11:12 +0000298 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
299 /// and as such is only permitted from the shell user.
300 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000301 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000302 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000303 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900304
305 /// Get a list of assignable device types.
306 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
307 // Delegate to the global service, including checking the permission.
308 GLOBAL_SERVICE.getAssignableDevices()
309 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100310
Inseob Kim46257382024-01-03 15:41:22 +0900311 /// Get a list of supported OSes.
312 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
313 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
314 }
315
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100316 /// Returns whether given feature is enabled
317 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
318 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000319 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100320 }
Alice Wange64dd182024-01-17 15:57:55 +0000321
322 fn enableTestAttestation(&self) -> binder::Result<()> {
323 GLOBAL_SERVICE.enableTestAttestation()
324 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000325
326 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
327 check_manage_access()?;
328 GLOBAL_SERVICE.isRemoteAttestationSupported()
329 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000330
331 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
332 // The response is specific to Microdroid. Updatable VMs are only possible if device
333 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
334 // this, however other guest OSes may do things differently.
335 check_manage_access()?;
336 Ok(is_secretkeeper_supported())
337 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000338
Shikha Panwar07d701c2024-03-28 14:43:52 +0000339 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
340 check_manage_access()?;
341 GLOBAL_SERVICE.removeVmInstance(instance_id)
342 }
343
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000344 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
345 check_manage_access()?;
346 GLOBAL_SERVICE.claimVmInstance(instance_id)
347 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000348}
349
Inseob Kimecde8c02024-09-03 13:11:08 +0900350/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
351#[derive(Debug, Default)]
352struct EarlyVmContext {
353 /// The unique CID assigned to the VM for vsock communication.
354 cid: Cid,
355 /// Temporary directory for this VM instance.
356 temp_dir: PathBuf,
357}
358
359impl EarlyVmContext {
360 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
361 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
362 // should trust clients, e.g. they won't run two VMs at the same time
363 let _ = remove_dir_all(&temp_dir);
364 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
365
366 Ok(Self { cid, temp_dir })
367 }
368}
369
370impl Interface for EarlyVmContext {}
371
372impl Drop for EarlyVmContext {
373 fn drop(&mut self) {
374 if let Err(e) = remove_dir_all(&self.temp_dir) {
375 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
376 }
377 }
378}
379
380impl IGlobalVmContext for EarlyVmContext {
381 fn getCid(&self) -> binder::Result<i32> {
382 Ok(self.cid as i32)
383 }
384
385 fn getTemporaryDirectory(&self) -> binder::Result<String> {
386 Ok(self.temp_dir.to_string_lossy().to_string())
387 }
388
389 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
390 Err(Status::new_exception_str(
391 ExceptionCode::UNSUPPORTED_OPERATION,
392 Some("Early VM doesn't support setting host console name"),
393 ))
394 }
395}
396
397fn find_partition(path: &Path) -> binder::Result<String> {
398 match path.components().nth(1) {
399 Some(std::path::Component::Normal(partition)) => {
400 Ok(partition.to_string_lossy().into_owned())
401 }
402 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
403 .or_service_specific_exception(-1),
404 }
405}
406
Jiyong Park8611a6c2021-07-09 18:17:44 +0900407impl VirtualizationService {
408 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000409 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900410 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000411
Inseob Kimecde8c02024-09-03 13:11:08 +0900412 fn create_early_vm_context(
413 &self,
414 config: &VirtualMachineConfig,
415 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
416 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
417 let link = fs::read_link(&calling_exe_path)
418 .context(format!("can't read_link '{calling_exe_path}'"))
419 .or_service_specific_exception(-1)?;
420 let partition = find_partition(&link)?;
421
422 let name = match config {
423 VirtualMachineConfig::RawConfig(config) => &config.name,
424 VirtualMachineConfig::AppConfig(config) => &config.name,
425 };
426 let early_vm =
427 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
428 if Path::new(&early_vm.path) != link {
429 return Err(anyhow!(
430 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
431 &early_vm.path,
432 link.display()
433 ))
434 .or_service_specific_exception(-1);
435 }
436
437 let cid = early_vm.cid as Cid;
438 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
439
440 let context = EarlyVmContext::new(cid, temp_dir.clone())
441 .context(format!("Can't create early vm contexts for {cid}"))
442 .or_service_specific_exception(-1)?;
443 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
444
445 // Start VM service listening for connections from the new CID on port=CID.
446 let port = cid;
447 let vm_server = RpcServer::new_vsock(service, cid, port)
448 .context(format!("Could not start RpcServer on port {port}"))
449 .or_service_specific_exception(-1)?;
450 vm_server.start();
451 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
452 }
453
David Brazdil209074a2023-01-12 16:44:51 +0000454 fn create_vm_context(
455 &self,
456 requester_debug_pid: pid_t,
457 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000458 const NUM_ATTEMPTS: usize = 5;
459
460 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000461 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000462 let cid = vm_context.getCid()? as Cid;
463 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000464 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
465
466 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000467 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000468 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000469 Ok(vm_server) => {
470 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000471 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000472 }
473 Err(err) => {
474 warn!("Could not start RpcServer on port {}: {}", port, err);
475 }
476 }
477 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900478 Err(anyhow!("Too many attempts to create VM context failed"))
479 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000480 }
481
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000482 fn create_vm_internal(
483 &self,
484 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900485 console_out_fd: Option<&ParcelFileDescriptor>,
486 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000487 log_fd: Option<&ParcelFileDescriptor>,
488 is_protected: &mut bool,
489 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000490 let requester_uid = get_calling_uid();
491 let requester_debug_pid = get_calling_pid();
492
Nikita Ioffe631717e2023-09-05 13:38:07 +0100493 check_config_features(config)?;
494
Inseob Kimecde8c02024-09-03 13:11:08 +0900495 if cfg!(early) {
496 check_config_allowed_for_early_vms(config)?;
497 }
498
David Brazdil209074a2023-01-12 16:44:51 +0000499 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900500 let (vm_context, cid, temporary_directory) = if cfg!(early) {
501 self.create_early_vm_context(config)?
502 } else {
503 self.create_vm_context(requester_debug_pid)?
504 };
Inseob Kim1119d702022-05-02 18:01:58 +0900505
Alan Stokesfda70842023-12-20 17:50:14 +0000506 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100507 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900508 }
509
Nikita Ioffe5776f082023-02-10 21:38:26 +0000510 let gdb_port = extract_gdb_port(config);
511
512 // Additional permission checks if caller request gdb.
513 if gdb_port.is_some() {
514 check_gdb_allowed(config)?;
515 }
516
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000517 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900518
Jaewan Kimf3143242024-03-15 06:56:31 +0000519 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000520 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900521 Some(prepare_ramdump_file(&temporary_directory)?)
522 } else {
523 None
524 };
525
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000526 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900527 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100528 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900529 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100530 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000531
532 // Counter to generate unique IDs for temporary image files.
533 let mut next_temporary_image_id = 0;
534 // Files which are referred to from composite images. These must be mapped to the crosvm
535 // child process, and not closed before it is started.
536 let mut indirect_files = vec![];
537
Alan Stokes7bc146c2022-10-20 17:10:32 +0100538 let (is_app_config, config) = match config {
539 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
540 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900541 let config = load_app_config(config, &debug_config, &temporary_directory)
542 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900543 *is_protected = config.protectedVm;
544 let message = format!("Failed to load app config: {:?}", e);
545 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900546 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900547 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100548 (true, BorrowedOrOwned::Owned(config))
549 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000550 };
551 let config = config.as_ref();
552 *is_protected = config.protectedVm;
553
554 // Check if partition images are labeled incorrectly. This is to prevent random images
555 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100556 // being loaded in a pVM. This applies to everything but the instance image in the raw
557 // config, and everything but the non-executable, generated partitions in the app
558 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000559 config
560 .disks
561 .iter()
562 .flat_map(|disk| disk.partitions.iter())
563 .filter(|partition| {
564 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100565 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000566 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000567 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000568 }
569 })
570 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900571 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000572
Inseob Kimff48a7c2024-02-26 22:07:21 +0900573 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
574 // have unstable interfaces.
575 // TODO(b/316431494): remove once Treble interfaces are stabilized.
576 check_partitions_for_files(config).or_service_specific_exception(-1)?;
577
Alan Stokes185fe112023-01-10 16:20:55 +0000578 let kernel = maybe_clone_file(&config.kernel)?;
579 let initrd = maybe_clone_file(&config.initrd)?;
580
Alan Stokes185fe112023-01-10 16:20:55 +0000581 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000582 // In a protected VM, we require custom kernels to come from a trusted source
583 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900584 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000585 // Fail fast with a meaningful error message in case device doesn't support pVMs.
586 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000587 }
588
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000589 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900590 write_zero_filler(&zero_filler_path)
591 .context("Failed to make composite image")
592 .with_log()
593 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000594
595 // Assemble disk images if needed.
596 let disks = config
597 .disks
598 .iter()
599 .map(|disk| {
600 assemble_disk_image(
601 disk,
602 &zero_filler_path,
603 &temporary_directory,
604 &mut next_temporary_image_id,
605 &mut indirect_files,
606 )
607 })
608 .collect::<Result<Vec<DiskFile>, _>>()?;
609
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000610 let (cpus, host_cpu_topology) = match config.cpuTopology {
611 CpuTopology::MATCH_HOST => (None, true),
612 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
613 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900614 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
615 .with_log()
616 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000617 }
618 };
619
David Brazdil2dfefd12023-11-17 14:07:36 +0000620 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900621 let mut set = HashSet::new();
622 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900623 let path = canonicalize(device)
624 .with_context(|| format!("can't canonicalize {device}"))
625 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900626 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900627 return Err(anyhow!("duplicated device {device}"))
628 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900629 }
630 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000631 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000632 let dtbo_file = File::from(
633 GLOBAL_SERVICE
634 .getDtboFile()?
635 .as_ref()
636 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900637 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000638 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
639 );
640 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900641 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000642 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900643 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900644 let display_config = if cfg!(paravirtualized_devices) {
645 config
646 .displayConfig
647 .as_ref()
648 .map(DisplayConfig::new)
649 .transpose()
650 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
651 } else {
652 None
653 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700654 let gpu_config = if cfg!(paravirtualized_devices) {
655 config
656 .gpuConfig
657 .as_ref()
658 .map(GpuConfig::new)
659 .transpose()
660 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
661 } else {
662 None
663 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900664
Jeongik Chac181be72024-03-27 00:18:30 +0900665 let input_device_options = if cfg!(paravirtualized_devices) {
666 config
667 .inputDevices
668 .iter()
669 .map(to_input_device_option_from)
670 .collect::<Result<Vec<InputDeviceOption>, _>>()
671 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
672 } else {
673 vec![]
674 };
675
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900676 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900677 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900678 if *is_protected {
679 return Err(anyhow!("Network feature is not supported for pVM yet"))
680 .with_log()
681 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
682 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900683 Some(File::from(
684 GLOBAL_SERVICE
685 .createTapInterface(&get_this_pid().to_string())?
686 .as_ref()
687 .try_clone()
688 .context("Failed to get TAP interface from ParcelFileDescriptor")
689 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
690 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900691 } else {
692 None
693 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800694
695 let audio_config = if cfg!(paravirtualized_devices) {
696 config.audioConfig.as_ref().map(AudioConfig::new)
697 } else {
698 None
699 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900700
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000701 // Actually start the VM.
702 let crosvm_config = CrosvmConfig {
703 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000704 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000705 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000706 kernel,
707 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000708 disks,
709 params: config.params.to_owned(),
710 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900711 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700712 memory_mib: config
713 .memoryMib
714 .try_into()
715 .ok()
716 .and_then(NonZeroU32::new)
717 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000718 cpus,
719 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900720 console_out_fd,
721 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000722 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900723 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000724 indirect_files,
725 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900726 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000727 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900728 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000729 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000730 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900731 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900732 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000733 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900734 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800735 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000736 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700737 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800738 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900739 no_balloon: config.noBalloon,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000740 };
741 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100742 VmInstance::new(
743 crosvm_config,
744 temporary_directory,
745 requester_uid,
746 requester_debug_pid,
747 vm_context,
748 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900749 .with_context(|| format!("Failed to create VM with config {:?}", config))
750 .with_log()
751 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000752 );
753 state.add_vm(Arc::downgrade(&instance));
754 Ok(VirtualMachine::create(instance))
755 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900756}
757
Alan Stokesfda70842023-12-20 17:50:14 +0000758/// Returns whether a VM config represents a "custom" virtual machine, which requires the
759/// USE_CUSTOM_VIRTUAL_MACHINE.
760fn is_custom_config(config: &VirtualMachineConfig) -> bool {
761 match config {
762 // Any raw (non-Microdroid) VM is considered custom.
763 VirtualMachineConfig::RawConfig(_) => true,
764 VirtualMachineConfig::AppConfig(config) => {
765 // Some features are reserved for platform apps only, even when using
766 // VirtualMachineAppConfig. Almost all of these features are grouped in the
767 // CustomConfig struct:
768 // - controlling CPUs;
769 // - gdbPort is set, meaning that crosvm will start a gdb server;
770 // - using anything other than the default kernel;
771 // - specifying devices to be assigned.
772 if config.customConfig.is_some() {
773 true
774 } else {
775 // Additional custom features not included in CustomConfig:
776 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000777 // - specifying extra APKs;
778 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900779 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000780 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900781 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
782 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000783 }
784 }
785 }
786}
787
Seungjae Yoo14e60182024-02-21 13:28:31 +0900788fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
789 let VirtualMachineConfig::AppConfig(config) = config else {
790 return Ok(None);
791 };
792 let Some(custom_config) = &config.customConfig else {
793 return Ok(None);
794 };
795 let Some(file) = custom_config.vendorImage.as_ref() else {
796 return Ok(None);
797 };
798
799 let file = clone_file(file)?;
800 let size =
801 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
802 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
803 .context("Failed to get vbmeta from microdroid-vendor.img")?;
804
805 for descriptor in vbmeta.descriptors()?.iter() {
806 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
807 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
808 return Ok(Some(root_digest.as_bytes().to_vec()));
809 }
810 }
811 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
812}
813
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000814fn maybe_create_device_tree_overlay(
815 config: &VirtualMachineConfig,
816 temporary_directory: &Path,
817) -> binder::Result<Option<File>> {
818 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
819 // (e.g. instance-id)
820 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
821 let host_ref_dt = if host_ref_dt.exists()
822 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
823 {
824 Some(host_ref_dt)
825 } else {
826 warn!("VM reference DT doesn't exist in host DT");
827 None
828 };
829
830 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
831 .context("Failed to extract vendor hashtree digest")
832 .or_service_specific_exception(-1)?;
833
834 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
835 info!(
836 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
837 match the trusted digest in the pvmfw config, causing the VM to fail to start."
838 );
839 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
840 } else {
841 vec![]
842 };
843
844 let instance_id;
845 let mut untrusted_props = Vec::with_capacity(2);
846 if cfg!(llpvm_changes) {
847 instance_id = extract_instance_id(config);
848 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
849 let want_updatable = extract_want_updatable(config);
850 if want_updatable && is_secretkeeper_supported() {
851 // Let guest know that it can defer rollback protection to Secretkeeper by setting
852 // an empty property in untrusted node in DT. This enables Updatable VMs.
853 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
854 }
855 }
856
857 let device_tree_overlay = if host_ref_dt.is_some()
858 || !untrusted_props.is_empty()
859 || !trusted_props.is_empty()
860 {
861 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
862 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
863 let fdt =
864 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
865 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
866 .or_service_specific_exception(-1)?;
867 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
868 Some(File::open(dt_output).or_service_specific_exception(-1)?)
869 } else {
870 None
871 };
872 Ok(device_tree_overlay)
873}
874
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000875fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900876 let file = OpenOptions::new()
877 .create_new(true)
878 .read(true)
879 .write(true)
880 .open(zero_filler_path)
881 .with_context(|| "Failed to create zero.img")?;
882 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000883 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900884}
885
David Brazdilf50c7a62023-04-19 14:22:42 +0000886fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
887 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
888 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
889 part.flush()
890}
891
892fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
893 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
894 part.flush()
895}
896
897fn round_up(input: u64, granularity: u64) -> u64 {
898 if granularity == 0 {
899 return input;
900 }
901 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
902 let result = input.checked_add(granularity - 1).unwrap_or(input);
903 (result / granularity) * granularity
904}
905
Jeongik Chac181be72024-03-27 00:18:30 +0900906fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
907 Ok(match input_device {
908 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
909 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
910 height: u32::try_from(single_touch.height)?,
911 width: u32::try_from(single_touch.width)?,
912 name: if !single_touch.name.is_empty() {
913 Some(single_touch.name.clone())
914 } else {
915 None
916 },
917 },
918 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
919 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
920 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900921 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
922 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
923 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900924 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
925 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
926 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900927 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
928 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
929 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900930 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
931 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
932 height: u32::try_from(trackpad.height)?,
933 width: u32::try_from(trackpad.width)?,
934 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
935 },
Jeongik Cha10494912024-07-16 11:19:50 +0900936 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
937 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
938 height: u32::try_from(multi_touch.height)?,
939 width: u32::try_from(multi_touch.width)?,
940 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
941 },
Jeongik Chac181be72024-03-27 00:18:30 +0900942 })
943}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000944/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
945///
946/// This may involve assembling a composite disk from a set of partition images.
947fn assemble_disk_image(
948 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900949 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000950 temporary_directory: &Path,
951 next_temporary_image_id: &mut u64,
952 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000953) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000954 let image = if !disk.partitions.is_empty() {
955 if disk.image.is_some() {
956 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900957 return Err(anyhow!("DiskImage contains both image and partitions"))
958 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000959 }
960
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000961 let composite_image_filenames =
962 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
963 let (image, partition_files) = make_composite_image(
964 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900965 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000966 &composite_image_filenames.composite,
967 &composite_image_filenames.header,
968 &composite_image_filenames.footer,
969 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900970 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
971 .with_log()
972 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000973
974 // Pass the file descriptors for the various partition files to crosvm when it
975 // is run.
976 indirect_files.extend(partition_files);
977
978 image
979 } else if let Some(image) = &disk.image {
980 clone_file(image)?
981 } else {
982 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900983 return Err(anyhow!("DiskImage didn't contain image or partitions."))
984 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000985 };
986
987 Ok(DiskFile { image, writable: disk.writable })
988}
989
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100990fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
991 if let Some(ref mut params) = vm_config.params {
992 params.push(' ');
993 params.push_str(param)
994 } else {
995 vm_config.params = Some(param.to_owned())
996 }
997}
998
Inseob Kim46257382024-01-03 15:41:22 +0900999fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1000 if config.extension()?.to_str()? != "json" {
1001 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001002 }
Inseob Kim46257382024-01-03 15:41:22 +09001003
1004 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1005}
1006
1007fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1008 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1009 let os_names =
1010 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1011
1012 Ok(os_names)
1013}
1014
1015fn get_supported_os_names() -> Result<HashSet<String>> {
1016 if !cfg!(vendor_modules) {
1017 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1018 }
1019
1020 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1021}
1022
1023fn is_valid_os(os_name: &str) -> bool {
1024 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001025}
1026
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001027fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1028 if !cfg!(vendor_modules) {
1029 return false;
1030 }
1031 match config {
1032 VirtualMachineConfig::RawConfig(_) => false,
1033 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1034 }
1035}
1036
Jooyung Han21e9b922021-06-26 04:14:16 +09001037fn load_app_config(
1038 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001039 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001040 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001041) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001042 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1043 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001044 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001045
Shikha Panwar22e70452022-10-10 18:32:55 +00001046 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1047 Some(clone_file(file)?)
1048 } else {
1049 None
1050 };
1051
Alan Stokesfda70842023-12-20 17:50:14 +00001052 let vm_payload_config;
1053 let extra_apk_files: Vec<_>;
1054 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001055 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001056 vm_payload_config =
1057 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1058 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1059 extra_apk_files = vm_payload_config
1060 .extra_apks
1061 .iter()
1062 .enumerate()
1063 .map(|(i, apk)| {
1064 File::open(PathBuf::from(&apk.path))
1065 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1066 })
1067 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001068 }
Alan Stokesfda70842023-12-20 17:50:14 +00001069 Payload::PayloadConfig(payload_config) => {
1070 vm_payload_config = create_vm_payload_config(payload_config)?;
1071 extra_apk_files =
1072 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1073 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001074 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001075
Inseob Kim89b24592024-02-23 18:59:43 +09001076 let payload_config_os = vm_payload_config.os.name.as_str();
1077 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1078 bail!("'os' in payload config is deprecated");
1079 }
1080
Inseob Kim172f9eb2023-11-06 17:02:08 +09001081 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001082 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001083 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001084 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001085 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001086
1087 // It is safe to construct a filename based on the os_name because we've already checked that it
1088 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001089 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1090 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001091 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001092
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001093 if let Some(custom_config) = &config.customConfig {
1094 if let Some(file) = custom_config.customKernelImage.as_ref() {
1095 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1096 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001097 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001098
1099 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001100 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
1101 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001102 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001103
Chris Wailes6177c662024-05-09 14:37:44 -07001104 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001105 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001106
1107 for param in custom_config.extraKernelCmdlineParams.iter() {
1108 append_kernel_param(param, &mut vm_config);
1109 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001110 }
1111
Andrew Walbrancc045902021-07-27 16:06:17 +00001112 if config.memoryMib > 0 {
1113 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001114 }
1115
Chris Wailes6177c662024-05-09 14:37:44 -07001116 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001117 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001118 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001119 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001120 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001121
Shikha Panwar22e70452022-10-10 18:32:55 +00001122 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001123 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001124
1125 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1126 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001127 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001128 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001129 temporary_directory,
1130 apk_file,
1131 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001132 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001133 &vm_payload_config,
1134 &mut vm_config,
1135 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001136
Andrew Walbrancc0db522021-07-12 17:03:42 +00001137 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001138}
1139
Inseob Kimff48a7c2024-02-26 22:07:21 +09001140fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1141 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1142 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1143
1144 // microdroid vendor image is OK
1145 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1146 {
1147 return Ok(());
1148 }
1149
1150 if link.starts_with("/vendor") || link.starts_with("/odm") {
1151 bail!("vendor or odm file {} can't be used for VM", link.display());
1152 }
1153
1154 Ok(())
1155}
1156
1157fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1158 config
1159 .disks
1160 .iter()
1161 .flat_map(|disk| disk.partitions.iter())
1162 .filter_map(|partition| partition.image.as_ref())
1163 .try_for_each(check_partition_for_file)?;
1164
1165 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1166 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1167 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1168
1169 Ok(())
1170}
1171
Alan Stokes0d1ef782022-09-27 13:46:35 +01001172fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1173 let mut apk_zip = ZipArchive::new(apk_file)?;
1174 let config_file = apk_zip.by_name(config_path)?;
1175 Ok(serde_json::from_reader(config_file)?)
1176}
1177
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001178fn create_vm_payload_config(
1179 payload_config: &VirtualMachinePayloadConfig,
1180) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001181 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1182 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1183 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001184
1185 let payload_binary_name = &payload_config.payloadBinaryName;
1186 if payload_binary_name.contains('/') {
1187 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1188 }
1189
1190 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001191
1192 // The VM only cares about how many there are, these names are actually ignored.
1193 let extra_apk_count = payload_config.extraApks.len();
1194 let extra_apks =
1195 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1196
Inseob Kim89b24592024-02-23 18:59:43 +09001197 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001198}
1199
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001200/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001201fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001202 temporary_directory: &Path,
1203 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001204) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001205 let id = *next_temporary_image_id;
1206 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001207 CompositeImageFilenames {
1208 composite: temporary_directory.join(format!("composite-{}.img", id)),
1209 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1210 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1211 }
1212}
1213
1214/// Filenames for a composite disk image, including header and footer partitions.
1215#[derive(Clone, Debug, Eq, PartialEq)]
1216struct CompositeImageFilenames {
1217 /// The composite disk image itself.
1218 composite: PathBuf,
1219 /// The header partition image.
1220 header: PathBuf,
1221 /// The footer partition image.
1222 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001223}
1224
Jiyong Park753553b2021-07-12 21:21:09 +09001225/// Checks whether the caller has a specific permission
1226fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001227 if cfg!(early) {
1228 // Skip permission check for early VMs, in favor of SELinux
1229 return Ok(());
1230 }
David Brazdil1f530702022-10-03 12:18:10 +01001231 let calling_pid = get_calling_pid();
1232 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001233 // Root can do anything
1234 if calling_uid == 0 {
1235 return Ok(());
1236 }
1237 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001238 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001239 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001240 Ok(())
1241 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001242 Err(anyhow!("does not have the {} permission", perm))
1243 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001244 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001245}
1246
Jiyong Park753553b2021-07-12 21:21:09 +09001247/// Check whether the caller of the current Binder method is allowed to manage VMs
1248fn check_manage_access() -> binder::Result<()> {
1249 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1250}
1251
Inseob Kim1119d702022-05-02 18:01:58 +09001252/// Check whether the caller of the current Binder method is allowed to create custom VMs
1253fn check_use_custom_virtual_machine() -> binder::Result<()> {
1254 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1255}
1256
Alan Stokes185fe112023-01-10 16:20:55 +00001257/// Return whether a partition is exempt from selinux label checks, because we know that it does
1258/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001259fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001260 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001261 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001262 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001263 || label == "microdroid-apk-idsig"
1264 || label == "payload-metadata"
1265 || label.starts_with("extra-idsig-")
1266}
1267
Alice Wangc206b9b2023-08-28 14:13:51 +00001268/// Returns whether a partition with the given label is safe for a raw config VM.
1269fn is_safe_raw_partition(label: &str) -> bool {
1270 label == "vm-instance"
1271}
1272
Alan Stokes185fe112023-01-10 16:20:55 +00001273/// Check that a file SELinux label is acceptable.
1274///
1275/// We only want to allow code in a VM to be sourced from places that apps, and the
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001276/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001277///
1278/// Note that sepolicy must also grant read access for these types to both virtualization
1279/// service and crosvm.
1280///
1281/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1282/// user devices (W^X).
1283fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1284 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001285 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001286 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001287 | "staging_data_file" // updated/staged APEX images
1288 | "system_file" // immutable dm-verity protected partition
1289 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001290 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001291 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001292 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001293 }
1294}
1295
Alan Stokes185fe112023-01-10 16:20:55 +00001296fn check_label_for_partition(partition: &Partition) -> Result<()> {
1297 let file = partition.image.as_ref().unwrap().as_ref();
1298 check_label_is_allowed(&getfilecon(file)?)
1299 .with_context(|| format!("Partition {} invalid", &partition.label))
1300}
1301
1302fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1303 if let Some(f) = kernel {
1304 check_label_for_file(f, "kernel")?;
1305 }
1306 if let Some(f) = initrd {
1307 check_label_for_file(f, "initrd")?;
1308 }
1309 Ok(())
1310}
1311fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1312 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1313}
1314
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001315/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1316#[derive(Debug)]
1317struct VirtualMachine {
1318 instance: Arc<VmInstance>,
1319}
1320
1321impl VirtualMachine {
1322 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001323 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001324 }
1325}
1326
1327impl Interface for VirtualMachine {}
1328
1329impl IVirtualMachine for VirtualMachine {
1330 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001331 // Don't check permission. The owner of the VM might have passed this binder object to
1332 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001333 Ok(self.instance.cid as i32)
1334 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001335
Andrew Walbran6b650662021-09-07 13:13:23 +00001336 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001337 // Don't check permission. The owner of the VM might have passed this binder object to
1338 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001339 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001340 }
1341
1342 fn registerCallback(
1343 &self,
1344 callback: &Strong<dyn IVirtualMachineCallback>,
1345 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001346 // Don't check permission. The owner of the VM might have passed this binder object to
1347 // others.
1348 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001349 // TODO: Should this give an error if the VM is already dead?
1350 self.instance.callbacks.add(callback.clone());
1351 Ok(())
1352 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001353
Andrew Walbranf8d94112021-09-07 11:45:36 +00001354 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001355 self.instance
1356 .start()
1357 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1358 .with_log()
1359 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001360 }
1361
Inseob Kima446f802022-07-11 19:46:37 +09001362 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001363 self.instance
1364 .kill()
1365 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1366 .with_log()
1367 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001368 }
1369
Keir Fraser48221ba2024-07-12 14:05:02 +00001370 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1371 let balloon = self
1372 .instance
1373 .get_memory_balloon()
1374 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1375 .with_log()
1376 .or_service_specific_exception(-1)?;
1377 Ok(balloon.try_into().unwrap())
1378 }
1379
1380 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001381 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001382 .set_memory_balloon(num_bytes.try_into().unwrap())
1383 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001384 .with_log()
1385 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001386 }
1387
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001388 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001389 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001390 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001391 }
Alan Stokes10c47672022-12-13 17:17:08 +00001392 let port = port as u32;
1393 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001394 return Err(anyhow!("Can't connect to privileged port {port}"))
1395 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001396 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001397 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1398 .context("Failed to connect")
1399 .or_service_specific_exception(-1)?;
Jiyong Parkba3099e2024-08-20 18:19:12 +09001400 vsock_stream_to_pfd(stream)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001401 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001402
1403 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1404 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1405 }
Jiyong Park23b67392024-07-04 13:51:42 +09001406
1407 fn suspend(&self) -> binder::Result<()> {
1408 self.instance
1409 .suspend()
1410 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1411 .with_log()
1412 .or_service_specific_exception(-1)
1413 }
1414
1415 fn resume(&self) -> binder::Result<()> {
1416 self.instance
1417 .resume()
1418 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1419 .with_log()
1420 .or_service_specific_exception(-1)
1421 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001422}
1423
1424impl Drop for VirtualMachine {
1425 fn drop(&mut self) {
1426 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001427 if let Err(e) = self.instance.kill() {
1428 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1429 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001430 }
1431}
1432
1433/// A set of Binders to be called back in response to various events on the VM, such as when it
1434/// dies.
1435#[derive(Debug, Default)]
1436pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1437
1438impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001439 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001440 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001441 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001442 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001443 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001444 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001445 }
1446 }
1447 }
1448
Inseob Kim14cb8692021-08-31 21:50:39 +09001449 /// Call all registered callbacks to notify that the payload is ready to serve.
1450 pub fn notify_payload_ready(&self, cid: Cid) {
1451 let callbacks = &*self.0.lock().unwrap();
1452 for callback in callbacks {
1453 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001454 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001455 }
1456 }
1457 }
1458
Inseob Kim2444af92021-08-31 01:22:50 +09001459 /// Call all registered callbacks to notify that the payload has finished.
1460 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1461 let callbacks = &*self.0.lock().unwrap();
1462 for callback in callbacks {
1463 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001464 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001465 }
1466 }
1467 }
1468
Jooyung Handd0a1732021-11-23 15:26:20 +09001469 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001470 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001471 let callbacks = &*self.0.lock().unwrap();
1472 for callback in callbacks {
1473 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001474 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001475 }
1476 }
1477 }
1478
Andrew Walbrandae07162021-03-12 17:05:20 +00001479 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001480 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001481 let callbacks = &*self.0.lock().unwrap();
1482 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001483 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001484 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001485 }
1486 }
1487 }
1488
1489 /// Add a new callback to the set.
1490 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1491 self.0.lock().unwrap().push(callback);
1492 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001493}
1494
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001495/// The mutable state of the VirtualizationService. There should only be one instance of this
1496/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001497#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001498struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001499 /// The VMs which have been started. When VMs are started a weak reference is added to this
1500 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1501 /// the Binder client are dropped the weak reference here will become invalid, and will be
1502 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001503 vms: Vec<Weak<VmInstance>>,
1504}
1505
1506impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001507 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001508 fn vms(&self) -> Vec<Arc<VmInstance>> {
1509 // Attempt to upgrade the weak pointers to strong pointers.
1510 self.vms.iter().filter_map(Weak::upgrade).collect()
1511 }
1512
1513 /// Add a new VM to the list.
1514 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1515 // Garbage collect any entries from the stored list which no longer exist.
1516 self.vms.retain(|vm| vm.strong_count() > 0);
1517
1518 // Actually add the new VM.
1519 self.vms.push(vm);
1520 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001521
Jiyong Park8611a6c2021-07-09 18:17:44 +09001522 /// Get a VM that corresponds to the given cid
1523 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1524 self.vms().into_iter().find(|vm| vm.cid == cid)
1525 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001526}
1527
Andrew Walbran6b650662021-09-07 13:13:23 +00001528/// Gets the `VirtualMachineState` of the given `VmInstance`.
1529fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001530 match &*instance.vm_state.lock().unwrap() {
1531 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1532 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001533 PayloadState::Starting => VirtualMachineState::STARTING,
1534 PayloadState::Started => VirtualMachineState::STARTED,
1535 PayloadState::Ready => VirtualMachineState::READY,
1536 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001537 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001538 },
1539 VmState::Dead => VirtualMachineState::DEAD,
1540 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001541 }
1542}
1543
David Brazdilf50c7a62023-04-19 14:22:42 +00001544/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001545pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1546 file.as_ref()
1547 .try_clone()
1548 .context("Failed to clone File from ParcelFileDescriptor")
1549 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001550 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001551}
1552
Andrew Walbrand3a84182021-09-07 14:48:52 +00001553/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001554fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001555 file.as_ref().map(clone_file).transpose()
1556}
1557
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001558/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkba3099e2024-08-20 18:19:12 +09001559fn vsock_stream_to_pfd(stream: VsockStream) -> binder::Result<ParcelFileDescriptor> {
1560 let owned_fd = take_fd_ownership(stream.into_raw_fd())
1561 .context("Failed to take ownership of the vsock stream")
1562 .with_log()
1563 .or_service_specific_exception(-1)?;
1564 Ok(ParcelFileDescriptor::new(owned_fd))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001565}
1566
Jiyong Parkdcf17412022-02-08 15:07:23 +09001567/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001568fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1569 VersionReq::parse(s)
1570 .with_context(|| format!("Invalid platform version requirement {}", s))
1571 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001572}
1573
Jiyong Parked180932023-02-24 19:55:41 +09001574/// Create the empty ramdump file
1575fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1576 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1577 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1578 // owner) for readout.
1579 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001580 let ramdump = File::create(ramdump_path)
1581 .context("Failed to prepare ramdump file")
1582 .with_log()
1583 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001584 Ok(ramdump)
1585}
1586
Nikita Ioffe5776f082023-02-10 21:38:26 +00001587fn is_protected(config: &VirtualMachineConfig) -> bool {
1588 match config {
1589 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1590 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1591 }
1592}
1593
1594fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1595 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001596 return Err(anyhow!("Can't use gdb with protected VMs"))
1597 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001598 }
1599
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001600 if get_debug_level(config) == Some(DebugLevel::NONE) {
1601 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1602 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001603 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001604
1605 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001606}
1607
Shikha Panwar61a74b52024-02-16 13:17:01 +00001608fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1609 match config {
1610 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1611 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1612 }
1613}
1614
Alan Stokesc96b35e2024-05-03 13:21:20 +01001615fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1616 match config {
1617 VirtualMachineConfig::RawConfig(_) => true,
1618 VirtualMachineConfig::AppConfig(config) => {
1619 let Some(custom) = &config.customConfig else { return true };
1620 custom.wantUpdatable
1621 }
1622 }
1623}
1624
Nikita Ioffe5776f082023-02-10 21:38:26 +00001625fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1626 match config {
1627 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001628 VirtualMachineConfig::AppConfig(config) => {
1629 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1630 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001631 }
1632}
1633
Nikita Ioffe631717e2023-09-05 13:38:07 +01001634fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1635 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1636 if let Some(custom_config) = &config.customConfig {
1637 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1638 return Err(anyhow!("vendor modules feature is disabled"))
1639 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1640 }
1641 }
1642 Ok(())
1643}
1644
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001645fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1646 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1647 if let Some(custom_config) = &config.customConfig {
1648 if !custom_config.devices.is_empty() {
1649 return Err(anyhow!("device assignment feature is disabled"))
1650 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1651 }
1652 }
1653 Ok(())
1654}
1655
Alan Stokesfda70842023-12-20 17:50:14 +00001656fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1657 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1658 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1659 if !payload_config.extraApks.is_empty() {
1660 return Err(anyhow!("multi-tenant feature is disabled"))
1661 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1662 }
1663 Ok(())
1664}
1665
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001666fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1667 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1668 if let Some(custom_config) = &config.customConfig {
1669 if !custom_config.extraKernelCmdlineParams.is_empty() {
1670 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1671 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1672 }
1673 }
1674 Ok(())
1675}
1676
Nikita Ioffef934e812024-07-05 15:44:41 +00001677fn check_protected_vm_is_supported() -> binder::Result<()> {
1678 let is_pvm_supported =
1679 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1680 if is_pvm_supported {
1681 Ok(())
1682 } else {
1683 Err(anyhow!("pVM is not supported"))
1684 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1685 }
1686}
1687
Nikita Ioffe631717e2023-09-05 13:38:07 +01001688fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1689 if !cfg!(vendor_modules) {
1690 check_no_vendor_modules(config)?;
1691 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001692 if !cfg!(device_assignment) {
1693 check_no_devices(config)?;
1694 }
Alan Stokesfda70842023-12-20 17:50:14 +00001695 if !cfg!(multi_tenant) {
1696 check_no_extra_apks(config)?;
1697 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001698 if !cfg!(debuggable_vms_improvements) {
1699 check_no_extra_kernel_cmdline_params(config)?;
1700 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001701 Ok(())
1702}
1703
Inseob Kimecde8c02024-09-03 13:11:08 +09001704fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1705 check_no_vendor_modules(config)?;
1706 check_no_devices(config)?;
1707
1708 Ok(())
1709}
1710
Inseob Kim0168b462022-12-27 14:54:35 +09001711fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001712 fd: Option<&ParcelFileDescriptor>,
1713 tag: String,
1714) -> Result<Option<File>, Status> {
1715 if let Some(fd) = fd {
1716 return Ok(Some(clone_file(fd)?));
1717 }
1718
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001719 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001720 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001721
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001722 let mut reader = BufReader::new(File::from(read_fd));
1723 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001724
1725 std::thread::spawn(move || loop {
1726 let mut buf = vec![];
1727 match reader.read_until(b'\n', &mut buf) {
1728 Ok(0) => {
1729 // EOF
1730 return;
1731 }
1732 Ok(size) => {
1733 if buf[size - 1] == b'\n' {
1734 buf.pop();
1735 }
1736 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1737 }
1738 Err(e) => {
1739 error!("Could not read console pipe: {:?}", e);
1740 return;
1741 }
1742 };
1743 });
1744
1745 Ok(Some(write_fd))
1746}
1747
Jooyung Han35edb8f2021-07-01 16:17:16 +09001748/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1749/// it doesn't require that T implements Clone.
1750enum BorrowedOrOwned<'a, T> {
1751 Borrowed(&'a T),
1752 Owned(T),
1753}
1754
1755impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1756 fn as_ref(&self) -> &T {
1757 match self {
1758 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001759 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001760 }
1761 }
1762}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001763
1764/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1765#[derive(Debug, Default)]
1766struct VirtualMachineService {
1767 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001768 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001769}
1770
1771impl Interface for VirtualMachineService {}
1772
1773impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001774 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1775 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001776 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001777 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001778 vm.update_payload_state(PayloadState::Started)
1779 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001780 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001781
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001782 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1783 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001784 Ok(())
1785 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001786 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001787 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001788 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001789 }
Inseob Kim2444af92021-08-31 01:22:50 +09001790
Inseob Kimc7d28c72021-10-25 14:28:10 +00001791 fn notifyPayloadReady(&self) -> binder::Result<()> {
1792 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001793 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001794 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001795 vm.update_payload_state(PayloadState::Ready)
1796 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001797 vm.callbacks.notify_payload_ready(cid);
1798 Ok(())
1799 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001800 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001801 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001802 }
1803 }
1804
Inseob Kimc7d28c72021-10-25 14:28:10 +00001805 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1806 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001807 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001808 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001809 vm.update_payload_state(PayloadState::Finished)
1810 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001811 vm.callbacks.notify_payload_finished(cid, exit_code);
1812 Ok(())
1813 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001814 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001815 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001816 }
1817 }
1818
Alan Stokes2bead0d2022-09-05 16:58:34 +01001819 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001820 let cid = self.cid;
1821 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001822 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001823 vm.update_payload_state(PayloadState::Finished)
1824 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001825 vm.callbacks.notify_error(cid, error_code, message);
1826 Ok(())
1827 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001828 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001829 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001830 }
1831 }
Alice Wangc2fec932023-02-23 16:24:02 +00001832
Shikha Panware45e9422024-02-28 21:18:10 +00001833 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1834 if !is_secretkeeper_supported() {
1835 return Err(StatusCode::NAME_NOT_FOUND)?;
1836 }
1837 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1838 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001839 }
1840
Alice Wange64dd182024-01-17 15:57:55 +00001841 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1842 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001843 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001844}
1845
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001846fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001847 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1848 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001849}
1850
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001851impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001852 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001853 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001854 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001855 BinderFeatures::default(),
1856 )
1857 }
1858}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001859
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001860struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1861
1862impl Interface for SecretkeeperProxy {}
1863
1864impl ISecretkeeper for SecretkeeperProxy {
1865 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1866 // Pass the request to the channel, and read the response.
1867 self.0.processSecretManagementRequest(req)
1868 }
1869
1870 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1871 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1872 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1873 }
1874
1875 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1876 self.0.deleteIds(ids)
1877 }
1878
1879 fn deleteAll(&self) -> binder::Result<()> {
1880 self.0.deleteAll()
1881 }
1882}
1883
1884struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1885
1886impl Interface for AuthGraphKeyExchangeProxy {}
1887
1888impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1889 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1890 self.0.create()
1891 }
1892
1893 fn init(
1894 &self,
1895 peer_pub_key: &PubKey,
1896 peer_id: &Identity,
1897 peer_nonce: &[u8],
1898 peer_version: i32,
1899 ) -> binder::Result<KeInitResult> {
1900 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1901 }
1902
1903 fn finish(
1904 &self,
1905 peer_pub_key: &PubKey,
1906 peer_id: &Identity,
1907 peer_signature: &SessionIdSignature,
1908 peer_nonce: &[u8],
1909 peer_version: i32,
1910 own_key: &Key,
1911 ) -> binder::Result<SessionInfo> {
1912 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1913 }
1914
1915 fn authenticationComplete(
1916 &self,
1917 peer_signature: &SessionIdSignature,
1918 shared_keys: &[AuthgraphArc; 2],
1919 ) -> binder::Result<[AuthgraphArc; 2]> {
1920 self.0.authenticationComplete(peer_signature, shared_keys)
1921 }
1922}
1923
Inseob Kimecde8c02024-09-03 13:11:08 +09001924// KEEP IN SYNC WITH early_vms.xsd
1925#[derive(Debug, Deserialize, PartialEq)]
1926struct EarlyVm {
1927 #[allow(dead_code)]
1928 name: String,
1929 #[allow(dead_code)]
1930 cid: i32,
1931 #[allow(dead_code)]
1932 path: String,
1933}
1934
1935#[derive(Debug, Default, Deserialize)]
1936struct EarlyVms {
1937 #[allow(dead_code)]
1938 early_vm: Vec<EarlyVm>,
1939}
1940
1941fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1942 match partition {
1943 "system" => Ok(100..200),
1944 "system_ext" | "product" => Ok(200..300),
1945 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1946 }
1947}
1948
1949fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1950 if !xml_path.exists() {
1951 bail!("{} doesn't exist", xml_path.display());
1952 }
1953
1954 let xml =
1955 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
1956 let xml = String::from_utf8(xml)
1957 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
1958 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
1959 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
1960
1961 let mut found_vm: Option<EarlyVm> = None;
1962
1963 for early_vm in early_vms.early_vm {
1964 if early_vm.name != name {
1965 continue;
1966 }
1967
1968 let cid = early_vm
1969 .cid
1970 .try_into()
1971 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
1972
1973 if !cid_range.contains(&cid) {
1974 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
1975 }
1976
1977 if found_vm.is_some() {
1978 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
1979 }
1980
1981 found_vm = Some(early_vm);
1982 }
1983
1984 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
1985}
1986
1987fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
1988 let cid_range = range_for_partition(partition)?;
1989 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
1990}
1991
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001992#[cfg(test)]
1993mod tests {
1994 use super::*;
1995
1996 #[test]
1997 fn test_is_allowed_label_for_partition() -> Result<()> {
1998 let expected_results = vec![
1999 ("u:object_r:system_file:s0", true),
2000 ("u:object_r:apk_data_file:s0", true),
2001 ("u:object_r:app_data_file:s0", false),
2002 ("u:object_r:app_data_file:s0:c512,c768", false),
2003 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2004 ("invalid", false),
2005 ("user:role:apk_data_file:severity:categories", true),
2006 ("user:role:apk_data_file:severity:categories:extraneous", false),
2007 ];
2008
2009 for (label, expected_valid) in expected_results {
2010 let context = SeContext::new(label)?;
2011 let result = check_label_is_allowed(&context);
2012 if expected_valid {
2013 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2014 } else if result.is_ok() {
2015 bail!("Expected label {} to be disallowed", label);
2016 }
2017 }
2018 Ok(())
2019 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002020
2021 #[test]
2022 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2023 let apk = tempfile::tempfile().unwrap();
2024 let idsig = tempfile::tempfile().unwrap();
2025
2026 let ret = create_or_update_idsig_file(
2027 &ParcelFileDescriptor::new(apk),
2028 &ParcelFileDescriptor::new(idsig),
2029 );
2030 assert!(ret.is_err(), "should fail");
2031 Ok(())
2032 }
2033
2034 #[test]
2035 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2036 let tmp_dir = tempfile::TempDir::new().unwrap();
2037 let apk = File::open(tmp_dir.path()).unwrap();
2038 let idsig = tempfile::tempfile().unwrap();
2039
2040 let ret = create_or_update_idsig_file(
2041 &ParcelFileDescriptor::new(apk),
2042 &ParcelFileDescriptor::new(idsig),
2043 );
2044 assert!(ret.is_err(), "should fail");
2045 Ok(())
2046 }
2047
2048 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2049 /// on ext4 filesystem is passed.
2050 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2051 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2052 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2053 #[test]
2054 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2055 // APEXes are backed by the ext4.
2056 let apk = File::open("/apex/com.android.virt/").unwrap();
2057 let idsig = tempfile::tempfile().unwrap();
2058
2059 let ret = create_or_update_idsig_file(
2060 &ParcelFileDescriptor::new(apk),
2061 &ParcelFileDescriptor::new(idsig),
2062 );
2063 assert!(ret.is_err(), "should fail");
2064 Ok(())
2065 }
Jiyong Park8d192952023-06-26 14:29:51 +09002066
2067 #[test]
2068 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2069 use std::io::Seek;
2070
2071 // Pick any APK
2072 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2073 let mut idsig = tempfile::tempfile().unwrap();
2074
2075 create_or_update_idsig_file(
2076 &ParcelFileDescriptor::new(apk.try_clone()?),
2077 &ParcelFileDescriptor::new(idsig.try_clone()?),
2078 )?;
2079 let modified_orig = idsig.metadata()?.modified()?;
2080 apk.rewind()?;
2081 idsig.rewind()?;
2082
2083 // Call the function again
2084 create_or_update_idsig_file(
2085 &ParcelFileDescriptor::new(apk.try_clone()?),
2086 &ParcelFileDescriptor::new(idsig.try_clone()?),
2087 )?;
2088 let modified_new = idsig.metadata()?.modified()?;
2089 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2090 Ok(())
2091 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002092
2093 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002094 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2095 use std::io::Read;
2096
2097 // Pick any APK
2098 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2099 let idsig_empty = tempfile::tempfile().unwrap();
2100 let mut idsig_invalid = tempfile::tempfile().unwrap();
2101 idsig_invalid.write_all(b"Oops")?;
2102
2103 // Create new idsig
2104 create_or_update_idsig_file(
2105 &ParcelFileDescriptor::new(apk.try_clone()?),
2106 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2107 )?;
2108 apk.rewind()?;
2109
2110 // Update idsig_invalid
2111 create_or_update_idsig_file(
2112 &ParcelFileDescriptor::new(apk.try_clone()?),
2113 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2114 )?;
2115
2116 // Ensure the 2 idsig files have same size!
2117 assert!(
2118 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2119 "idsig files differ in size"
2120 );
2121 // Ensure the 2 idsig files have same content!
2122 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2123 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2124 }
2125 Ok(())
2126 }
2127 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002128 fn test_append_kernel_param_first_param() {
2129 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2130 append_kernel_param("foo=1", &mut vm_config);
2131 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2132 }
2133
2134 #[test]
2135 fn test_append_kernel_param() {
2136 let mut vm_config =
2137 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2138 append_kernel_param("bar=42", &mut vm_config);
2139 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2140 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002141
Inseob Kim46257382024-01-03 15:41:22 +09002142 fn test_extract_os_name_from_config_path(
2143 path: &Path,
2144 expected_result: Option<&str>,
2145 ) -> Result<()> {
2146 let result = extract_os_name_from_config_path(path);
2147 if result.as_deref() != expected_result {
2148 bail!("Expected {:?} but was {:?}", expected_result, &result)
2149 }
2150 Ok(())
2151 }
2152
2153 #[test]
2154 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2155 test_extract_os_name_from_config_path(
2156 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2157 Some("microdroid"),
2158 )
2159 }
2160
2161 #[test]
2162 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2163 test_extract_os_name_from_config_path(
2164 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2165 Some("microdroid_gki-android14-6.1"),
2166 )
2167 }
2168
2169 #[test]
2170 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2171 test_extract_os_name_from_config_path(
2172 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2173 None,
2174 )
2175 }
2176
2177 #[test]
2178 fn test_extract_os_name_from_configs() -> Result<()> {
2179 let tmp_dir = tempfile::TempDir::new()?;
2180 let tmp_dir_path = tmp_dir.path().to_owned();
2181
2182 let mut os_names: HashSet<String> = HashSet::new();
2183 os_names.insert("microdroid".to_owned());
2184 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2185 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2186
2187 // config files
2188 for os_name in &os_names {
2189 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2190 }
2191
2192 // fake files not related to configs
2193 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2194 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2195
2196 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2197 Some(s) => s.to_owned(),
2198 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2199 };
2200
2201 let result = extract_os_names_from_configs(&glob_pattern)?;
2202 if result != os_names {
2203 bail!("Expected {:?} but was {:?}", os_names, result);
2204 }
2205 Ok(())
2206 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002207
2208 #[test]
2209 fn test_find_early_vms_from_xml() -> Result<()> {
2210 let tmp_dir = tempfile::TempDir::new()?;
2211 let tmp_dir_path = tmp_dir.path().to_owned();
2212 let xml_path = tmp_dir_path.join("early_vms.xml");
2213
2214 std::fs::write(
2215 &xml_path,
2216 br#"<?xml version="1.0" encoding="utf-8"?>
2217 <early_vms>
2218 <early_vm>
2219 <name>vm_demo_native_early</name>
2220 <cid>123</cid>
2221 <path>/system/bin/vm_demo_native_early</path>
2222 </early_vm>
2223 <early_vm>
2224 <name>vm_demo_duplicated_name</name>
2225 <cid>456</cid>
2226 <path>/system/bin/vm_demo_duplicated_name_1</path>
2227 </early_vm>
2228 <early_vm>
2229 <name>vm_demo_duplicated_name</name>
2230 <cid>789</cid>
2231 <path>/system/bin/vm_demo_duplicated_name_2</path>
2232 </early_vm>
2233 <early_vm>
2234 <name>vm_demo_invalid_cid_1</name>
2235 <cid>-1</cid>
2236 <path>/system/bin/vm_demo_invalid_cid_1</path>
2237 </early_vm>
2238 <early_vm>
2239 <name>vm_demo_invalid_cid_2</name>
2240 <cid>999999</cid>
2241 <path>/system/bin/vm_demo_invalid_cid_2</path>
2242 </early_vm>
2243 </early_vms>
2244 "#,
2245 )?;
2246
2247 let cid_range = 100..1000;
2248
2249 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2250 let expected = EarlyVm {
2251 name: "vm_demo_native_early".to_owned(),
2252 cid: 123,
2253 path: "/system/bin/vm_demo_native_early".to_owned(),
2254 };
2255 assert_eq!(result, expected);
2256
2257 assert!(
2258 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2259 "should fail"
2260 );
2261 assert!(
2262 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2263 "should fail"
2264 );
2265 assert!(
2266 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2267 "should fail"
2268 );
2269
2270 Ok(())
2271 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002272}