blob: 66d32ce256956b3c16f72435222ce7442c44cb6b [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;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, 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::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000073use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
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 Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, 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};
Devin Moorec8800a12024-10-17 17:56:18 +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
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
Nikita Ioffe832410f2025-03-07 15:24:44 +0000120const VM_CAPABILITIES_HAL_IDENTIFIER: &str =
121 "android.hardware.virtualization.capabilities.IVmCapabilitiesService/default";
122
David Brazdilf50c7a62023-04-19 14:22:42 +0000123const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
124
125/// crosvm requires all partitions to be a multiple of 4KiB.
126const PARTITION_GRANULARITY_BYTES: u64 = 4096;
127
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000128const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
129
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100130pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
131 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900132 if cfg!(early) {
133 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
134 } else {
135 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
136 .expect("Could not connect to VirtualizationServiceInternal")
137 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100138 });
139static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
140 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000141
Inseob Kime3e932d2024-12-16 20:06:57 +0900142static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
143 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
144 match fs::read_link(&calling_exe_link) {
145 Ok(calling_exe_path) => Some(calling_exe_path),
146 Err(e) => {
147 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
148 // discourage vendor apps, regarding such cases as system is safer.
149 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
150 // apps.
151 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
152 None
153 }
154 }
155});
156
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000157// TODO(ioffe): add service for guest-ffa.
158const KNOWN_TEE_SERVICES: [&str; 0] = [];
159
160fn check_known_tee_service(tee_service: &str) -> binder::Result<()> {
161 if !KNOWN_TEE_SERVICES.contains(&tee_service) {
162 return Err(anyhow!("unknown tee_service {tee_service}"))
163 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
164 }
165 Ok(())
166}
167
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000168fn create_or_update_idsig_file(
169 input_fd: &ParcelFileDescriptor,
170 idsig_fd: &ParcelFileDescriptor,
171) -> Result<()> {
172 let mut input = clone_file(input_fd)?;
173 let metadata = input.metadata().context("failed to get input metadata")?;
174 if !metadata.is_file() {
175 bail!("input is not a regular file");
176 }
Alan Stokes25f69362023-03-06 16:51:54 +0000177 let mut sig =
178 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
179 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000180
181 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900182
183 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
184 // if the idsig file already has the same APK digest.
185 if output.metadata()?.len() > 0 {
186 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
187 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
188 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
189 return Ok(());
190 }
191 }
192 // if we fail to read v4signature from output, that's fine. User can pass a random file.
193 // We will anyway overwrite the file to the v4signature generated from input_fd.
194 }
195
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000196 output
197 .seek(SeekFrom::Start(0))
198 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000199 output.set_len(0).context("failed to set_len on the idsig output")?;
200 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000201 Ok(())
202}
203
Alan Stokes25f69362023-03-06 16:51:54 +0000204fn get_current_sdk() -> Result<u32> {
205 let current_sdk = system_properties::read("ro.build.version.sdk")?;
206 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
207 current_sdk.parse().context("Malformed SDK version")
208}
209
David Brazdil4b4c5102022-12-19 22:56:20 +0000210pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
211 for dir_entry in read_dir(path)? {
212 remove_file(dir_entry?.path())?;
213 }
214 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100215}
216
David Brazdil528e0472022-10-10 15:06:02 +0100217/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000218#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000219pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900220 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221}
222
Shikha Panward8e35422021-10-11 13:51:27 +0000223impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000225 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
226 let state = &mut *self.state.lock().unwrap();
227 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000228 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000229 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000230 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
231 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000232 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000233 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000234 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000235 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
236 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000237 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000238 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000239 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000240 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000241 .or(Err(StatusCode::UNKNOWN_ERROR))?;
242 }
243 Ok(())
244 }
245}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000246impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000247 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
248 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000249 ///
250 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000251 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000252 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000253 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900254 console_out_fd: Option<&ParcelFileDescriptor>,
255 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000256 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000257 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000258 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000259 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900260 let ret = self.create_vm_internal(
261 config,
262 console_out_fd,
263 console_in_fd,
264 log_fd,
265 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000266 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900267 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000268 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000269 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000270 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000271
Shikha Panwar61a74b52024-02-16 13:17:01 +0000272 /// Allocate a new instance_id to the VM
273 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000274 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000275 GLOBAL_SERVICE.allocateInstanceId()
276 }
277
Andrew Walbrandff3b942021-06-09 15:20:36 +0000278 /// Initialise an empty partition image of the given size to be used as a writable partition.
279 fn initializeWritablePartition(
280 &self,
281 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000282 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900283 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000284 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900285 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900286 let size_bytes = size_bytes
287 .try_into()
288 .with_context(|| format!("Invalid size: {}", size_bytes))
289 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000291 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000292 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000293 image
294 .seek(SeekFrom::Start(0))
295 .context("failed to move cursor to start")
296 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900297 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700298 // Set the file length. In most filesystems, this will not allocate any physical disk
299 // space, it will only change the logical size.
300 image
301 .set_len(size_bytes)
302 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900303 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000304
305 match partition_type {
306 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700307 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
308 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000309 _ => Err(Error::new(
310 ErrorKind::Unsupported,
311 format!("Unsupported partition type {:?}", partition_type),
312 )),
313 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
315 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000316
317 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000318 }
319
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800320 fn setEncryptedStorageSize(
321 &self,
322 image_fd: &ParcelFileDescriptor,
323 size: i64,
324 ) -> binder::Result<()> {
325 check_manage_access()?;
326
327 let size = size
328 .try_into()
329 .with_context(|| format!("Invalid size: {}", size))
330 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
331 let size = round_up(size, PARTITION_GRANULARITY_BYTES);
332
333 let image = clone_file(image_fd)?;
334 let image_size = image.metadata().unwrap().len();
335
336 if image_size > size {
337 return Err(Status::new_exception_str(
338 ExceptionCode::ILLEGAL_ARGUMENT,
339 Some("Can't shrink encrypted storage"),
340 ));
341 }
342 // Reset the file length. In most filesystems, this will not allocate any physical disk
343 // space, it will only change the logical size.
344 image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
345 Ok(())
346 }
347
Jiyong Park0a248432021-08-20 23:32:39 +0900348 /// Creates or update the idsig file by digesting the input APK file.
349 fn createOrUpdateIdsigFile(
350 &self,
351 input_fd: &ParcelFileDescriptor,
352 idsig_fd: &ParcelFileDescriptor,
353 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900354 check_manage_access()?;
355
Jiyong Park2227eaa2023-08-04 11:59:18 +0900356 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900357 Ok(())
358 }
359
Andrew Walbran320b5602021-03-04 16:11:12 +0000360 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
361 /// and as such is only permitted from the shell user.
362 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000363 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000364 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000365 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900366
367 /// Get a list of assignable device types.
368 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
369 // Delegate to the global service, including checking the permission.
370 GLOBAL_SERVICE.getAssignableDevices()
371 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100372
Inseob Kim46257382024-01-03 15:41:22 +0900373 /// Get a list of supported OSes.
374 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
375 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
376 }
377
Jaewan Kimabd328b2024-12-10 15:59:33 +0900378 /// Get printable debug policy for testing and debugging
379 fn getDebugPolicy(&self) -> binder::Result<String> {
380 let debug_policy = DebugPolicy::from_host();
381 Ok(format!("{debug_policy:?}"))
382 }
383
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100384 /// Returns whether given feature is enabled
385 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
386 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000387 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100388 }
Alice Wange64dd182024-01-17 15:57:55 +0000389
390 fn enableTestAttestation(&self) -> binder::Result<()> {
391 GLOBAL_SERVICE.enableTestAttestation()
392 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000393
394 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
395 check_manage_access()?;
396 GLOBAL_SERVICE.isRemoteAttestationSupported()
397 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000398
399 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
400 // The response is specific to Microdroid. Updatable VMs are only possible if device
401 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
402 // this, however other guest OSes may do things differently.
403 check_manage_access()?;
404 Ok(is_secretkeeper_supported())
405 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000406
Shikha Panwar07d701c2024-03-28 14:43:52 +0000407 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
408 check_manage_access()?;
409 GLOBAL_SERVICE.removeVmInstance(instance_id)
410 }
411
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000412 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
413 check_manage_access()?;
414 GLOBAL_SERVICE.claimVmInstance(instance_id)
415 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000416}
417
Inseob Kimecde8c02024-09-03 13:11:08 +0900418/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
419#[derive(Debug, Default)]
420struct EarlyVmContext {
421 /// The unique CID assigned to the VM for vsock communication.
422 cid: Cid,
423 /// Temporary directory for this VM instance.
424 temp_dir: PathBuf,
425}
426
427impl EarlyVmContext {
428 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
429 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
430 // should trust clients, e.g. they won't run two VMs at the same time
431 let _ = remove_dir_all(&temp_dir);
432 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
433
434 Ok(Self { cid, temp_dir })
435 }
436}
437
438impl Interface for EarlyVmContext {}
439
440impl Drop for EarlyVmContext {
441 fn drop(&mut self) {
442 if let Err(e) = remove_dir_all(&self.temp_dir) {
443 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
444 }
445 }
446}
447
448impl IGlobalVmContext for EarlyVmContext {
449 fn getCid(&self) -> binder::Result<i32> {
450 Ok(self.cid as i32)
451 }
452
453 fn getTemporaryDirectory(&self) -> binder::Result<String> {
454 Ok(self.temp_dir.to_string_lossy().to_string())
455 }
456
457 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
458 Err(Status::new_exception_str(
459 ExceptionCode::UNSUPPORTED_OPERATION,
460 Some("Early VM doesn't support setting host console name"),
461 ))
462 }
463}
464
Frederick Mayle3a46b272025-02-10 21:55:49 -0800465#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466enum CallingPartition {
467 Odm,
468 Product,
469 System,
470 SystemExt,
471 Vendor,
472 Unknown,
473}
474
475impl CallingPartition {
476 fn as_str(&self) -> &'static str {
477 match self {
478 CallingPartition::Odm => "odm",
479 CallingPartition::Product => "product",
480 CallingPartition::System => "system",
481 CallingPartition::SystemExt => "system_ext",
482 CallingPartition::Vendor => "vendor",
483 CallingPartition::Unknown => "[unknown]",
484 }
485 }
486}
487
488impl std::fmt::Display for CallingPartition {
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 write!(f, "{}", self.as_str())
491 }
492}
493
494fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800495 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800496 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900497 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000498 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800499 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000500 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800501 if path.starts_with("/system/product/") {
502 return Ok(CallingPartition::Product);
503 }
Frederick Mayle2192baf2025-02-26 11:27:22 -0800504 if path.starts_with("/data/nativetest/vendor/")
505 || path.starts_with("/data/nativetest64/vendor/")
506 {
507 return Ok(CallingPartition::Vendor);
508 }
509
Frederick Mayle3a46b272025-02-10 21:55:49 -0800510 let partition = {
511 let mut components = path.components();
512 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
513 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800514 .or_service_specific_exception(-1);
515 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800516
Frederick Mayle3a46b272025-02-10 21:55:49 -0800517 // If path is under /apex, find a partition of the preinstalled .apex path
518 if partition == "apex" {
519 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
520 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
521 .or_service_specific_exception(-1);
522 };
523 let apex_info_list = ApexInfoList::load()
524 .context("Failed to get apex info list")
525 .or_service_specific_exception(-1)?;
526 apex_info_list
527 .list
528 .iter()
529 .find(|apex_info| apex_info.name.as_str() == apex_name)
530 .map(|apex_info| apex_info.partition.to_lowercase())
531 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
532 .or_service_specific_exception(-1)?
533 } else {
534 partition.to_string_lossy().into_owned()
535 }
536 };
537 Ok(match partition.as_str() {
538 "odm" => CallingPartition::Odm,
539 "product" => CallingPartition::Product,
540 "system" => CallingPartition::System,
541 "system_ext" => CallingPartition::SystemExt,
542 "vendor" => CallingPartition::Vendor,
543 _ => {
544 warn!("unknown partition for '{}'", path.display());
545 CallingPartition::Unknown
546 }
547 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900548}
549
Jiyong Park8611a6c2021-07-09 18:17:44 +0900550impl VirtualizationService {
551 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000552 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900553 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000554
Inseob Kimecde8c02024-09-03 13:11:08 +0900555 fn create_early_vm_context(
556 &self,
557 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900558 calling_exe_path: Option<&Path>,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800559 calling_partition: CallingPartition,
Inseob Kimecde8c02024-09-03 13:11:08 +0900560 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900561 let name = match config {
562 VirtualMachineConfig::RawConfig(config) => &config.name,
563 VirtualMachineConfig::AppConfig(config) => &config.name,
564 };
Frederick Mayle3a46b272025-02-10 21:55:49 -0800565 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900566 .or_service_specific_exception(-1)?;
567 let calling_exe_path = match calling_exe_path {
568 Some(path) => path,
569 None => {
570 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
571 .or_service_specific_exception(-1)
572 }
573 };
Alice Wang78dd87a2025-02-13 08:56:07 +0000574 early_vm.check_exe_paths_match(calling_exe_path)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900575
576 let cid = early_vm.cid as Cid;
577 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
578
579 let context = EarlyVmContext::new(cid, temp_dir.clone())
580 .context(format!("Can't create early vm contexts for {cid}"))
581 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900582
Jiyong Park690c1ca2024-11-28 18:06:50 +0900583 if requires_vm_service(config) {
584 // Start VM service listening for connections from the new CID on port=CID.
585 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
586 let port = cid;
587 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
588 .context(format!("Could not start RpcServer on port {port}"))
589 .or_service_specific_exception(-1)?;
590 vm_server.start();
591 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
592 } else {
593 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
594 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900595 }
596
David Brazdil209074a2023-01-12 16:44:51 +0000597 fn create_vm_context(
598 &self,
599 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900600 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000601 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000602 const NUM_ATTEMPTS: usize = 5;
Jiyong Park18ceddc2025-03-18 13:30:02 +0900603 let name = get_name(config);
David Brazdil8cf8f482022-11-23 14:21:26 +0000604
605 for _ in 0..NUM_ATTEMPTS {
Jiyong Park18ceddc2025-03-18 13:30:02 +0900606 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(name, requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000607 let cid = vm_context.getCid()? as Cid;
608 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900609
610 // We don't need to start the VM service for custom VMs.
611 if !requires_vm_service(config) {
612 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
613 }
614
David Brazdil8cf8f482022-11-23 14:21:26 +0000615 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
616
617 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000618 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000619 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000620 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000621 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900622 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000623 }
624 Err(err) => {
625 warn!("Could not start RpcServer on port {}: {}", port, err);
626 }
627 }
628 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900629 Err(anyhow!("Too many attempts to create VM context failed"))
630 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000631 }
632
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000633 fn create_vm_internal(
634 &self,
635 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900636 console_out_fd: Option<&ParcelFileDescriptor>,
637 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000638 log_fd: Option<&ParcelFileDescriptor>,
639 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000640 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000641 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000642 let requester_uid = get_calling_uid();
643 let requester_debug_pid = get_calling_pid();
644
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800645 let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
646
Nikita Ioffe631717e2023-09-05 13:38:07 +0100647 check_config_features(config)?;
648
Inseob Kimecde8c02024-09-03 13:11:08 +0900649 if cfg!(early) {
650 check_config_allowed_for_early_vms(config)?;
651 }
652
Nikita Ioffeb1416122024-10-22 12:18:49 +0000653 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
654 info!("callers secontext: {}", caller_secontext);
655
David Brazdil209074a2023-01-12 16:44:51 +0000656 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900657 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800658 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900659 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900660 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900661 };
Inseob Kim1119d702022-05-02 18:01:58 +0900662
Alan Stokesfda70842023-12-20 17:50:14 +0000663 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100664 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900665 }
666
Nikita Ioffe5776f082023-02-10 21:38:26 +0000667 let gdb_port = extract_gdb_port(config);
668
669 // Additional permission checks if caller request gdb.
670 if gdb_port.is_some() {
671 check_gdb_allowed(config)?;
672 }
673
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800674 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900675 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800676 if let Some(dt_overlay) =
677 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
678 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900679 device_tree_overlays.push(dt_overlay);
680 }
681 if let Some(dtbo) = get_dtbo(config) {
682 let dtbo = File::from(
683 dtbo.as_ref()
684 .try_clone()
685 .context("Failed to create VM DTBO from ParcelFileDescriptor")
686 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
687 );
688 device_tree_overlays.push(dtbo);
689 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900690
Jaewan Kimf3143242024-03-15 06:56:31 +0000691 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000692 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900693 Some(prepare_ramdump_file(&temporary_directory)?)
694 } else {
695 None
696 };
697
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000698 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900699 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100700 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900701 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100702 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100703 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
704 Some(clone_file(fd)?)
705 } else if debug_config.dump_device_tree {
706 Some(prepare_dump_dt_file(&temporary_directory)?)
707 } else {
708 None
709 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000710
711 // Counter to generate unique IDs for temporary image files.
712 let mut next_temporary_image_id = 0;
713 // Files which are referred to from composite images. These must be mapped to the crosvm
714 // child process, and not closed before it is started.
715 let mut indirect_files = vec![];
716
Alan Stokes7bc146c2022-10-20 17:10:32 +0100717 let (is_app_config, config) = match config {
718 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
719 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900720 let config = load_app_config(config, &debug_config, &temporary_directory)
721 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900722 *is_protected = config.protectedVm;
723 let message = format!("Failed to load app config: {:?}", e);
724 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900725 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900726 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100727 (true, BorrowedOrOwned::Owned(config))
728 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000729 };
730 let config = config.as_ref();
731 *is_protected = config.protectedVm;
732
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000733 if !config.teeServices.is_empty() {
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000734 if !config.protectedVm {
735 return Err(anyhow!("only protected VMs can request tee services"))
736 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
737 }
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000738 check_tee_service_permission(&caller_secontext, &config.teeServices)
739 .with_log()
740 .or_binder_exception(ExceptionCode::SECURITY)?;
741 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000742
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000743 let mut system_tee_services = Vec::new();
744 let mut vendor_tee_services = Vec::new();
745 for tee_service in config.teeServices.clone() {
746 if !tee_service.starts_with("vendor.") {
747 check_known_tee_service(&tee_service)?;
748 system_tee_services.push(tee_service);
749 } else {
750 vendor_tee_services.push(tee_service);
751 }
752 }
753
Nikita Ioffecaff2822025-03-18 13:43:14 +0000754 if !vendor_tee_services.is_empty() && !is_vm_capabilities_hal_supported() {
755 return Err(anyhow!(
756 "requesting access to tee services requires {VM_CAPABILITIES_HAL_IDENTIFIER}"
757 ))
758 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000759 }
760
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000761 // TODO(b/391774181): remove this check in a follow-up patch.
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000762 if !system_tee_services.is_empty() {
763 return Err(anyhow!("support for system tee services is coming soon!"))
764 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
765 }
766
Jiyong Park3051ffe2024-11-26 14:41:58 +0900767 let kernel = maybe_clone_file(&config.kernel)?;
768 let initrd = maybe_clone_file(&config.initrd)?;
769
770 if config.protectedVm {
771 // Fail fast with a meaningful error message in case device doesn't support pVMs.
772 check_protected_vm_is_supported()?;
773
774 // In a protected VM, we require custom kernels to come from a trusted source
775 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800776 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
777 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900778
779 // Check if partition images are labeled incorrectly. This is to prevent random images
780 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
781 // from being loaded in a pVM. This applies to everything but the instance image in the
782 // raw config, and everything but the non-executable, generated partitions in the app
783 // config.
784 config
785 .disks
786 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800787 .flat_map(|disk| disk.image.as_ref())
788 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
789 .or_service_specific_exception(-1)?;
790 config
791 .disks
792 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900793 .flat_map(|disk| disk.partitions.iter())
794 .filter(|partition| {
795 if is_app_config {
796 !is_safe_app_partition(&partition.label)
797 } else {
798 !is_safe_raw_partition(&partition.label)
799 }
800 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800801 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900802 .or_service_specific_exception(-1)?;
803 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000804
Frederick Mayle279783a2025-03-18 16:16:45 -0700805 // Check if files for payloads and bases are on the same side of the Treble boundary as the
806 // calling process, as they may have unstable interfaces.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800807 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900808
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000809 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900810 write_zero_filler(&zero_filler_path)
811 .context("Failed to make composite image")
812 .with_log()
813 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000814
815 // Assemble disk images if needed.
816 let disks = config
817 .disks
818 .iter()
819 .map(|disk| {
820 assemble_disk_image(
821 disk,
822 &zero_filler_path,
823 &temporary_directory,
824 &mut next_temporary_image_id,
825 &mut indirect_files,
826 )
827 })
828 .collect::<Result<Vec<DiskFile>, _>>()?;
829
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700830 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
831
Jaewan Kimf43372b2024-12-13 18:33:58 +0900832 let (vfio_devices, dtbo) = match &config.devices {
833 AssignedDevices::Devices(devices) if !devices.is_empty() => {
834 let mut set = HashSet::new();
835 for device in devices.iter() {
836 let path = canonicalize(device)
837 .with_context(|| format!("can't canonicalize {device}"))
838 .or_service_specific_exception(-1)?;
839 if !set.insert(path) {
840 return Err(anyhow!("duplicated device {device}"))
841 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
842 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900843 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900844 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
845 let dtbo_file = File::from(
846 GLOBAL_SERVICE
847 .getDtboFile()?
848 .as_ref()
849 .try_clone()
850 .context("Failed to create VM DTBO from ParcelFileDescriptor")
851 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
852 );
853 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900854 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900855 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900856 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900857 let display_config = if cfg!(paravirtualized_devices) {
858 config
859 .displayConfig
860 .as_ref()
861 .map(DisplayConfig::new)
862 .transpose()
863 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
864 } else {
865 None
866 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700867 let gpu_config = if cfg!(paravirtualized_devices) {
868 config
869 .gpuConfig
870 .as_ref()
871 .map(GpuConfig::new)
872 .transpose()
873 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
874 } else {
875 None
876 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900877
Jeongik Chac181be72024-03-27 00:18:30 +0900878 let input_device_options = if cfg!(paravirtualized_devices) {
879 config
880 .inputDevices
881 .iter()
882 .map(to_input_device_option_from)
883 .collect::<Result<Vec<InputDeviceOption>, _>>()
884 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
885 } else {
886 vec![]
887 };
888
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900889 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900890 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900891 if *is_protected {
892 return Err(anyhow!("Network feature is not supported for pVM yet"))
893 .with_log()
894 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
895 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900896 Some(File::from(
897 GLOBAL_SERVICE
898 .createTapInterface(&get_this_pid().to_string())?
899 .as_ref()
900 .try_clone()
901 .context("Failed to get TAP interface from ParcelFileDescriptor")
902 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
903 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900904 } else {
905 None
906 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800907
908 let audio_config = if cfg!(paravirtualized_devices) {
909 config.audioConfig.as_ref().map(AudioConfig::new)
910 } else {
911 None
912 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900913
Elie Kheirallah29d72912024-08-07 20:17:26 +0000914 let usb_config = config
915 .usbConfig
916 .as_ref()
917 .map(UsbConfig::new)
918 .unwrap_or(Ok(UsbConfig { controller: false }))
919 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
920
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000921 let detect_hangup = is_app_config && gdb_port.is_none();
922
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800923 let custom_memory_backing_files = config
924 .customMemoryBackingFiles
925 .iter()
926 .map(|memory_backing_file| {
927 Ok((
928 clone_file(
929 memory_backing_file
930 .file
931 .as_ref()
932 .context("missing CustomMemoryBackingFile FD")
933 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
934 )?
935 .into(),
936 memory_backing_file.rangeStart as u64,
937 memory_backing_file.size as u64,
938 ))
939 })
940 .collect::<binder::Result<_>>()?;
941
Yuan Yao3843ea22025-02-27 06:22:20 +0000942 let memory_reclaim_supported =
943 system_properties::read_bool("hypervisor.memory_reclaim.supported", false)
944 .unwrap_or(false);
945
946 let balloon = config.balloon && memory_reclaim_supported;
947
948 if !balloon {
949 warn!(
950 "Memory balloon not enabled:
951 config.balloon={},hypervisor.memory_reclaim.supported={}",
952 config.balloon, memory_reclaim_supported
953 );
954 }
955
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000956 // Actually start the VM.
957 let crosvm_config = CrosvmConfig {
958 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000959 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000960 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000961 kernel,
962 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000963 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700964 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000965 params: config.params.to_owned(),
966 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900967 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700968 memory_mib: config
969 .memoryMib
970 .try_into()
971 .ok()
972 .and_then(NonZeroU32::new)
973 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800974 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000975 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900976 console_out_fd,
977 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000978 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900979 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000980 indirect_files,
981 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000982 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000983 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900984 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000985 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900986 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900987 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900988 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000989 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900990 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800991 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000992 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700993 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800994 audio_config,
Yuan Yao3843ea22025-02-27 06:22:20 +0000995 balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000996 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000997 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800998 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
999 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -08001000 custom_memory_backing_files,
Nikita Ioffecaff2822025-03-18 13:43:14 +00001001 start_suspended: !vendor_tee_services.is_empty(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001002 };
1003 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +01001004 VmInstance::new(
1005 crosvm_config,
1006 temporary_directory,
1007 requester_uid,
1008 requester_debug_pid,
1009 vm_context,
Nikita Ioffecaff2822025-03-18 13:43:14 +00001010 vendor_tee_services,
David Brazdil528e0472022-10-10 15:06:02 +01001011 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001012 .with_context(|| format!("Failed to create VM with config {:?}", config))
1013 .with_log()
1014 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001015 );
1016 state.add_vm(Arc::downgrade(&instance));
1017 Ok(VirtualMachine::create(instance))
1018 }
Jiyong Park8611a6c2021-07-09 18:17:44 +09001019}
1020
Alan Stokesfda70842023-12-20 17:50:14 +00001021/// Returns whether a VM config represents a "custom" virtual machine, which requires the
1022/// USE_CUSTOM_VIRTUAL_MACHINE.
1023fn is_custom_config(config: &VirtualMachineConfig) -> bool {
1024 match config {
1025 // Any raw (non-Microdroid) VM is considered custom.
1026 VirtualMachineConfig::RawConfig(_) => true,
1027 VirtualMachineConfig::AppConfig(config) => {
1028 // Some features are reserved for platform apps only, even when using
1029 // VirtualMachineAppConfig. Almost all of these features are grouped in the
1030 // CustomConfig struct:
1031 // - controlling CPUs;
1032 // - gdbPort is set, meaning that crosvm will start a gdb server;
1033 // - using anything other than the default kernel;
1034 // - specifying devices to be assigned.
1035 if config.customConfig.is_some() {
1036 true
1037 } else {
1038 // Additional custom features not included in CustomConfig:
1039 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +00001040 // - specifying extra APKs;
1041 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +09001042 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +00001043 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +09001044 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
1045 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +00001046 }
1047 }
1048 }
1049}
1050
Jiyong Park690c1ca2024-11-28 18:06:50 +09001051/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
1052/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
1053/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
1054/// "microdroid" we run VirtualMachineService
1055fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
1056 match config {
1057 VirtualMachineConfig::AppConfig(_) => true,
1058 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
1059 }
1060}
1061
Jiyong Park18ceddc2025-03-18 13:30:02 +09001062/// Returns the name of the config
1063fn get_name(config: &VirtualMachineConfig) -> &str {
1064 match config {
1065 VirtualMachineConfig::AppConfig(config) => &config.name,
1066 VirtualMachineConfig::RawConfig(config) => &config.name,
1067 }
1068}
1069
Seungjae Yoo14e60182024-02-21 13:28:31 +09001070fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
1071 let VirtualMachineConfig::AppConfig(config) = config else {
1072 return Ok(None);
1073 };
1074 let Some(custom_config) = &config.customConfig else {
1075 return Ok(None);
1076 };
1077 let Some(file) = custom_config.vendorImage.as_ref() else {
1078 return Ok(None);
1079 };
1080
1081 let file = clone_file(file)?;
1082 let size =
1083 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1084 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1085 .context("Failed to get vbmeta from microdroid-vendor.img")?;
1086
1087 for descriptor in vbmeta.descriptors()?.iter() {
1088 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1089 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1090 return Ok(Some(root_digest.as_bytes().to_vec()));
1091 }
1092 }
1093 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1094}
1095
Jaewan Kimf43372b2024-12-13 18:33:58 +09001096fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001097 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001098 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001099 temporary_directory: &Path,
1100) -> binder::Result<Option<File>> {
1101 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1102 // (e.g. instance-id)
1103 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1104 let host_ref_dt = if host_ref_dt.exists()
1105 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1106 {
1107 Some(host_ref_dt)
1108 } else {
1109 warn!("VM reference DT doesn't exist in host DT");
1110 None
1111 };
1112
1113 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1114 .context("Failed to extract vendor hashtree digest")
1115 .or_service_specific_exception(-1)?;
1116
Matt Gilbrideaade4272024-12-05 13:52:42 +00001117 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001118 info!(
1119 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1120 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1121 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001122 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001123 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001124 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001125 };
1126
Matt Gilbrideaade4272024-12-05 13:52:42 +00001127 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001128 let mut untrusted_props = Vec::with_capacity(2);
1129 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001130 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001131 let want_updatable = extract_want_updatable(config);
1132 if want_updatable && is_secretkeeper_supported() {
1133 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1134 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001135 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001136 let sk: Strong<dyn ISecretkeeper> =
1137 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1138 if sk.getInterfaceVersion()? >= 2 {
1139 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1140 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001141 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001142 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001143 }
1144 }
1145
1146 let device_tree_overlay = if host_ref_dt.is_some()
1147 || !untrusted_props.is_empty()
1148 || !trusted_props.is_empty()
1149 {
1150 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1151 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1152 let fdt =
1153 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1154 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1155 .or_service_specific_exception(-1)?;
1156 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1157 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1158 } else {
1159 None
1160 };
1161 Ok(device_tree_overlay)
1162}
1163
Jaewan Kimf43372b2024-12-13 18:33:58 +09001164fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1165 let VirtualMachineConfig::RawConfig(config) = config else {
1166 return None;
1167 };
1168 match &config.devices {
1169 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1170 _ => None,
1171 }
1172}
1173
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001174fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001175 let file = OpenOptions::new()
1176 .create_new(true)
1177 .read(true)
1178 .write(true)
1179 .open(zero_filler_path)
1180 .with_context(|| "Failed to create zero.img")?;
1181 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001182 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001183}
1184
David Brazdilf50c7a62023-04-19 14:22:42 +00001185fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1186 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1187 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1188 part.flush()
1189}
1190
1191fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1192 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1193 part.flush()
1194}
1195
1196fn round_up(input: u64, granularity: u64) -> u64 {
1197 if granularity == 0 {
1198 return input;
1199 }
1200 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1201 let result = input.checked_add(granularity - 1).unwrap_or(input);
1202 (result / granularity) * granularity
1203}
1204
Jeongik Chac181be72024-03-27 00:18:30 +09001205fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1206 Ok(match input_device {
1207 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1208 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1209 height: u32::try_from(single_touch.height)?,
1210 width: u32::try_from(single_touch.width)?,
1211 name: if !single_touch.name.is_empty() {
1212 Some(single_touch.name.clone())
1213 } else {
1214 None
1215 },
1216 },
1217 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1218 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1219 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001220 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1221 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1222 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001223 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1224 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1225 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001226 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1227 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1228 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001229 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1230 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1231 height: u32::try_from(trackpad.height)?,
1232 width: u32::try_from(trackpad.width)?,
1233 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1234 },
Jeongik Cha10494912024-07-16 11:19:50 +09001235 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1236 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1237 height: u32::try_from(multi_touch.height)?,
1238 width: u32::try_from(multi_touch.width)?,
1239 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1240 },
Jeongik Chac181be72024-03-27 00:18:30 +09001241 })
1242}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001243
1244fn assemble_shared_paths(
1245 shared_paths: &[SharedPath],
1246 temporary_directory: &Path,
1247) -> Result<Vec<SharedPathConfig>, Status> {
1248 if shared_paths.is_empty() {
1249 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1250 }
1251
1252 shared_paths
1253 .iter()
1254 .map(|path| {
1255 Ok(SharedPathConfig {
1256 path: path.sharedPath.clone(),
1257 host_uid: path.hostUid,
1258 host_gid: path.hostGid,
1259 guest_uid: path.guestUid,
1260 guest_gid: path.guestGid,
1261 mask: path.mask,
1262 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001263 socket_path: temporary_directory
1264 .join(&path.socketPath)
1265 .to_string_lossy()
1266 .to_string(),
1267 socket_fd: maybe_clone_file(&path.socketFd)?,
1268 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001269 })
1270 })
1271 .collect()
1272}
1273
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001274/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1275///
1276/// This may involve assembling a composite disk from a set of partition images.
1277fn assemble_disk_image(
1278 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001279 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001280 temporary_directory: &Path,
1281 next_temporary_image_id: &mut u64,
1282 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001283) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001284 let image = if !disk.partitions.is_empty() {
1285 if disk.image.is_some() {
1286 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001287 return Err(anyhow!("DiskImage contains both image and partitions"))
1288 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001289 }
1290
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001291 let composite_image_filenames =
1292 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1293 let (image, partition_files) = make_composite_image(
1294 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001295 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001296 &composite_image_filenames.composite,
1297 &composite_image_filenames.header,
1298 &composite_image_filenames.footer,
1299 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001300 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1301 .with_log()
1302 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001303
1304 // Pass the file descriptors for the various partition files to crosvm when it
1305 // is run.
1306 indirect_files.extend(partition_files);
1307
1308 image
1309 } else if let Some(image) = &disk.image {
1310 clone_file(image)?
1311 } else {
1312 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001313 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1314 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001315 };
1316
1317 Ok(DiskFile { image, writable: disk.writable })
1318}
1319
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001320fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1321 if let Some(ref mut params) = vm_config.params {
1322 params.push(' ');
1323 params.push_str(param)
1324 } else {
1325 vm_config.params = Some(param.to_owned())
1326 }
1327}
1328
Inseob Kim46257382024-01-03 15:41:22 +09001329fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1330 if config.extension()?.to_str()? != "json" {
1331 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001332 }
Inseob Kim46257382024-01-03 15:41:22 +09001333
1334 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1335}
1336
1337fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1338 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1339 let os_names =
1340 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1341
1342 Ok(os_names)
1343}
1344
1345fn get_supported_os_names() -> Result<HashSet<String>> {
1346 if !cfg!(vendor_modules) {
1347 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1348 }
1349
1350 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1351}
1352
1353fn is_valid_os(os_name: &str) -> bool {
1354 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001355}
1356
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001357fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1358 if !cfg!(vendor_modules) {
1359 return false;
1360 }
1361 match config {
1362 VirtualMachineConfig::RawConfig(_) => false,
1363 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1364 }
1365}
1366
Jooyung Han21e9b922021-06-26 04:14:16 +09001367fn load_app_config(
1368 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001369 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001370 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001371) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001372 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1373 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001374 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001375
Shikha Panwar22e70452022-10-10 18:32:55 +00001376 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1377 Some(clone_file(file)?)
1378 } else {
1379 None
1380 };
1381
Alan Stokesfda70842023-12-20 17:50:14 +00001382 let vm_payload_config;
1383 let extra_apk_files: Vec<_>;
1384 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001385 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001386 vm_payload_config =
1387 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1388 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1389 extra_apk_files = vm_payload_config
1390 .extra_apks
1391 .iter()
1392 .enumerate()
1393 .map(|(i, apk)| {
1394 File::open(PathBuf::from(&apk.path))
1395 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1396 })
1397 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001398 }
Alan Stokesfda70842023-12-20 17:50:14 +00001399 Payload::PayloadConfig(payload_config) => {
1400 vm_payload_config = create_vm_payload_config(payload_config)?;
1401 extra_apk_files =
1402 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1403 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001404 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001405
Inseob Kim89b24592024-02-23 18:59:43 +09001406 let payload_config_os = vm_payload_config.os.name.as_str();
1407 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1408 bail!("'os' in payload config is deprecated");
1409 }
1410
Inseob Kim172f9eb2023-11-06 17:02:08 +09001411 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001412 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001413 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001414 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001415 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001416
1417 // It is safe to construct a filename based on the os_name because we've already checked that it
1418 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001419 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1420 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001421 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001422
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001423 if let Some(custom_config) = &config.customConfig {
1424 if let Some(file) = custom_config.customKernelImage.as_ref() {
1425 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1426 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001427 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001428
1429 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001430 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001431 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001432 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001433
Jaewan Kimf43372b2024-12-13 18:33:58 +09001434 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001435 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001436
1437 for param in custom_config.extraKernelCmdlineParams.iter() {
1438 append_kernel_param(param, &mut vm_config);
1439 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001440
1441 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001442 }
1443
Andrew Walbrancc045902021-07-27 16:06:17 +00001444 if config.memoryMib > 0 {
1445 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001446 }
1447
Chris Wailes6177c662024-05-09 14:37:44 -07001448 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001449 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001450 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001451 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001452 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001453
Shikha Panwar22e70452022-10-10 18:32:55 +00001454 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001455 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001456
1457 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1458 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001459 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001460 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001461 temporary_directory,
1462 apk_file,
1463 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001464 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001465 &vm_payload_config,
1466 &mut vm_config,
1467 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001468
Andrew Walbrancc0db522021-07-12 17:03:42 +00001469 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001470}
1471
Frederick Mayle3a46b272025-02-10 21:55:49 -08001472fn check_partition_for_file(
1473 fd: &ParcelFileDescriptor,
1474 calling_partition: CallingPartition,
1475) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001476 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
Inseob Kim4d414452025-03-04 16:17:47 +09001477 let link = fs::read_link(&path).with_context(|| format!("can't read_link {path}"))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001478
1479 // microdroid vendor image is OK
1480 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1481 {
1482 return Ok(());
1483 }
1484
Inseob Kim4d414452025-03-04 16:17:47 +09001485 let fd_partition = find_partition(Some(&link))
1486 .with_context(|| format!("can't find_partition {}", link.display()))?;
1487 let is_fd_vendor =
1488 fd_partition == CallingPartition::Vendor || fd_partition == CallingPartition::Odm;
Frederick Mayle3a46b272025-02-10 21:55:49 -08001489 let is_caller_vendor =
1490 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001491
1492 if is_fd_vendor != is_caller_vendor {
1493 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001494 }
1495
1496 Ok(())
1497}
1498
Inseob Kime3e932d2024-12-16 20:06:57 +09001499fn check_partitions_for_files(
1500 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001501 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001502) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001503 config
1504 .disks
1505 .iter()
1506 .flat_map(|disk| disk.partitions.iter())
1507 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001508 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001509
Inseob Kime3e932d2024-12-16 20:06:57 +09001510 config
1511 .disks
1512 .iter()
1513 .filter_map(|disk| disk.image.as_ref())
1514 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1515
1516 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1517 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1518 config
1519 .bootloader
1520 .as_ref()
1521 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001522
1523 Ok(())
1524}
1525
Alan Stokes0d1ef782022-09-27 13:46:35 +01001526fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1527 let mut apk_zip = ZipArchive::new(apk_file)?;
1528 let config_file = apk_zip.by_name(config_path)?;
1529 Ok(serde_json::from_reader(config_file)?)
1530}
1531
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001532fn create_vm_payload_config(
1533 payload_config: &VirtualMachinePayloadConfig,
1534) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001535 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1536 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1537 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001538
1539 let payload_binary_name = &payload_config.payloadBinaryName;
1540 if payload_binary_name.contains('/') {
1541 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1542 }
1543
1544 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001545
1546 // The VM only cares about how many there are, these names are actually ignored.
1547 let extra_apk_count = payload_config.extraApks.len();
1548 let extra_apks =
1549 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1550
Nikita Ioffe901083f2025-01-20 01:54:28 +00001551 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1552 // The only payload delivered via Mainline module in this release requires
1553 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1554 // APIs, so we use the fact that the payload is granted
1555 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1556 // com.android.i18n APEX.
1557 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1558 // Microdroid pVMs.
1559 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1560 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1561 } else {
1562 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1563 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001564}
1565
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001566/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001567fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001568 temporary_directory: &Path,
1569 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001570) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001571 let id = *next_temporary_image_id;
1572 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001573 CompositeImageFilenames {
1574 composite: temporary_directory.join(format!("composite-{}.img", id)),
1575 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1576 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1577 }
1578}
1579
1580/// Filenames for a composite disk image, including header and footer partitions.
1581#[derive(Clone, Debug, Eq, PartialEq)]
1582struct CompositeImageFilenames {
1583 /// The composite disk image itself.
1584 composite: PathBuf,
1585 /// The header partition image.
1586 header: PathBuf,
1587 /// The footer partition image.
1588 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001589}
1590
Jiyong Park753553b2021-07-12 21:21:09 +09001591/// Checks whether the caller has a specific permission
1592fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001593 if cfg!(early) {
1594 // Skip permission check for early VMs, in favor of SELinux
1595 return Ok(());
1596 }
David Brazdil1f530702022-10-03 12:18:10 +01001597 let calling_pid = get_calling_pid();
1598 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001599 // Root can do anything
1600 if calling_uid == 0 {
1601 return Ok(());
1602 }
1603 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001604 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001605 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001606 Ok(())
1607 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001608 Err(anyhow!("does not have the {} permission", perm))
1609 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001610 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001611}
1612
Jiyong Park753553b2021-07-12 21:21:09 +09001613/// Check whether the caller of the current Binder method is allowed to manage VMs
1614fn check_manage_access() -> binder::Result<()> {
1615 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1616}
1617
Inseob Kim1119d702022-05-02 18:01:58 +09001618/// Check whether the caller of the current Binder method is allowed to create custom VMs
1619fn check_use_custom_virtual_machine() -> binder::Result<()> {
1620 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1621}
1622
Nikita Ioffe901083f2025-01-20 01:54:28 +00001623/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1624/// rollback protection schema.
1625fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1626 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1627}
1628
Alan Stokes185fe112023-01-10 16:20:55 +00001629/// Return whether a partition is exempt from selinux label checks, because we know that it does
1630/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001631fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001632 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001633 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001634 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001635 || label == "microdroid-apk-idsig"
1636 || label == "payload-metadata"
1637 || label.starts_with("extra-idsig-")
1638}
1639
Alice Wangc206b9b2023-08-28 14:13:51 +00001640/// Returns whether a partition with the given label is safe for a raw config VM.
1641fn is_safe_raw_partition(label: &str) -> bool {
1642 label == "vm-instance"
1643}
1644
Alan Stokes185fe112023-01-10 16:20:55 +00001645/// Check that a file SELinux label is acceptable.
1646///
1647/// 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 +09001648/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001649///
1650/// Note that sepolicy must also grant read access for these types to both virtualization
1651/// service and crosvm.
1652///
1653/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1654/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001655fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001656 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001657 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001658 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001659 | "staging_data_file" // updated/staged APEX images
1660 | "system_file" // immutable dm-verity protected partition
1661 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001662 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001663 => Ok(()),
Frederick Maylec8f27042025-02-26 12:35:26 -08001664 // It is difficult to require specific label types for vendor initiated VM's files.
1665 _ if calling_partition == CallingPartition::Vendor => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001666 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001667 }
1668}
1669
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001670fn check_label_for_partition(
1671 partition: &Partition,
1672 calling_partition: CallingPartition,
1673) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001674 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001675 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001676 .with_context(|| format!("Partition {} invalid", &partition.label))
1677}
1678
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001679fn check_label_for_kernel_files(
1680 kernel: &Option<File>,
1681 initrd: &Option<File>,
1682 calling_partition: CallingPartition,
1683) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001684 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001685 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001686 }
1687 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001688 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001689 }
1690 Ok(())
1691}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001692fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001693 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001694 name: &str,
1695 calling_partition: CallingPartition,
1696) -> Result<()> {
1697 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1698 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001699}
1700
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001701/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1702#[derive(Debug)]
1703struct VirtualMachine {
1704 instance: Arc<VmInstance>,
1705}
1706
1707impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001708 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001709 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001710 }
Nikita Ioffecaff2822025-03-18 13:43:14 +00001711
1712 fn handle_vendor_tee_services(&self) -> binder::Result<()> {
1713 // TODO(b/360102915): get vm_fd from crosvm
1714 // TODO(b/360102915): talk to HAL
1715 self.instance
1716 .resume_full()
1717 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1718 .with_log()
1719 .or_service_specific_exception(-1)
1720 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001721}
1722
1723impl Interface for VirtualMachine {}
1724
Devin Moore407df8f2024-08-27 19:39:16 +00001725impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001726 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001727 // Don't check permission. The owner of the VM might have passed this binder object to
1728 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001729 Ok(self.instance.cid as i32)
1730 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001731
Andrew Walbran6b650662021-09-07 13:13:23 +00001732 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001733 // Don't check permission. The owner of the VM might have passed this binder object to
1734 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001735 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001736 }
1737
1738 fn registerCallback(
1739 &self,
1740 callback: &Strong<dyn IVirtualMachineCallback>,
1741 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001742 // Don't check permission. The owner of the VM might have passed this binder object to
1743 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001744
1745 // Only register callback if it may be notified.
1746 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1747 let vm_state = self.instance.vm_state.lock().unwrap();
1748 if matches!(*vm_state, VmState::Dead) {
1749 warn!("Ignoring registerCallback() after VM is died");
1750 } else {
1751 self.instance.callbacks.add(callback.clone());
1752 }
1753 drop(vm_state);
1754
Andrew Walbrandae07162021-03-12 17:05:20 +00001755 Ok(())
1756 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001757
Andrew Walbranf8d94112021-09-07 11:45:36 +00001758 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001759 self.instance
1760 .start()
1761 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1762 .with_log()
Nikita Ioffecaff2822025-03-18 13:43:14 +00001763 .or_service_specific_exception(-1)?;
1764 if !self.instance.vendor_tee_services.is_empty() {
1765 self.handle_vendor_tee_services()
1766 } else {
1767 Ok(())
1768 }
Andrew Walbranf8d94112021-09-07 11:45:36 +00001769 }
1770
Inseob Kima446f802022-07-11 19:46:37 +09001771 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001772 self.instance
1773 .kill()
1774 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1775 .with_log()
1776 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001777 }
1778
Yuan Yao3843ea22025-02-27 06:22:20 +00001779 fn isMemoryBalloonEnabled(&self) -> binder::Result<bool> {
1780 Ok(self.instance.balloon_enabled)
1781 }
1782
Keir Fraser48221ba2024-07-12 14:05:02 +00001783 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1784 let balloon = self
1785 .instance
1786 .get_memory_balloon()
1787 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1788 .with_log()
1789 .or_service_specific_exception(-1)?;
1790 Ok(balloon.try_into().unwrap())
1791 }
1792
1793 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001794 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001795 .set_memory_balloon(num_bytes.try_into().unwrap())
1796 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001797 .with_log()
1798 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001799 }
1800
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001801 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001802 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001803 return Err(Status::new_service_specific_error_str(
1804 IVirtualMachine::ERROR_UNEXPECTED,
1805 Some("Virtual Machine is not running"),
1806 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001807 }
Alan Stokes10c47672022-12-13 17:17:08 +00001808 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001809 if port < VSOCK_PRIV_PORT_MAX {
1810 return Err(Status::new_service_specific_error_str(
1811 IVirtualMachine::ERROR_UNEXPECTED,
1812 Some("Can't connect to privileged port {port}"),
1813 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001814 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001815 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1816 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001817 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001818 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001819 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001820
Devin Moore407df8f2024-08-27 19:39:16 +00001821 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1822 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1823 return Err(Status::new_service_specific_error_str(
1824 IVirtualMachine::ERROR_UNEXPECTED,
1825 Some("Virtual Machine is not running"),
1826 ));
1827 }
1828 let port = port as u32;
1829 if port < VSOCK_PRIV_PORT_MAX {
1830 return Err(Status::new_service_specific_error_str(
1831 IVirtualMachine::ERROR_UNEXPECTED,
1832 Some("Can't connect to privileged port {port}"),
1833 ));
1834 }
1835 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001836 let addr = sockaddr_vm {
1837 svm_family: AF_VSOCK as sa_family_t,
1838 svm_reserved1: 0,
1839 svm_port: port,
1840 svm_cid: cid,
1841 svm_zero: [0u8; 4],
1842 };
1843 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001844 let accessor = Accessor::new(name, get_connection_info);
1845 accessor
1846 .as_binder()
1847 .context("The newly created Accessor should always have a binder")
1848 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1849 }
1850
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001851 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1852 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1853 }
Jiyong Park23b67392024-07-04 13:51:42 +09001854
1855 fn suspend(&self) -> binder::Result<()> {
1856 self.instance
1857 .suspend()
1858 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1859 .with_log()
1860 .or_service_specific_exception(-1)
1861 }
1862
1863 fn resume(&self) -> binder::Result<()> {
1864 self.instance
1865 .resume()
1866 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1867 .with_log()
1868 .or_service_specific_exception(-1)
1869 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001870}
1871
1872impl Drop for VirtualMachine {
1873 fn drop(&mut self) {
1874 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001875 if let Err(e) = self.instance.kill() {
1876 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1877 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001878 }
1879}
1880
1881/// A set of Binders to be called back in response to various events on the VM, such as when it
1882/// dies.
1883#[derive(Debug, Default)]
1884pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1885
1886impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001887 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001888 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001889 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001890 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001891 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001892 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001893 }
1894 }
1895 }
1896
Inseob Kim14cb8692021-08-31 21:50:39 +09001897 /// Call all registered callbacks to notify that the payload is ready to serve.
1898 pub fn notify_payload_ready(&self, cid: Cid) {
1899 let callbacks = &*self.0.lock().unwrap();
1900 for callback in callbacks {
1901 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001902 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001903 }
1904 }
1905 }
1906
Inseob Kim2444af92021-08-31 01:22:50 +09001907 /// Call all registered callbacks to notify that the payload has finished.
1908 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1909 let callbacks = &*self.0.lock().unwrap();
1910 for callback in callbacks {
1911 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001912 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001913 }
1914 }
1915 }
1916
Jooyung Handd0a1732021-11-23 15:26:20 +09001917 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001918 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001919 let callbacks = &*self.0.lock().unwrap();
1920 for callback in callbacks {
1921 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001922 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001923 }
1924 }
1925 }
1926
Andrew Walbrandae07162021-03-12 17:05:20 +00001927 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001928 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001929 let mut callbacks = self.0.lock().unwrap();
1930 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001931 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001932 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001933 }
1934 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001935
1936 // Nothing to notify afterward because VM cannot be restarted.
1937 // Explicitly clear callbacks to prevent potential cyclic references
1938 // between callback and VmInstance.
1939 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001940 }
1941
1942 /// Add a new callback to the set.
1943 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1944 self.0.lock().unwrap().push(callback);
1945 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001946}
1947
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001948/// The mutable state of the VirtualizationService. There should only be one instance of this
1949/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001950#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001951struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001952 /// The VMs which have been started. When VMs are started a weak reference is added to this
1953 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1954 /// the Binder client are dropped the weak reference here will become invalid, and will be
1955 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001956 vms: Vec<Weak<VmInstance>>,
1957}
1958
1959impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001960 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001961 fn vms(&self) -> Vec<Arc<VmInstance>> {
1962 // Attempt to upgrade the weak pointers to strong pointers.
1963 self.vms.iter().filter_map(Weak::upgrade).collect()
1964 }
1965
1966 /// Add a new VM to the list.
1967 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1968 // Garbage collect any entries from the stored list which no longer exist.
1969 self.vms.retain(|vm| vm.strong_count() > 0);
1970
1971 // Actually add the new VM.
1972 self.vms.push(vm);
1973 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001974
Jiyong Park8611a6c2021-07-09 18:17:44 +09001975 /// Get a VM that corresponds to the given cid
1976 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1977 self.vms().into_iter().find(|vm| vm.cid == cid)
1978 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001979}
1980
Andrew Walbran6b650662021-09-07 13:13:23 +00001981/// Gets the `VirtualMachineState` of the given `VmInstance`.
1982fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001983 match &*instance.vm_state.lock().unwrap() {
1984 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1985 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001986 PayloadState::Starting => VirtualMachineState::STARTING,
1987 PayloadState::Started => VirtualMachineState::STARTED,
1988 PayloadState::Ready => VirtualMachineState::READY,
1989 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001990 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001991 },
1992 VmState::Dead => VirtualMachineState::DEAD,
1993 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001994 }
1995}
1996
David Brazdilf50c7a62023-04-19 14:22:42 +00001997/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001998pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1999 file.as_ref()
2000 .try_clone()
2001 .context("Failed to clone File from ParcelFileDescriptor")
2002 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00002003 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00002004}
2005
Andrew Walbrand3a84182021-09-07 14:48:52 +00002006/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002007fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00002008 file.as_ref().map(clone_file).transpose()
2009}
2010
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002011/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09002012fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
2013 // SAFETY: ownership is transferred from stream to f
2014 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
2015 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002016}
2017
Jiyong Parkdcf17412022-02-08 15:07:23 +09002018/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002019fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
2020 VersionReq::parse(s)
2021 .with_context(|| format!("Invalid platform version requirement {}", s))
2022 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09002023}
2024
Jiyong Parked180932023-02-24 19:55:41 +09002025/// Create the empty ramdump file
2026fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
2027 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
2028 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
2029 // owner) for readout.
2030 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09002031 let ramdump = File::create(ramdump_path)
2032 .context("Failed to prepare ramdump file")
2033 .with_log()
2034 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09002035 Ok(ramdump)
2036}
2037
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01002038/// Create the empty device tree dump file
2039fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
2040 let path = temporary_directory.join("device_tree.dtb");
2041 let file = File::create(path)
2042 .context("Failed to prepare device tree dump file")
2043 .with_log()
2044 .or_service_specific_exception(-1)?;
2045 Ok(file)
2046}
2047
Nikita Ioffe5776f082023-02-10 21:38:26 +00002048fn is_protected(config: &VirtualMachineConfig) -> bool {
2049 match config {
2050 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
2051 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
2052 }
2053}
2054
2055fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
2056 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09002057 return Err(anyhow!("Can't use gdb with protected VMs"))
2058 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002059 }
2060
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002061 if get_debug_level(config) == Some(DebugLevel::NONE) {
2062 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
2063 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002064 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002065
2066 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00002067}
2068
Shikha Panwar61a74b52024-02-16 13:17:01 +00002069fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
2070 match config {
2071 VirtualMachineConfig::RawConfig(config) => config.instanceId,
2072 VirtualMachineConfig::AppConfig(config) => config.instanceId,
2073 }
2074}
2075
Alan Stokesc96b35e2024-05-03 13:21:20 +01002076fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
2077 match config {
2078 VirtualMachineConfig::RawConfig(_) => true,
2079 VirtualMachineConfig::AppConfig(config) => {
2080 let Some(custom) = &config.customConfig else { return true };
2081 custom.wantUpdatable
2082 }
2083 }
2084}
2085
Nikita Ioffe5776f082023-02-10 21:38:26 +00002086fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
2087 match config {
2088 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01002089 VirtualMachineConfig::AppConfig(config) => {
2090 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
2091 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00002092 }
2093}
2094
Nikita Ioffe631717e2023-09-05 13:38:07 +01002095fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2096 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2097 if let Some(custom_config) = &config.customConfig {
2098 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2099 return Err(anyhow!("vendor modules feature is disabled"))
2100 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2101 }
2102 }
2103 Ok(())
2104}
2105
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002106fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2107 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2108 if let Some(custom_config) = &config.customConfig {
2109 if !custom_config.devices.is_empty() {
2110 return Err(anyhow!("device assignment feature is disabled"))
2111 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2112 }
2113 }
2114 Ok(())
2115}
2116
Alan Stokesfda70842023-12-20 17:50:14 +00002117fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2118 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2119 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2120 if !payload_config.extraApks.is_empty() {
2121 return Err(anyhow!("multi-tenant feature is disabled"))
2122 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2123 }
2124 Ok(())
2125}
2126
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002127fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2128 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2129 if let Some(custom_config) = &config.customConfig {
2130 if !custom_config.extraKernelCmdlineParams.is_empty() {
2131 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2132 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2133 }
2134 }
2135 Ok(())
2136}
2137
Nikita Ioffe99548382024-10-21 15:54:46 +00002138fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2139 match config {
2140 VirtualMachineConfig::RawConfig(config) => {
2141 if !config.teeServices.is_empty() {
2142 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2143 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2144 }
2145 }
2146 VirtualMachineConfig::AppConfig(config) => {
2147 if let Some(custom_config) = &config.customConfig {
2148 if !custom_config.teeServices.is_empty() {
2149 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2150 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2151 }
2152 }
2153 }
2154 };
2155 Ok(())
2156}
2157
Nikita Ioffef934e812024-07-05 15:44:41 +00002158fn check_protected_vm_is_supported() -> binder::Result<()> {
2159 let is_pvm_supported =
2160 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2161 if is_pvm_supported {
2162 Ok(())
2163 } else {
2164 Err(anyhow!("pVM is not supported"))
2165 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2166 }
2167}
2168
Nikita Ioffe631717e2023-09-05 13:38:07 +01002169fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2170 if !cfg!(vendor_modules) {
2171 check_no_vendor_modules(config)?;
2172 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002173 if !cfg!(device_assignment) {
2174 check_no_devices(config)?;
2175 }
Alan Stokesfda70842023-12-20 17:50:14 +00002176 if !cfg!(multi_tenant) {
2177 check_no_extra_apks(config)?;
2178 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002179 if !cfg!(debuggable_vms_improvements) {
2180 check_no_extra_kernel_cmdline_params(config)?;
2181 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002182 if !cfg!(tee_services_allowlist) {
2183 check_no_tee_services(config)?;
2184 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002185 Ok(())
2186}
2187
Inseob Kimecde8c02024-09-03 13:11:08 +09002188fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2189 check_no_vendor_modules(config)?;
2190 check_no_devices(config)?;
2191
2192 Ok(())
2193}
2194
Inseob Kim0168b462022-12-27 14:54:35 +09002195fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002196 fd: Option<&ParcelFileDescriptor>,
2197 tag: String,
2198) -> Result<Option<File>, Status> {
2199 if let Some(fd) = fd {
2200 return Ok(Some(clone_file(fd)?));
2201 }
2202
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002203 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002204 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002205
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002206 let mut reader = BufReader::new(File::from(read_fd));
2207 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002208
Frederick Mayle26e41af2025-02-05 18:30:29 -08002209 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002210 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002211 buf.clear();
2212 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002213 match reader.read_until(b'\n', &mut buf) {
2214 Ok(0) => {
2215 // EOF
2216 return;
2217 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002218 Ok(_size) => {
2219 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002220 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002221 // Logs sent via TTY usually end lines with "\r\n".
2222 if buf.last() == Some(&b'\r') {
2223 buf.pop();
2224 }
Inseob Kim0168b462022-12-27 14:54:35 +09002225 }
2226 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2227 }
2228 Err(e) => {
2229 error!("Could not read console pipe: {:?}", e);
2230 return;
2231 }
2232 };
2233 });
2234
2235 Ok(Some(write_fd))
2236}
2237
Jooyung Han35edb8f2021-07-01 16:17:16 +09002238/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2239/// it doesn't require that T implements Clone.
2240enum BorrowedOrOwned<'a, T> {
2241 Borrowed(&'a T),
2242 Owned(T),
2243}
2244
Chris Wailes73a1eb72025-01-15 11:56:43 -08002245impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002246 fn as_ref(&self) -> &T {
2247 match self {
2248 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002249 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002250 }
2251 }
2252}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002253
2254/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2255#[derive(Debug, Default)]
2256struct VirtualMachineService {
2257 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002258 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002259}
2260
2261impl Interface for VirtualMachineService {}
2262
2263impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002264 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2265 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002266 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002267 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002268 vm.update_payload_state(PayloadState::Started)
2269 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002270 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002271
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002272 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2273 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002274 Ok(())
2275 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002276 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002277 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002278 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002279 }
Inseob Kim2444af92021-08-31 01:22:50 +09002280
Inseob Kimc7d28c72021-10-25 14:28:10 +00002281 fn notifyPayloadReady(&self) -> binder::Result<()> {
2282 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002283 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002284 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002285 vm.update_payload_state(PayloadState::Ready)
2286 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002287 vm.callbacks.notify_payload_ready(cid);
2288 Ok(())
2289 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002290 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002291 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002292 }
2293 }
2294
Inseob Kimc7d28c72021-10-25 14:28:10 +00002295 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2296 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002297 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002298 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002299 vm.update_payload_state(PayloadState::Finished)
2300 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002301 vm.callbacks.notify_payload_finished(cid, exit_code);
2302 Ok(())
2303 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002304 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002305 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002306 }
2307 }
2308
Alan Stokes2bead0d2022-09-05 16:58:34 +01002309 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002310 let cid = self.cid;
2311 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002312 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002313 vm.update_payload_state(PayloadState::Finished)
2314 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002315 vm.callbacks.notify_error(cid, error_code, message);
2316 Ok(())
2317 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002318 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002319 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002320 }
2321 }
Alice Wangc2fec932023-02-23 16:24:02 +00002322
Shikha Panware45e9422024-02-28 21:18:10 +00002323 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2324 if !is_secretkeeper_supported() {
2325 return Err(StatusCode::NAME_NOT_FOUND)?;
2326 }
2327 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2328 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002329 }
2330
Alice Wange64dd182024-01-17 15:57:55 +00002331 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2332 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002333 }
Shikha Panwareeae6402025-02-06 19:05:31 +00002334
2335 fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2336 GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2337 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002338}
2339
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002340fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002341 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2342 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002343}
2344
Nikita Ioffe832410f2025-03-07 15:24:44 +00002345fn is_vm_capabilities_hal_supported() -> bool {
2346 binder::is_declared(VM_CAPABILITIES_HAL_IDENTIFIER)
2347 .expect("failed to check if {VM_CAPABILITIES_HAL_IDENTIFIER} is present")
2348}
2349
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002350impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002351 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002352 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002353 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002354 BinderFeatures::default(),
2355 )
2356 }
2357}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002358
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002359struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2360
2361impl Interface for SecretkeeperProxy {}
2362
2363impl ISecretkeeper for SecretkeeperProxy {
2364 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2365 // Pass the request to the channel, and read the response.
2366 self.0.processSecretManagementRequest(req)
2367 }
2368
2369 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2370 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2371 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2372 }
2373
2374 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2375 self.0.deleteIds(ids)
2376 }
2377
2378 fn deleteAll(&self) -> binder::Result<()> {
2379 self.0.deleteAll()
2380 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002381
2382 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2383 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2384 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2385 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2386 // use this API from the proxy.
2387 Err(ExceptionCode::SECURITY.into())
2388 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002389}
2390
2391struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2392
2393impl Interface for AuthGraphKeyExchangeProxy {}
2394
2395impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2396 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2397 self.0.create()
2398 }
2399
2400 fn init(
2401 &self,
2402 peer_pub_key: &PubKey,
2403 peer_id: &Identity,
2404 peer_nonce: &[u8],
2405 peer_version: i32,
2406 ) -> binder::Result<KeInitResult> {
2407 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2408 }
2409
2410 fn finish(
2411 &self,
2412 peer_pub_key: &PubKey,
2413 peer_id: &Identity,
2414 peer_signature: &SessionIdSignature,
2415 peer_nonce: &[u8],
2416 peer_version: i32,
2417 own_key: &Key,
2418 ) -> binder::Result<SessionInfo> {
2419 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2420 }
2421
2422 fn authenticationComplete(
2423 &self,
2424 peer_signature: &SessionIdSignature,
2425 shared_keys: &[AuthgraphArc; 2],
2426 ) -> binder::Result<[AuthgraphArc; 2]> {
2427 self.0.authenticationComplete(peer_signature, shared_keys)
2428 }
2429}
2430
Inseob Kimecde8c02024-09-03 13:11:08 +09002431// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002432#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002433struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002434 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002435 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002436 path: String,
2437}
2438
2439#[derive(Debug, Default, Deserialize)]
2440struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002441 early_vm: Vec<EarlyVm>,
2442}
2443
Alice Wang78dd87a2025-02-13 08:56:07 +00002444impl EarlyVm {
2445 /// Verifies that the provided executable path matches the expected path stored in the XML
2446 /// configuration.
2447 /// If the provided path starts with `/system`, it will be stripped before comparison.
2448 fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2449 let actual_path = calling_exe_path.as_ref();
2450 if Path::new(&self.path)
2451 == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2452 {
2453 return Ok(());
2454 }
2455 Err(Status::new_service_specific_error_str(
2456 -1,
2457 Some(format!(
2458 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2459 self.name,
2460 self.path,
2461 actual_path.display()
2462 )),
2463 ))
2464 }
2465}
2466
Frederick Mayle3a46b272025-02-10 21:55:49 -08002467static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002468 LazyLock::new(|| Mutex::new(HashMap::new()));
2469
Frederick Mayle3a46b272025-02-10 21:55:49 -08002470fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002471 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002472 CallingPartition::System => 100..200,
2473 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2474 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2475 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002476 }
2477}
2478
Inseob Kim7e1877b2024-11-07 17:28:56 +09002479fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002480 if !xml_path.exists() {
2481 bail!("{} doesn't exist", xml_path.display());
2482 }
2483
2484 let xml =
2485 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2486 let xml = String::from_utf8(xml)
2487 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2488 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2489 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2490
Inseob Kim7e1877b2024-11-07 17:28:56 +09002491 Ok(early_vms.early_vm)
2492}
Inseob Kimecde8c02024-09-03 13:11:08 +09002493
Inseob Kim7e1877b2024-11-07 17:28:56 +09002494fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2495 for early_vm in early_vms {
2496 let cid = early_vm
2497 .cid
2498 .try_into()
2499 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2500
2501 ensure!(
2502 cid_range.contains(&cid),
2503 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2504 early_vm.name
2505 );
2506 }
2507 Ok(())
2508}
2509
Frederick Mayle3a46b272025-02-10 21:55:49 -08002510fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002511 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2512
Frederick Mayle3a46b272025-02-10 21:55:49 -08002513 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002514 return Ok(result.clone());
2515 }
2516
2517 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2518 let mut early_vms = Vec::new();
2519 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2520 match entry {
2521 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2522 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2523 }
2524 }
2525
Frederick Mayle3a46b272025-02-10 21:55:49 -08002526 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002527 .with_context(|| format!("CID validation for {partition} failed"))?;
2528
Frederick Mayle3a46b272025-02-10 21:55:49 -08002529 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002530
2531 Ok(early_vms)
2532}
2533
2534fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2535 let mut found_vm: Option<&EarlyVm> = None;
2536
2537 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002538 if early_vm.name != name {
2539 continue;
2540 }
2541
Inseob Kimecde8c02024-09-03 13:11:08 +09002542 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002543 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002544 }
2545
2546 found_vm = Some(early_vm);
2547 }
2548
Inseob Kim7e1877b2024-11-07 17:28:56 +09002549 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002550}
2551
Frederick Mayle3a46b272025-02-10 21:55:49 -08002552fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002553 let early_vms = get_early_vms_in_partition(partition)
2554 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2555
2556 Ok(find_early_vm(&early_vms, name)
2557 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2558 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002559}
2560
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002561#[cfg(test)]
2562mod tests {
2563 use super::*;
2564
2565 #[test]
2566 fn test_is_allowed_label_for_partition() -> Result<()> {
2567 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002568 (CallingPartition::System, "u:object_r:system_file:s0", true),
2569 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2570 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2571 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2572 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2573 (CallingPartition::System, "invalid", false),
2574 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2575 (
2576 CallingPartition::System,
2577 "user:role:apk_data_file:severity:categories:extraneous",
2578 false,
2579 ),
2580 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2581 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002582 ];
2583
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002584 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002585 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002586 let result = check_label_is_allowed(&context, calling_partition);
2587 if expected_valid != result.is_ok() {
2588 bail!(
2589 "Expected label {label} to be {} for {calling_partition} partition",
2590 if expected_valid { "allowed" } else { "disallowed" }
2591 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002592 }
2593 }
2594 Ok(())
2595 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002596
2597 #[test]
2598 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2599 let apk = tempfile::tempfile().unwrap();
2600 let idsig = tempfile::tempfile().unwrap();
2601
2602 let ret = create_or_update_idsig_file(
2603 &ParcelFileDescriptor::new(apk),
2604 &ParcelFileDescriptor::new(idsig),
2605 );
2606 assert!(ret.is_err(), "should fail");
2607 Ok(())
2608 }
2609
2610 #[test]
2611 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2612 let tmp_dir = tempfile::TempDir::new().unwrap();
2613 let apk = File::open(tmp_dir.path()).unwrap();
2614 let idsig = tempfile::tempfile().unwrap();
2615
2616 let ret = create_or_update_idsig_file(
2617 &ParcelFileDescriptor::new(apk),
2618 &ParcelFileDescriptor::new(idsig),
2619 );
2620 assert!(ret.is_err(), "should fail");
2621 Ok(())
2622 }
2623
2624 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2625 /// on ext4 filesystem is passed.
2626 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2627 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2628 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2629 #[test]
2630 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2631 // APEXes are backed by the ext4.
2632 let apk = File::open("/apex/com.android.virt/").unwrap();
2633 let idsig = tempfile::tempfile().unwrap();
2634
2635 let ret = create_or_update_idsig_file(
2636 &ParcelFileDescriptor::new(apk),
2637 &ParcelFileDescriptor::new(idsig),
2638 );
2639 assert!(ret.is_err(), "should fail");
2640 Ok(())
2641 }
Jiyong Park8d192952023-06-26 14:29:51 +09002642
2643 #[test]
2644 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2645 use std::io::Seek;
2646
2647 // Pick any APK
2648 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2649 let mut idsig = tempfile::tempfile().unwrap();
2650
2651 create_or_update_idsig_file(
2652 &ParcelFileDescriptor::new(apk.try_clone()?),
2653 &ParcelFileDescriptor::new(idsig.try_clone()?),
2654 )?;
2655 let modified_orig = idsig.metadata()?.modified()?;
2656 apk.rewind()?;
2657 idsig.rewind()?;
2658
2659 // Call the function again
2660 create_or_update_idsig_file(
2661 &ParcelFileDescriptor::new(apk.try_clone()?),
2662 &ParcelFileDescriptor::new(idsig.try_clone()?),
2663 )?;
2664 let modified_new = idsig.metadata()?.modified()?;
2665 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2666 Ok(())
2667 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002668
2669 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002670 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2671 use std::io::Read;
2672
2673 // Pick any APK
2674 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2675 let idsig_empty = tempfile::tempfile().unwrap();
2676 let mut idsig_invalid = tempfile::tempfile().unwrap();
2677 idsig_invalid.write_all(b"Oops")?;
2678
2679 // Create new idsig
2680 create_or_update_idsig_file(
2681 &ParcelFileDescriptor::new(apk.try_clone()?),
2682 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2683 )?;
2684 apk.rewind()?;
2685
2686 // Update idsig_invalid
2687 create_or_update_idsig_file(
2688 &ParcelFileDescriptor::new(apk.try_clone()?),
2689 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2690 )?;
2691
2692 // Ensure the 2 idsig files have same size!
2693 assert!(
2694 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2695 "idsig files differ in size"
2696 );
2697 // Ensure the 2 idsig files have same content!
2698 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2699 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2700 }
2701 Ok(())
2702 }
2703 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002704 fn test_append_kernel_param_first_param() {
2705 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2706 append_kernel_param("foo=1", &mut vm_config);
2707 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2708 }
2709
2710 #[test]
2711 fn test_append_kernel_param() {
2712 let mut vm_config =
2713 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2714 append_kernel_param("bar=42", &mut vm_config);
2715 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2716 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002717
Inseob Kim46257382024-01-03 15:41:22 +09002718 fn test_extract_os_name_from_config_path(
2719 path: &Path,
2720 expected_result: Option<&str>,
2721 ) -> Result<()> {
2722 let result = extract_os_name_from_config_path(path);
2723 if result.as_deref() != expected_result {
2724 bail!("Expected {:?} but was {:?}", expected_result, &result)
2725 }
2726 Ok(())
2727 }
2728
2729 #[test]
2730 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2731 test_extract_os_name_from_config_path(
2732 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2733 Some("microdroid"),
2734 )
2735 }
2736
2737 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002738 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2739 test_extract_os_name_from_config_path(
2740 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2741 Some("microdroid_16k"),
2742 )
2743 }
2744
2745 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002746 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2747 test_extract_os_name_from_config_path(
2748 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2749 Some("microdroid_gki-android14-6.1"),
2750 )
2751 }
2752
2753 #[test]
2754 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2755 test_extract_os_name_from_config_path(
2756 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2757 None,
2758 )
2759 }
2760
2761 #[test]
2762 fn test_extract_os_name_from_configs() -> Result<()> {
2763 let tmp_dir = tempfile::TempDir::new()?;
2764 let tmp_dir_path = tmp_dir.path().to_owned();
2765
2766 let mut os_names: HashSet<String> = HashSet::new();
2767 os_names.insert("microdroid".to_owned());
2768 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2769 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2770
2771 // config files
2772 for os_name in &os_names {
2773 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2774 }
2775
2776 // fake files not related to configs
2777 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2778 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2779
2780 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2781 Some(s) => s.to_owned(),
2782 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2783 };
2784
2785 let result = extract_os_names_from_configs(&glob_pattern)?;
2786 if result != os_names {
2787 bail!("Expected {:?} but was {:?}", os_names, result);
2788 }
2789 Ok(())
2790 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002791
2792 #[test]
2793 fn test_find_early_vms_from_xml() -> Result<()> {
2794 let tmp_dir = tempfile::TempDir::new()?;
2795 let tmp_dir_path = tmp_dir.path().to_owned();
2796 let xml_path = tmp_dir_path.join("early_vms.xml");
2797
2798 std::fs::write(
2799 &xml_path,
2800 br#"<?xml version="1.0" encoding="utf-8"?>
2801 <early_vms>
2802 <early_vm>
2803 <name>vm_demo_native_early</name>
2804 <cid>123</cid>
2805 <path>/system/bin/vm_demo_native_early</path>
2806 </early_vm>
2807 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002808 <name>vm_demo_native_early_2</name>
2809 <cid>456</cid>
2810 <path>/system/bin/vm_demo_native_early_2</path>
2811 </early_vm>
2812 </early_vms>
2813 "#,
2814 )?;
2815
2816 let cid_range = 100..1000;
2817
2818 let early_vms = get_early_vms_in_path(&xml_path)?;
2819 validate_cid_range(&early_vms, &cid_range)?;
2820
2821 let test_cases = [
2822 (
2823 "vm_demo_native_early",
2824 EarlyVm {
2825 name: "vm_demo_native_early".to_owned(),
2826 cid: 123,
2827 path: "/system/bin/vm_demo_native_early".to_owned(),
2828 },
2829 ),
2830 (
2831 "vm_demo_native_early_2",
2832 EarlyVm {
2833 name: "vm_demo_native_early_2".to_owned(),
2834 cid: 456,
2835 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2836 },
2837 ),
2838 ];
2839
2840 for (name, expected) in test_cases {
2841 let result = find_early_vm(&early_vms, name)?;
2842 assert_eq!(result, &expected);
2843 }
2844
2845 Ok(())
2846 }
2847
2848 #[test]
2849 fn test_invalid_cid_validation() -> Result<()> {
2850 let tmp_dir = tempfile::TempDir::new()?;
2851 let xml_path = tmp_dir.path().join("early_vms.xml");
2852
2853 let cid_range = 100..1000;
2854
2855 for cid in [-1, 999999] {
2856 std::fs::write(
2857 &xml_path,
2858 format!(
2859 r#"<?xml version="1.0" encoding="utf-8"?>
2860 <early_vms>
2861 <early_vm>
2862 <name>vm_demo_invalid_cid</name>
2863 <cid>{cid}</cid>
2864 <path>/system/bin/vm_demo_invalid_cid</path>
2865 </early_vm>
2866 </early_vms>
2867 "#
2868 ),
2869 )?;
2870
2871 let early_vms = get_early_vms_in_path(&xml_path)?;
2872 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2873 }
2874
2875 Ok(())
2876 }
2877
2878 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002879 fn test_symlink_to_system_ext_supported() -> Result<()> {
2880 let link_path = Path::new("/system/system_ext/file");
2881 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002882 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002883 Ok(())
2884 }
2885
2886 #[test]
2887 fn test_symlink_to_product_supported() -> Result<()> {
2888 let link_path = Path::new("/system/product/file");
2889 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002890 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002891 Ok(())
2892 }
2893
2894 #[test]
Frederick Mayle2192baf2025-02-26 11:27:22 -08002895 fn test_vendor_in_data() {
2896 assert_eq!(
2897 CallingPartition::Vendor,
2898 find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap()
2899 );
2900 }
2901
2902 #[test]
Alice Wang78dd87a2025-02-13 08:56:07 +00002903 fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2904 let early_vm = EarlyVm {
2905 name: "vm_demo_native_early".to_owned(),
2906 cid: 123,
2907 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2908 };
2909 let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2910 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2911 }
2912
2913 #[test]
2914 fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2915 let early_vm = EarlyVm {
2916 name: "vm_demo_native_early".to_owned(),
2917 cid: 123,
2918 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2919 };
2920 let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2921 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2922 }
2923
2924 #[test]
2925 fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2926 let early_vm = EarlyVm {
2927 name: "vm_demo_native_early".to_owned(),
2928 cid: 123,
2929 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2930 };
2931 let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2932 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2933 }
2934
2935 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002936 fn test_duplicated_early_vms() -> Result<()> {
2937 let tmp_dir = tempfile::TempDir::new()?;
2938 let tmp_dir_path = tmp_dir.path().to_owned();
2939 let xml_path = tmp_dir_path.join("early_vms.xml");
2940
2941 std::fs::write(
2942 &xml_path,
2943 br#"<?xml version="1.0" encoding="utf-8"?>
2944 <early_vms>
2945 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002946 <name>vm_demo_duplicated_name</name>
2947 <cid>456</cid>
2948 <path>/system/bin/vm_demo_duplicated_name_1</path>
2949 </early_vm>
2950 <early_vm>
2951 <name>vm_demo_duplicated_name</name>
2952 <cid>789</cid>
2953 <path>/system/bin/vm_demo_duplicated_name_2</path>
2954 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002955 </early_vms>
2956 "#,
2957 )?;
2958
2959 let cid_range = 100..1000;
2960
Inseob Kim7e1877b2024-11-07 17:28:56 +09002961 let early_vms = get_early_vms_in_path(&xml_path)?;
2962 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002963
Inseob Kim7e1877b2024-11-07 17:28:56 +09002964 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002965
2966 Ok(())
2967 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002968}