blob: 161a534ad123febeac383ab5ee5ef8b8e6238ac1 [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
Frederick Mayle01dff422025-02-13 16:52:06 -0800647 let instance_id = extract_instance_id(config);
648 // Require vendor instance IDs to start with a specific prefix so that they don't conflict
649 // with system instance IDs.
650 //
651 // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
652 // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
653 // for now, we only check in one direction.
654 const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
655 if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
656 && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
657 {
658 return Err(anyhow!(
659 "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
660 hex::encode(instance_id)
661 ))
662 .or_service_specific_exception(-1);
663 }
664
Nikita Ioffe631717e2023-09-05 13:38:07 +0100665 check_config_features(config)?;
666
Inseob Kimecde8c02024-09-03 13:11:08 +0900667 if cfg!(early) {
668 check_config_allowed_for_early_vms(config)?;
669 }
670
Nikita Ioffeb1416122024-10-22 12:18:49 +0000671 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
672 info!("callers secontext: {}", caller_secontext);
673
David Brazdil209074a2023-01-12 16:44:51 +0000674 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900675 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800676 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900677 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900678 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900679 };
Inseob Kim1119d702022-05-02 18:01:58 +0900680
Alan Stokesfda70842023-12-20 17:50:14 +0000681 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100682 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900683 }
684
Nikita Ioffe5776f082023-02-10 21:38:26 +0000685 let gdb_port = extract_gdb_port(config);
686
687 // Additional permission checks if caller request gdb.
688 if gdb_port.is_some() {
689 check_gdb_allowed(config)?;
690 }
691
Jaewan Kimf43372b2024-12-13 18:33:58 +0900692 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800693 if let Some(dt_overlay) =
694 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
695 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900696 device_tree_overlays.push(dt_overlay);
697 }
698 if let Some(dtbo) = get_dtbo(config) {
699 let dtbo = File::from(
700 dtbo.as_ref()
701 .try_clone()
702 .context("Failed to create VM DTBO from ParcelFileDescriptor")
703 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
704 );
705 device_tree_overlays.push(dtbo);
706 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900707
Jaewan Kimf3143242024-03-15 06:56:31 +0000708 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000709 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900710 Some(prepare_ramdump_file(&temporary_directory)?)
711 } else {
712 None
713 };
714
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000715 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900716 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100717 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900718 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100719 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100720 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
721 Some(clone_file(fd)?)
722 } else if debug_config.dump_device_tree {
723 Some(prepare_dump_dt_file(&temporary_directory)?)
724 } else {
725 None
726 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000727
728 // Counter to generate unique IDs for temporary image files.
729 let mut next_temporary_image_id = 0;
730 // Files which are referred to from composite images. These must be mapped to the crosvm
731 // child process, and not closed before it is started.
732 let mut indirect_files = vec![];
733
Alan Stokes7bc146c2022-10-20 17:10:32 +0100734 let (is_app_config, config) = match config {
735 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
736 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900737 let config = load_app_config(config, &debug_config, &temporary_directory)
738 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900739 *is_protected = config.protectedVm;
740 let message = format!("Failed to load app config: {:?}", e);
741 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900742 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900743 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100744 (true, BorrowedOrOwned::Owned(config))
745 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000746 };
747 let config = config.as_ref();
748 *is_protected = config.protectedVm;
749
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000750 if !config.teeServices.is_empty() {
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000751 if !config.protectedVm {
752 return Err(anyhow!("only protected VMs can request tee services"))
753 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
754 }
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000755 check_tee_service_permission(&caller_secontext, &config.teeServices)
756 .with_log()
757 .or_binder_exception(ExceptionCode::SECURITY)?;
758 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000759
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000760 let mut system_tee_services = Vec::new();
761 let mut vendor_tee_services = Vec::new();
762 for tee_service in config.teeServices.clone() {
763 if !tee_service.starts_with("vendor.") {
764 check_known_tee_service(&tee_service)?;
765 system_tee_services.push(tee_service);
766 } else {
767 vendor_tee_services.push(tee_service);
768 }
769 }
770
Nikita Ioffecaff2822025-03-18 13:43:14 +0000771 if !vendor_tee_services.is_empty() && !is_vm_capabilities_hal_supported() {
772 return Err(anyhow!(
773 "requesting access to tee services requires {VM_CAPABILITIES_HAL_IDENTIFIER}"
774 ))
775 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000776 }
777
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000778 // TODO(b/391774181): remove this check in a follow-up patch.
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000779 if !system_tee_services.is_empty() {
780 return Err(anyhow!("support for system tee services is coming soon!"))
781 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
782 }
783
Jiyong Park3051ffe2024-11-26 14:41:58 +0900784 let kernel = maybe_clone_file(&config.kernel)?;
785 let initrd = maybe_clone_file(&config.initrd)?;
786
787 if config.protectedVm {
788 // Fail fast with a meaningful error message in case device doesn't support pVMs.
789 check_protected_vm_is_supported()?;
790
791 // In a protected VM, we require custom kernels to come from a trusted source
792 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800793 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
794 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900795
796 // Check if partition images are labeled incorrectly. This is to prevent random images
797 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
798 // from being loaded in a pVM. This applies to everything but the instance image in the
799 // raw config, and everything but the non-executable, generated partitions in the app
800 // config.
801 config
802 .disks
803 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800804 .flat_map(|disk| disk.image.as_ref())
805 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
806 .or_service_specific_exception(-1)?;
807 config
808 .disks
809 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900810 .flat_map(|disk| disk.partitions.iter())
811 .filter(|partition| {
812 if is_app_config {
813 !is_safe_app_partition(&partition.label)
814 } else {
815 !is_safe_raw_partition(&partition.label)
816 }
817 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800818 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900819 .or_service_specific_exception(-1)?;
820 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000821
Frederick Mayle279783a2025-03-18 16:16:45 -0700822 // Check if files for payloads and bases are on the same side of the Treble boundary as the
823 // calling process, as they may have unstable interfaces.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800824 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900825
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000826 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900827 write_zero_filler(&zero_filler_path)
828 .context("Failed to make composite image")
829 .with_log()
830 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000831
832 // Assemble disk images if needed.
833 let disks = config
834 .disks
835 .iter()
836 .map(|disk| {
837 assemble_disk_image(
838 disk,
839 &zero_filler_path,
840 &temporary_directory,
841 &mut next_temporary_image_id,
842 &mut indirect_files,
843 )
844 })
845 .collect::<Result<Vec<DiskFile>, _>>()?;
846
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700847 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
848
Jaewan Kimf43372b2024-12-13 18:33:58 +0900849 let (vfio_devices, dtbo) = match &config.devices {
850 AssignedDevices::Devices(devices) if !devices.is_empty() => {
851 let mut set = HashSet::new();
852 for device in devices.iter() {
853 let path = canonicalize(device)
854 .with_context(|| format!("can't canonicalize {device}"))
855 .or_service_specific_exception(-1)?;
856 if !set.insert(path) {
857 return Err(anyhow!("duplicated device {device}"))
858 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
859 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900860 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900861 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
862 let dtbo_file = File::from(
863 GLOBAL_SERVICE
864 .getDtboFile()?
865 .as_ref()
866 .try_clone()
867 .context("Failed to create VM DTBO from ParcelFileDescriptor")
868 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
869 );
870 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900871 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900872 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900873 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900874 let display_config = if cfg!(paravirtualized_devices) {
875 config
876 .displayConfig
877 .as_ref()
878 .map(DisplayConfig::new)
879 .transpose()
880 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
881 } else {
882 None
883 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700884 let gpu_config = if cfg!(paravirtualized_devices) {
885 config
886 .gpuConfig
887 .as_ref()
888 .map(GpuConfig::new)
889 .transpose()
890 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
891 } else {
892 None
893 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900894
Jeongik Chac181be72024-03-27 00:18:30 +0900895 let input_device_options = if cfg!(paravirtualized_devices) {
896 config
897 .inputDevices
898 .iter()
899 .map(to_input_device_option_from)
900 .collect::<Result<Vec<InputDeviceOption>, _>>()
901 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
902 } else {
903 vec![]
904 };
905
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900906 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900907 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900908 if *is_protected {
909 return Err(anyhow!("Network feature is not supported for pVM yet"))
910 .with_log()
911 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
912 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900913 Some(File::from(
914 GLOBAL_SERVICE
915 .createTapInterface(&get_this_pid().to_string())?
916 .as_ref()
917 .try_clone()
918 .context("Failed to get TAP interface from ParcelFileDescriptor")
919 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
920 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900921 } else {
922 None
923 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800924
925 let audio_config = if cfg!(paravirtualized_devices) {
926 config.audioConfig.as_ref().map(AudioConfig::new)
927 } else {
928 None
929 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900930
Elie Kheirallah29d72912024-08-07 20:17:26 +0000931 let usb_config = config
932 .usbConfig
933 .as_ref()
934 .map(UsbConfig::new)
935 .unwrap_or(Ok(UsbConfig { controller: false }))
936 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
937
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000938 let detect_hangup = is_app_config && gdb_port.is_none();
939
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800940 let custom_memory_backing_files = config
941 .customMemoryBackingFiles
942 .iter()
943 .map(|memory_backing_file| {
944 Ok((
945 clone_file(
946 memory_backing_file
947 .file
948 .as_ref()
949 .context("missing CustomMemoryBackingFile FD")
950 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
951 )?
952 .into(),
953 memory_backing_file.rangeStart as u64,
954 memory_backing_file.size as u64,
955 ))
956 })
957 .collect::<binder::Result<_>>()?;
958
Yuan Yao3843ea22025-02-27 06:22:20 +0000959 let memory_reclaim_supported =
960 system_properties::read_bool("hypervisor.memory_reclaim.supported", false)
961 .unwrap_or(false);
962
963 let balloon = config.balloon && memory_reclaim_supported;
964
965 if !balloon {
966 warn!(
967 "Memory balloon not enabled:
968 config.balloon={},hypervisor.memory_reclaim.supported={}",
969 config.balloon, memory_reclaim_supported
970 );
971 }
972
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000973 // Actually start the VM.
974 let crosvm_config = CrosvmConfig {
975 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000976 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000977 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000978 kernel,
979 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000980 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700981 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000982 params: config.params.to_owned(),
983 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900984 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700985 memory_mib: config
986 .memoryMib
987 .try_into()
988 .ok()
989 .and_then(NonZeroU32::new)
990 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800991 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000992 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900993 console_out_fd,
994 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000995 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900996 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000997 indirect_files,
998 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000999 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +00001000 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +09001001 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +00001002 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +09001003 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +09001004 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +09001005 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001006 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +09001007 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +08001008 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +00001009 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -07001010 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +08001011 audio_config,
Yuan Yao3843ea22025-02-27 06:22:20 +00001012 balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +00001013 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +00001014 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001015 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
1016 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -08001017 custom_memory_backing_files,
Nikita Ioffecaff2822025-03-18 13:43:14 +00001018 start_suspended: !vendor_tee_services.is_empty(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001019 };
1020 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +01001021 VmInstance::new(
1022 crosvm_config,
1023 temporary_directory,
1024 requester_uid,
1025 requester_debug_pid,
1026 vm_context,
Nikita Ioffecaff2822025-03-18 13:43:14 +00001027 vendor_tee_services,
David Brazdil528e0472022-10-10 15:06:02 +01001028 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001029 .with_context(|| format!("Failed to create VM with config {:?}", config))
1030 .with_log()
1031 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001032 );
1033 state.add_vm(Arc::downgrade(&instance));
1034 Ok(VirtualMachine::create(instance))
1035 }
Jiyong Park8611a6c2021-07-09 18:17:44 +09001036}
1037
Alan Stokesfda70842023-12-20 17:50:14 +00001038/// Returns whether a VM config represents a "custom" virtual machine, which requires the
1039/// USE_CUSTOM_VIRTUAL_MACHINE.
1040fn is_custom_config(config: &VirtualMachineConfig) -> bool {
1041 match config {
1042 // Any raw (non-Microdroid) VM is considered custom.
1043 VirtualMachineConfig::RawConfig(_) => true,
1044 VirtualMachineConfig::AppConfig(config) => {
1045 // Some features are reserved for platform apps only, even when using
1046 // VirtualMachineAppConfig. Almost all of these features are grouped in the
1047 // CustomConfig struct:
1048 // - controlling CPUs;
1049 // - gdbPort is set, meaning that crosvm will start a gdb server;
1050 // - using anything other than the default kernel;
1051 // - specifying devices to be assigned.
1052 if config.customConfig.is_some() {
1053 true
1054 } else {
1055 // Additional custom features not included in CustomConfig:
1056 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +00001057 // - specifying extra APKs;
1058 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +09001059 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +00001060 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +09001061 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
1062 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +00001063 }
1064 }
1065 }
1066}
1067
Jiyong Park690c1ca2024-11-28 18:06:50 +09001068/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
1069/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
1070/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
1071/// "microdroid" we run VirtualMachineService
1072fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
1073 match config {
1074 VirtualMachineConfig::AppConfig(_) => true,
1075 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
1076 }
1077}
1078
Jiyong Park18ceddc2025-03-18 13:30:02 +09001079/// Returns the name of the config
1080fn get_name(config: &VirtualMachineConfig) -> &str {
1081 match config {
1082 VirtualMachineConfig::AppConfig(config) => &config.name,
1083 VirtualMachineConfig::RawConfig(config) => &config.name,
1084 }
1085}
1086
Seungjae Yoo14e60182024-02-21 13:28:31 +09001087fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
1088 let VirtualMachineConfig::AppConfig(config) = config else {
1089 return Ok(None);
1090 };
1091 let Some(custom_config) = &config.customConfig else {
1092 return Ok(None);
1093 };
1094 let Some(file) = custom_config.vendorImage.as_ref() else {
1095 return Ok(None);
1096 };
1097
1098 let file = clone_file(file)?;
1099 let size =
1100 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1101 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1102 .context("Failed to get vbmeta from microdroid-vendor.img")?;
1103
1104 for descriptor in vbmeta.descriptors()?.iter() {
1105 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1106 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1107 return Ok(Some(root_digest.as_bytes().to_vec()));
1108 }
1109 }
1110 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1111}
1112
Jaewan Kimf43372b2024-12-13 18:33:58 +09001113fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001114 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001115 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001116 temporary_directory: &Path,
1117) -> binder::Result<Option<File>> {
1118 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1119 // (e.g. instance-id)
1120 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1121 let host_ref_dt = if host_ref_dt.exists()
1122 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1123 {
1124 Some(host_ref_dt)
1125 } else {
1126 warn!("VM reference DT doesn't exist in host DT");
1127 None
1128 };
1129
1130 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1131 .context("Failed to extract vendor hashtree digest")
1132 .or_service_specific_exception(-1)?;
1133
Matt Gilbrideaade4272024-12-05 13:52:42 +00001134 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001135 info!(
1136 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1137 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1138 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001139 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001140 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001141 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001142 };
1143
Matt Gilbrideaade4272024-12-05 13:52:42 +00001144 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001145 let mut untrusted_props = Vec::with_capacity(2);
1146 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001147 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001148 let want_updatable = extract_want_updatable(config);
1149 if want_updatable && is_secretkeeper_supported() {
1150 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1151 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001152 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001153 let sk: Strong<dyn ISecretkeeper> =
1154 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1155 if sk.getInterfaceVersion()? >= 2 {
1156 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1157 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001158 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001159 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001160 }
1161 }
1162
1163 let device_tree_overlay = if host_ref_dt.is_some()
1164 || !untrusted_props.is_empty()
1165 || !trusted_props.is_empty()
1166 {
1167 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1168 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1169 let fdt =
1170 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1171 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1172 .or_service_specific_exception(-1)?;
1173 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1174 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1175 } else {
1176 None
1177 };
1178 Ok(device_tree_overlay)
1179}
1180
Jaewan Kimf43372b2024-12-13 18:33:58 +09001181fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1182 let VirtualMachineConfig::RawConfig(config) = config else {
1183 return None;
1184 };
1185 match &config.devices {
1186 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1187 _ => None,
1188 }
1189}
1190
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001191fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001192 let file = OpenOptions::new()
1193 .create_new(true)
1194 .read(true)
1195 .write(true)
1196 .open(zero_filler_path)
1197 .with_context(|| "Failed to create zero.img")?;
1198 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001199 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001200}
1201
David Brazdilf50c7a62023-04-19 14:22:42 +00001202fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1203 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1204 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1205 part.flush()
1206}
1207
1208fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1209 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1210 part.flush()
1211}
1212
1213fn round_up(input: u64, granularity: u64) -> u64 {
1214 if granularity == 0 {
1215 return input;
1216 }
1217 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1218 let result = input.checked_add(granularity - 1).unwrap_or(input);
1219 (result / granularity) * granularity
1220}
1221
Jeongik Chac181be72024-03-27 00:18:30 +09001222fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1223 Ok(match input_device {
1224 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1225 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1226 height: u32::try_from(single_touch.height)?,
1227 width: u32::try_from(single_touch.width)?,
1228 name: if !single_touch.name.is_empty() {
1229 Some(single_touch.name.clone())
1230 } else {
1231 None
1232 },
1233 },
1234 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1235 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1236 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001237 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1238 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1239 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001240 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1241 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1242 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001243 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1244 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1245 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001246 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1247 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1248 height: u32::try_from(trackpad.height)?,
1249 width: u32::try_from(trackpad.width)?,
1250 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1251 },
Jeongik Cha10494912024-07-16 11:19:50 +09001252 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1253 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1254 height: u32::try_from(multi_touch.height)?,
1255 width: u32::try_from(multi_touch.width)?,
1256 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1257 },
Jeongik Chac181be72024-03-27 00:18:30 +09001258 })
1259}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001260
1261fn assemble_shared_paths(
1262 shared_paths: &[SharedPath],
1263 temporary_directory: &Path,
1264) -> Result<Vec<SharedPathConfig>, Status> {
1265 if shared_paths.is_empty() {
1266 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1267 }
1268
1269 shared_paths
1270 .iter()
1271 .map(|path| {
1272 Ok(SharedPathConfig {
1273 path: path.sharedPath.clone(),
1274 host_uid: path.hostUid,
1275 host_gid: path.hostGid,
1276 guest_uid: path.guestUid,
1277 guest_gid: path.guestGid,
1278 mask: path.mask,
1279 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001280 socket_path: temporary_directory
1281 .join(&path.socketPath)
1282 .to_string_lossy()
1283 .to_string(),
1284 socket_fd: maybe_clone_file(&path.socketFd)?,
1285 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001286 })
1287 })
1288 .collect()
1289}
1290
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001291/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1292///
1293/// This may involve assembling a composite disk from a set of partition images.
1294fn assemble_disk_image(
1295 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001296 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001297 temporary_directory: &Path,
1298 next_temporary_image_id: &mut u64,
1299 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001300) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001301 let image = if !disk.partitions.is_empty() {
1302 if disk.image.is_some() {
1303 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001304 return Err(anyhow!("DiskImage contains both image and partitions"))
1305 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001306 }
1307
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001308 let composite_image_filenames =
1309 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1310 let (image, partition_files) = make_composite_image(
1311 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001312 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001313 &composite_image_filenames.composite,
1314 &composite_image_filenames.header,
1315 &composite_image_filenames.footer,
1316 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001317 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1318 .with_log()
1319 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001320
1321 // Pass the file descriptors for the various partition files to crosvm when it
1322 // is run.
1323 indirect_files.extend(partition_files);
1324
1325 image
1326 } else if let Some(image) = &disk.image {
1327 clone_file(image)?
1328 } else {
1329 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001330 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1331 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001332 };
1333
1334 Ok(DiskFile { image, writable: disk.writable })
1335}
1336
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001337fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1338 if let Some(ref mut params) = vm_config.params {
1339 params.push(' ');
1340 params.push_str(param)
1341 } else {
1342 vm_config.params = Some(param.to_owned())
1343 }
1344}
1345
Inseob Kim46257382024-01-03 15:41:22 +09001346fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1347 if config.extension()?.to_str()? != "json" {
1348 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001349 }
Inseob Kim46257382024-01-03 15:41:22 +09001350
1351 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1352}
1353
1354fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1355 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1356 let os_names =
1357 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1358
1359 Ok(os_names)
1360}
1361
1362fn get_supported_os_names() -> Result<HashSet<String>> {
1363 if !cfg!(vendor_modules) {
1364 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1365 }
1366
1367 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1368}
1369
1370fn is_valid_os(os_name: &str) -> bool {
1371 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001372}
1373
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001374fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1375 if !cfg!(vendor_modules) {
1376 return false;
1377 }
1378 match config {
1379 VirtualMachineConfig::RawConfig(_) => false,
1380 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1381 }
1382}
1383
Jooyung Han21e9b922021-06-26 04:14:16 +09001384fn load_app_config(
1385 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001386 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001387 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001388) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001389 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1390 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001391 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001392
Shikha Panwar22e70452022-10-10 18:32:55 +00001393 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1394 Some(clone_file(file)?)
1395 } else {
1396 None
1397 };
1398
Alan Stokesfda70842023-12-20 17:50:14 +00001399 let vm_payload_config;
1400 let extra_apk_files: Vec<_>;
1401 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001402 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001403 vm_payload_config =
1404 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1405 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1406 extra_apk_files = vm_payload_config
1407 .extra_apks
1408 .iter()
1409 .enumerate()
1410 .map(|(i, apk)| {
1411 File::open(PathBuf::from(&apk.path))
1412 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1413 })
1414 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001415 }
Alan Stokesfda70842023-12-20 17:50:14 +00001416 Payload::PayloadConfig(payload_config) => {
1417 vm_payload_config = create_vm_payload_config(payload_config)?;
1418 extra_apk_files =
1419 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1420 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001421 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001422
Inseob Kim89b24592024-02-23 18:59:43 +09001423 let payload_config_os = vm_payload_config.os.name.as_str();
1424 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1425 bail!("'os' in payload config is deprecated");
1426 }
1427
Inseob Kim172f9eb2023-11-06 17:02:08 +09001428 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001429 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001430 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001431 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001432 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001433
1434 // It is safe to construct a filename based on the os_name because we've already checked that it
1435 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001436 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1437 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001438 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001439
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001440 if let Some(custom_config) = &config.customConfig {
1441 if let Some(file) = custom_config.customKernelImage.as_ref() {
1442 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1443 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001444 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001445
1446 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001447 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001448 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001449 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001450
Jaewan Kimf43372b2024-12-13 18:33:58 +09001451 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001452 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001453
1454 for param in custom_config.extraKernelCmdlineParams.iter() {
1455 append_kernel_param(param, &mut vm_config);
1456 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001457
1458 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001459 }
1460
Andrew Walbrancc045902021-07-27 16:06:17 +00001461 if config.memoryMib > 0 {
1462 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001463 }
1464
Chris Wailes6177c662024-05-09 14:37:44 -07001465 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001466 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001467 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001468 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001469 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001470
Shikha Panwar22e70452022-10-10 18:32:55 +00001471 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001472 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001473
1474 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1475 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001476 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001477 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001478 temporary_directory,
1479 apk_file,
1480 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001481 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001482 &vm_payload_config,
1483 &mut vm_config,
1484 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001485
Andrew Walbrancc0db522021-07-12 17:03:42 +00001486 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001487}
1488
Frederick Mayle3a46b272025-02-10 21:55:49 -08001489fn check_partition_for_file(
1490 fd: &ParcelFileDescriptor,
1491 calling_partition: CallingPartition,
1492) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001493 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
Inseob Kim4d414452025-03-04 16:17:47 +09001494 let link = fs::read_link(&path).with_context(|| format!("can't read_link {path}"))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001495
1496 // microdroid vendor image is OK
1497 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1498 {
1499 return Ok(());
1500 }
1501
Inseob Kim4d414452025-03-04 16:17:47 +09001502 let fd_partition = find_partition(Some(&link))
1503 .with_context(|| format!("can't find_partition {}", link.display()))?;
1504 let is_fd_vendor =
1505 fd_partition == CallingPartition::Vendor || fd_partition == CallingPartition::Odm;
Frederick Mayle3a46b272025-02-10 21:55:49 -08001506 let is_caller_vendor =
1507 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001508
1509 if is_fd_vendor != is_caller_vendor {
1510 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001511 }
1512
1513 Ok(())
1514}
1515
Inseob Kime3e932d2024-12-16 20:06:57 +09001516fn check_partitions_for_files(
1517 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001518 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001519) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001520 config
1521 .disks
1522 .iter()
1523 .flat_map(|disk| disk.partitions.iter())
1524 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001525 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001526
Inseob Kime3e932d2024-12-16 20:06:57 +09001527 config
1528 .disks
1529 .iter()
1530 .filter_map(|disk| disk.image.as_ref())
1531 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1532
1533 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1534 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1535 config
1536 .bootloader
1537 .as_ref()
1538 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001539
1540 Ok(())
1541}
1542
Alan Stokes0d1ef782022-09-27 13:46:35 +01001543fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1544 let mut apk_zip = ZipArchive::new(apk_file)?;
1545 let config_file = apk_zip.by_name(config_path)?;
1546 Ok(serde_json::from_reader(config_file)?)
1547}
1548
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001549fn create_vm_payload_config(
1550 payload_config: &VirtualMachinePayloadConfig,
1551) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001552 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1553 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1554 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001555
1556 let payload_binary_name = &payload_config.payloadBinaryName;
1557 if payload_binary_name.contains('/') {
1558 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1559 }
1560
1561 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001562
1563 // The VM only cares about how many there are, these names are actually ignored.
1564 let extra_apk_count = payload_config.extraApks.len();
1565 let extra_apks =
1566 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1567
Nikita Ioffe901083f2025-01-20 01:54:28 +00001568 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1569 // The only payload delivered via Mainline module in this release requires
1570 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1571 // APIs, so we use the fact that the payload is granted
1572 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1573 // com.android.i18n APEX.
1574 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1575 // Microdroid pVMs.
1576 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1577 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1578 } else {
1579 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1580 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001581}
1582
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001583/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001584fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001585 temporary_directory: &Path,
1586 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001587) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001588 let id = *next_temporary_image_id;
1589 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001590 CompositeImageFilenames {
1591 composite: temporary_directory.join(format!("composite-{}.img", id)),
1592 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1593 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1594 }
1595}
1596
1597/// Filenames for a composite disk image, including header and footer partitions.
1598#[derive(Clone, Debug, Eq, PartialEq)]
1599struct CompositeImageFilenames {
1600 /// The composite disk image itself.
1601 composite: PathBuf,
1602 /// The header partition image.
1603 header: PathBuf,
1604 /// The footer partition image.
1605 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001606}
1607
Jiyong Park753553b2021-07-12 21:21:09 +09001608/// Checks whether the caller has a specific permission
1609fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001610 if cfg!(early) {
1611 // Skip permission check for early VMs, in favor of SELinux
1612 return Ok(());
1613 }
David Brazdil1f530702022-10-03 12:18:10 +01001614 let calling_pid = get_calling_pid();
1615 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001616 // Root can do anything
1617 if calling_uid == 0 {
1618 return Ok(());
1619 }
1620 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001621 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001622 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001623 Ok(())
1624 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001625 Err(anyhow!("does not have the {} permission", perm))
1626 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001627 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001628}
1629
Jiyong Park753553b2021-07-12 21:21:09 +09001630/// Check whether the caller of the current Binder method is allowed to manage VMs
1631fn check_manage_access() -> binder::Result<()> {
1632 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1633}
1634
Inseob Kim1119d702022-05-02 18:01:58 +09001635/// Check whether the caller of the current Binder method is allowed to create custom VMs
1636fn check_use_custom_virtual_machine() -> binder::Result<()> {
1637 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1638}
1639
Nikita Ioffe901083f2025-01-20 01:54:28 +00001640/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1641/// rollback protection schema.
1642fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1643 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1644}
1645
Alan Stokes185fe112023-01-10 16:20:55 +00001646/// Return whether a partition is exempt from selinux label checks, because we know that it does
1647/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001648fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001649 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001650 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001651 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001652 || label == "microdroid-apk-idsig"
1653 || label == "payload-metadata"
1654 || label.starts_with("extra-idsig-")
1655}
1656
Alice Wangc206b9b2023-08-28 14:13:51 +00001657/// Returns whether a partition with the given label is safe for a raw config VM.
1658fn is_safe_raw_partition(label: &str) -> bool {
1659 label == "vm-instance"
1660}
1661
Alan Stokes185fe112023-01-10 16:20:55 +00001662/// Check that a file SELinux label is acceptable.
1663///
1664/// 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 +09001665/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001666///
1667/// Note that sepolicy must also grant read access for these types to both virtualization
1668/// service and crosvm.
1669///
1670/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1671/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001672fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001673 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001674 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001675 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001676 | "staging_data_file" // updated/staged APEX images
1677 | "system_file" // immutable dm-verity protected partition
1678 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001679 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001680 => Ok(()),
Frederick Maylec8f27042025-02-26 12:35:26 -08001681 // It is difficult to require specific label types for vendor initiated VM's files.
1682 _ if calling_partition == CallingPartition::Vendor => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001683 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001684 }
1685}
1686
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001687fn check_label_for_partition(
1688 partition: &Partition,
1689 calling_partition: CallingPartition,
1690) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001691 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001692 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001693 .with_context(|| format!("Partition {} invalid", &partition.label))
1694}
1695
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001696fn check_label_for_kernel_files(
1697 kernel: &Option<File>,
1698 initrd: &Option<File>,
1699 calling_partition: CallingPartition,
1700) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001701 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001702 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001703 }
1704 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001705 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001706 }
1707 Ok(())
1708}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001709fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001710 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001711 name: &str,
1712 calling_partition: CallingPartition,
1713) -> Result<()> {
1714 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1715 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001716}
1717
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001718/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1719#[derive(Debug)]
1720struct VirtualMachine {
1721 instance: Arc<VmInstance>,
1722}
1723
1724impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001725 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001726 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001727 }
Nikita Ioffecaff2822025-03-18 13:43:14 +00001728
1729 fn handle_vendor_tee_services(&self) -> binder::Result<()> {
1730 // TODO(b/360102915): get vm_fd from crosvm
1731 // TODO(b/360102915): talk to HAL
1732 self.instance
1733 .resume_full()
1734 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1735 .with_log()
1736 .or_service_specific_exception(-1)
1737 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001738}
1739
1740impl Interface for VirtualMachine {}
1741
Devin Moore407df8f2024-08-27 19:39:16 +00001742impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001743 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001744 // Don't check permission. The owner of the VM might have passed this binder object to
1745 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001746 Ok(self.instance.cid as i32)
1747 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001748
Andrew Walbran6b650662021-09-07 13:13:23 +00001749 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001750 // Don't check permission. The owner of the VM might have passed this binder object to
1751 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001752 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001753 }
1754
1755 fn registerCallback(
1756 &self,
1757 callback: &Strong<dyn IVirtualMachineCallback>,
1758 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001759 // Don't check permission. The owner of the VM might have passed this binder object to
1760 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001761
1762 // Only register callback if it may be notified.
1763 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1764 let vm_state = self.instance.vm_state.lock().unwrap();
1765 if matches!(*vm_state, VmState::Dead) {
1766 warn!("Ignoring registerCallback() after VM is died");
1767 } else {
1768 self.instance.callbacks.add(callback.clone());
1769 }
1770 drop(vm_state);
1771
Andrew Walbrandae07162021-03-12 17:05:20 +00001772 Ok(())
1773 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001774
Andrew Walbranf8d94112021-09-07 11:45:36 +00001775 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001776 self.instance
1777 .start()
1778 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1779 .with_log()
Nikita Ioffecaff2822025-03-18 13:43:14 +00001780 .or_service_specific_exception(-1)?;
1781 if !self.instance.vendor_tee_services.is_empty() {
1782 self.handle_vendor_tee_services()
1783 } else {
1784 Ok(())
1785 }
Andrew Walbranf8d94112021-09-07 11:45:36 +00001786 }
1787
Inseob Kima446f802022-07-11 19:46:37 +09001788 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001789 self.instance
1790 .kill()
1791 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1792 .with_log()
1793 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001794 }
1795
Yuan Yao3843ea22025-02-27 06:22:20 +00001796 fn isMemoryBalloonEnabled(&self) -> binder::Result<bool> {
1797 Ok(self.instance.balloon_enabled)
1798 }
1799
Keir Fraser48221ba2024-07-12 14:05:02 +00001800 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1801 let balloon = self
1802 .instance
1803 .get_memory_balloon()
1804 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1805 .with_log()
1806 .or_service_specific_exception(-1)?;
1807 Ok(balloon.try_into().unwrap())
1808 }
1809
1810 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001811 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001812 .set_memory_balloon(num_bytes.try_into().unwrap())
1813 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001814 .with_log()
1815 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001816 }
1817
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001818 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001819 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001820 return Err(Status::new_service_specific_error_str(
1821 IVirtualMachine::ERROR_UNEXPECTED,
1822 Some("Virtual Machine is not running"),
1823 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001824 }
Alan Stokes10c47672022-12-13 17:17:08 +00001825 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001826 if port < VSOCK_PRIV_PORT_MAX {
1827 return Err(Status::new_service_specific_error_str(
1828 IVirtualMachine::ERROR_UNEXPECTED,
1829 Some("Can't connect to privileged port {port}"),
1830 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001831 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001832 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1833 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001834 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001835 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001836 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001837
Devin Moore407df8f2024-08-27 19:39:16 +00001838 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1839 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1840 return Err(Status::new_service_specific_error_str(
1841 IVirtualMachine::ERROR_UNEXPECTED,
1842 Some("Virtual Machine is not running"),
1843 ));
1844 }
1845 let port = port as u32;
1846 if port < VSOCK_PRIV_PORT_MAX {
1847 return Err(Status::new_service_specific_error_str(
1848 IVirtualMachine::ERROR_UNEXPECTED,
1849 Some("Can't connect to privileged port {port}"),
1850 ));
1851 }
1852 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001853 let addr = sockaddr_vm {
1854 svm_family: AF_VSOCK as sa_family_t,
1855 svm_reserved1: 0,
1856 svm_port: port,
1857 svm_cid: cid,
1858 svm_zero: [0u8; 4],
1859 };
1860 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001861 let accessor = Accessor::new(name, get_connection_info);
1862 accessor
1863 .as_binder()
1864 .context("The newly created Accessor should always have a binder")
1865 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1866 }
1867
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001868 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1869 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1870 }
Jiyong Park23b67392024-07-04 13:51:42 +09001871
1872 fn suspend(&self) -> binder::Result<()> {
1873 self.instance
1874 .suspend()
1875 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1876 .with_log()
1877 .or_service_specific_exception(-1)
1878 }
1879
1880 fn resume(&self) -> binder::Result<()> {
1881 self.instance
1882 .resume()
1883 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1884 .with_log()
1885 .or_service_specific_exception(-1)
1886 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001887}
1888
1889impl Drop for VirtualMachine {
1890 fn drop(&mut self) {
1891 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001892 if let Err(e) = self.instance.kill() {
1893 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1894 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001895 }
1896}
1897
1898/// A set of Binders to be called back in response to various events on the VM, such as when it
1899/// dies.
1900#[derive(Debug, Default)]
1901pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1902
1903impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001904 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001905 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001906 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001907 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001908 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001909 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001910 }
1911 }
1912 }
1913
Inseob Kim14cb8692021-08-31 21:50:39 +09001914 /// Call all registered callbacks to notify that the payload is ready to serve.
1915 pub fn notify_payload_ready(&self, cid: Cid) {
1916 let callbacks = &*self.0.lock().unwrap();
1917 for callback in callbacks {
1918 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001919 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001920 }
1921 }
1922 }
1923
Inseob Kim2444af92021-08-31 01:22:50 +09001924 /// Call all registered callbacks to notify that the payload has finished.
1925 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1926 let callbacks = &*self.0.lock().unwrap();
1927 for callback in callbacks {
1928 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001929 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001930 }
1931 }
1932 }
1933
Jooyung Handd0a1732021-11-23 15:26:20 +09001934 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001935 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001936 let callbacks = &*self.0.lock().unwrap();
1937 for callback in callbacks {
1938 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001939 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001940 }
1941 }
1942 }
1943
Andrew Walbrandae07162021-03-12 17:05:20 +00001944 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001945 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001946 let mut callbacks = self.0.lock().unwrap();
1947 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001948 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001949 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001950 }
1951 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001952
1953 // Nothing to notify afterward because VM cannot be restarted.
1954 // Explicitly clear callbacks to prevent potential cyclic references
1955 // between callback and VmInstance.
1956 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001957 }
1958
1959 /// Add a new callback to the set.
1960 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1961 self.0.lock().unwrap().push(callback);
1962 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001963}
1964
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001965/// The mutable state of the VirtualizationService. There should only be one instance of this
1966/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001967#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001968struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001969 /// The VMs which have been started. When VMs are started a weak reference is added to this
1970 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1971 /// the Binder client are dropped the weak reference here will become invalid, and will be
1972 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001973 vms: Vec<Weak<VmInstance>>,
1974}
1975
1976impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001977 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001978 fn vms(&self) -> Vec<Arc<VmInstance>> {
1979 // Attempt to upgrade the weak pointers to strong pointers.
1980 self.vms.iter().filter_map(Weak::upgrade).collect()
1981 }
1982
1983 /// Add a new VM to the list.
1984 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1985 // Garbage collect any entries from the stored list which no longer exist.
1986 self.vms.retain(|vm| vm.strong_count() > 0);
1987
1988 // Actually add the new VM.
1989 self.vms.push(vm);
1990 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001991
Jiyong Park8611a6c2021-07-09 18:17:44 +09001992 /// Get a VM that corresponds to the given cid
1993 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1994 self.vms().into_iter().find(|vm| vm.cid == cid)
1995 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001996}
1997
Andrew Walbran6b650662021-09-07 13:13:23 +00001998/// Gets the `VirtualMachineState` of the given `VmInstance`.
1999fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00002000 match &*instance.vm_state.lock().unwrap() {
2001 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
2002 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00002003 PayloadState::Starting => VirtualMachineState::STARTING,
2004 PayloadState::Started => VirtualMachineState::STARTED,
2005 PayloadState::Ready => VirtualMachineState::READY,
2006 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09002007 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00002008 },
2009 VmState::Dead => VirtualMachineState::DEAD,
2010 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00002011 }
2012}
2013
David Brazdilf50c7a62023-04-19 14:22:42 +00002014/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002015pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
2016 file.as_ref()
2017 .try_clone()
2018 .context("Failed to clone File from ParcelFileDescriptor")
2019 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00002020 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00002021}
2022
Andrew Walbrand3a84182021-09-07 14:48:52 +00002023/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002024fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00002025 file.as_ref().map(clone_file).transpose()
2026}
2027
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002028/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09002029fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
2030 // SAFETY: ownership is transferred from stream to f
2031 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
2032 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002033}
2034
Jiyong Parkdcf17412022-02-08 15:07:23 +09002035/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002036fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
2037 VersionReq::parse(s)
2038 .with_context(|| format!("Invalid platform version requirement {}", s))
2039 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09002040}
2041
Jiyong Parked180932023-02-24 19:55:41 +09002042/// Create the empty ramdump file
2043fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
2044 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
2045 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
2046 // owner) for readout.
2047 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09002048 let ramdump = File::create(ramdump_path)
2049 .context("Failed to prepare ramdump file")
2050 .with_log()
2051 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09002052 Ok(ramdump)
2053}
2054
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01002055/// Create the empty device tree dump file
2056fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
2057 let path = temporary_directory.join("device_tree.dtb");
2058 let file = File::create(path)
2059 .context("Failed to prepare device tree dump file")
2060 .with_log()
2061 .or_service_specific_exception(-1)?;
2062 Ok(file)
2063}
2064
Nikita Ioffe5776f082023-02-10 21:38:26 +00002065fn is_protected(config: &VirtualMachineConfig) -> bool {
2066 match config {
2067 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
2068 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
2069 }
2070}
2071
2072fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
2073 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09002074 return Err(anyhow!("Can't use gdb with protected VMs"))
2075 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002076 }
2077
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002078 if get_debug_level(config) == Some(DebugLevel::NONE) {
2079 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
2080 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002081 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002082
2083 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00002084}
2085
Shikha Panwar61a74b52024-02-16 13:17:01 +00002086fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
2087 match config {
2088 VirtualMachineConfig::RawConfig(config) => config.instanceId,
2089 VirtualMachineConfig::AppConfig(config) => config.instanceId,
2090 }
2091}
2092
Alan Stokesc96b35e2024-05-03 13:21:20 +01002093fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
2094 match config {
2095 VirtualMachineConfig::RawConfig(_) => true,
2096 VirtualMachineConfig::AppConfig(config) => {
2097 let Some(custom) = &config.customConfig else { return true };
2098 custom.wantUpdatable
2099 }
2100 }
2101}
2102
Nikita Ioffe5776f082023-02-10 21:38:26 +00002103fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
2104 match config {
2105 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01002106 VirtualMachineConfig::AppConfig(config) => {
2107 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
2108 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00002109 }
2110}
2111
Nikita Ioffe631717e2023-09-05 13:38:07 +01002112fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2113 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2114 if let Some(custom_config) = &config.customConfig {
2115 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2116 return Err(anyhow!("vendor modules feature is disabled"))
2117 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2118 }
2119 }
2120 Ok(())
2121}
2122
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002123fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2124 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2125 if let Some(custom_config) = &config.customConfig {
2126 if !custom_config.devices.is_empty() {
2127 return Err(anyhow!("device assignment feature is disabled"))
2128 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2129 }
2130 }
2131 Ok(())
2132}
2133
Alan Stokesfda70842023-12-20 17:50:14 +00002134fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2135 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2136 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2137 if !payload_config.extraApks.is_empty() {
2138 return Err(anyhow!("multi-tenant feature is disabled"))
2139 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2140 }
2141 Ok(())
2142}
2143
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002144fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2145 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2146 if let Some(custom_config) = &config.customConfig {
2147 if !custom_config.extraKernelCmdlineParams.is_empty() {
2148 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2149 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2150 }
2151 }
2152 Ok(())
2153}
2154
Nikita Ioffe99548382024-10-21 15:54:46 +00002155fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2156 match config {
2157 VirtualMachineConfig::RawConfig(config) => {
2158 if !config.teeServices.is_empty() {
2159 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2160 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2161 }
2162 }
2163 VirtualMachineConfig::AppConfig(config) => {
2164 if let Some(custom_config) = &config.customConfig {
2165 if !custom_config.teeServices.is_empty() {
2166 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2167 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2168 }
2169 }
2170 }
2171 };
2172 Ok(())
2173}
2174
Nikita Ioffef934e812024-07-05 15:44:41 +00002175fn check_protected_vm_is_supported() -> binder::Result<()> {
2176 let is_pvm_supported =
2177 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2178 if is_pvm_supported {
2179 Ok(())
2180 } else {
2181 Err(anyhow!("pVM is not supported"))
2182 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2183 }
2184}
2185
Nikita Ioffe631717e2023-09-05 13:38:07 +01002186fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2187 if !cfg!(vendor_modules) {
2188 check_no_vendor_modules(config)?;
2189 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002190 if !cfg!(device_assignment) {
2191 check_no_devices(config)?;
2192 }
Alan Stokesfda70842023-12-20 17:50:14 +00002193 if !cfg!(multi_tenant) {
2194 check_no_extra_apks(config)?;
2195 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002196 if !cfg!(debuggable_vms_improvements) {
2197 check_no_extra_kernel_cmdline_params(config)?;
2198 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002199 if !cfg!(tee_services_allowlist) {
2200 check_no_tee_services(config)?;
2201 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002202 Ok(())
2203}
2204
Inseob Kimecde8c02024-09-03 13:11:08 +09002205fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2206 check_no_vendor_modules(config)?;
2207 check_no_devices(config)?;
2208
2209 Ok(())
2210}
2211
Inseob Kim0168b462022-12-27 14:54:35 +09002212fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002213 fd: Option<&ParcelFileDescriptor>,
2214 tag: String,
2215) -> Result<Option<File>, Status> {
2216 if let Some(fd) = fd {
2217 return Ok(Some(clone_file(fd)?));
2218 }
2219
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002220 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002221 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002222
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002223 let mut reader = BufReader::new(File::from(read_fd));
2224 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002225
Frederick Mayle26e41af2025-02-05 18:30:29 -08002226 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002227 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002228 buf.clear();
2229 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002230 match reader.read_until(b'\n', &mut buf) {
2231 Ok(0) => {
2232 // EOF
2233 return;
2234 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002235 Ok(_size) => {
2236 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002237 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002238 // Logs sent via TTY usually end lines with "\r\n".
2239 if buf.last() == Some(&b'\r') {
2240 buf.pop();
2241 }
Inseob Kim0168b462022-12-27 14:54:35 +09002242 }
2243 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2244 }
2245 Err(e) => {
2246 error!("Could not read console pipe: {:?}", e);
2247 return;
2248 }
2249 };
2250 });
2251
2252 Ok(Some(write_fd))
2253}
2254
Jooyung Han35edb8f2021-07-01 16:17:16 +09002255/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2256/// it doesn't require that T implements Clone.
2257enum BorrowedOrOwned<'a, T> {
2258 Borrowed(&'a T),
2259 Owned(T),
2260}
2261
Chris Wailes73a1eb72025-01-15 11:56:43 -08002262impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002263 fn as_ref(&self) -> &T {
2264 match self {
2265 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002266 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002267 }
2268 }
2269}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002270
2271/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2272#[derive(Debug, Default)]
2273struct VirtualMachineService {
2274 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002275 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002276}
2277
2278impl Interface for VirtualMachineService {}
2279
2280impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002281 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2282 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002283 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002284 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002285 vm.update_payload_state(PayloadState::Started)
2286 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002287 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002288
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002289 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2290 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002291 Ok(())
2292 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002293 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002294 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002295 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002296 }
Inseob Kim2444af92021-08-31 01:22:50 +09002297
Inseob Kimc7d28c72021-10-25 14:28:10 +00002298 fn notifyPayloadReady(&self) -> binder::Result<()> {
2299 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002300 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002301 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002302 vm.update_payload_state(PayloadState::Ready)
2303 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002304 vm.callbacks.notify_payload_ready(cid);
2305 Ok(())
2306 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002307 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002308 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002309 }
2310 }
2311
Inseob Kimc7d28c72021-10-25 14:28:10 +00002312 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2313 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002314 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002315 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002316 vm.update_payload_state(PayloadState::Finished)
2317 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002318 vm.callbacks.notify_payload_finished(cid, exit_code);
2319 Ok(())
2320 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002321 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002322 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002323 }
2324 }
2325
Alan Stokes2bead0d2022-09-05 16:58:34 +01002326 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002327 let cid = self.cid;
2328 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002329 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002330 vm.update_payload_state(PayloadState::Finished)
2331 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002332 vm.callbacks.notify_error(cid, error_code, message);
2333 Ok(())
2334 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002335 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002336 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002337 }
2338 }
Alice Wangc2fec932023-02-23 16:24:02 +00002339
Shikha Panware45e9422024-02-28 21:18:10 +00002340 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2341 if !is_secretkeeper_supported() {
2342 return Err(StatusCode::NAME_NOT_FOUND)?;
2343 }
2344 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2345 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002346 }
2347
Alice Wange64dd182024-01-17 15:57:55 +00002348 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2349 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002350 }
Shikha Panwareeae6402025-02-06 19:05:31 +00002351
2352 fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2353 GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2354 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002355}
2356
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002357fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002358 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2359 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002360}
2361
Nikita Ioffe832410f2025-03-07 15:24:44 +00002362fn is_vm_capabilities_hal_supported() -> bool {
2363 binder::is_declared(VM_CAPABILITIES_HAL_IDENTIFIER)
2364 .expect("failed to check if {VM_CAPABILITIES_HAL_IDENTIFIER} is present")
2365}
2366
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002367impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002368 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002369 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002370 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002371 BinderFeatures::default(),
2372 )
2373 }
2374}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002375
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002376struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2377
2378impl Interface for SecretkeeperProxy {}
2379
2380impl ISecretkeeper for SecretkeeperProxy {
2381 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2382 // Pass the request to the channel, and read the response.
2383 self.0.processSecretManagementRequest(req)
2384 }
2385
2386 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2387 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2388 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2389 }
2390
2391 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2392 self.0.deleteIds(ids)
2393 }
2394
2395 fn deleteAll(&self) -> binder::Result<()> {
2396 self.0.deleteAll()
2397 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002398
2399 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2400 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2401 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2402 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2403 // use this API from the proxy.
2404 Err(ExceptionCode::SECURITY.into())
2405 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002406}
2407
2408struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2409
2410impl Interface for AuthGraphKeyExchangeProxy {}
2411
2412impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2413 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2414 self.0.create()
2415 }
2416
2417 fn init(
2418 &self,
2419 peer_pub_key: &PubKey,
2420 peer_id: &Identity,
2421 peer_nonce: &[u8],
2422 peer_version: i32,
2423 ) -> binder::Result<KeInitResult> {
2424 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2425 }
2426
2427 fn finish(
2428 &self,
2429 peer_pub_key: &PubKey,
2430 peer_id: &Identity,
2431 peer_signature: &SessionIdSignature,
2432 peer_nonce: &[u8],
2433 peer_version: i32,
2434 own_key: &Key,
2435 ) -> binder::Result<SessionInfo> {
2436 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2437 }
2438
2439 fn authenticationComplete(
2440 &self,
2441 peer_signature: &SessionIdSignature,
2442 shared_keys: &[AuthgraphArc; 2],
2443 ) -> binder::Result<[AuthgraphArc; 2]> {
2444 self.0.authenticationComplete(peer_signature, shared_keys)
2445 }
2446}
2447
Inseob Kimecde8c02024-09-03 13:11:08 +09002448// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002449#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002450struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002451 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002452 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002453 path: String,
2454}
2455
2456#[derive(Debug, Default, Deserialize)]
2457struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002458 early_vm: Vec<EarlyVm>,
2459}
2460
Alice Wang78dd87a2025-02-13 08:56:07 +00002461impl EarlyVm {
2462 /// Verifies that the provided executable path matches the expected path stored in the XML
2463 /// configuration.
2464 /// If the provided path starts with `/system`, it will be stripped before comparison.
2465 fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2466 let actual_path = calling_exe_path.as_ref();
2467 if Path::new(&self.path)
2468 == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2469 {
2470 return Ok(());
2471 }
2472 Err(Status::new_service_specific_error_str(
2473 -1,
2474 Some(format!(
2475 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2476 self.name,
2477 self.path,
2478 actual_path.display()
2479 )),
2480 ))
2481 }
2482}
2483
Frederick Mayle3a46b272025-02-10 21:55:49 -08002484static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002485 LazyLock::new(|| Mutex::new(HashMap::new()));
2486
Frederick Mayle3a46b272025-02-10 21:55:49 -08002487fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002488 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002489 CallingPartition::System => 100..200,
2490 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2491 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2492 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002493 }
2494}
2495
Inseob Kim7e1877b2024-11-07 17:28:56 +09002496fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002497 if !xml_path.exists() {
2498 bail!("{} doesn't exist", xml_path.display());
2499 }
2500
2501 let xml =
2502 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2503 let xml = String::from_utf8(xml)
2504 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2505 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2506 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2507
Inseob Kim7e1877b2024-11-07 17:28:56 +09002508 Ok(early_vms.early_vm)
2509}
Inseob Kimecde8c02024-09-03 13:11:08 +09002510
Inseob Kim7e1877b2024-11-07 17:28:56 +09002511fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2512 for early_vm in early_vms {
2513 let cid = early_vm
2514 .cid
2515 .try_into()
2516 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2517
2518 ensure!(
2519 cid_range.contains(&cid),
2520 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2521 early_vm.name
2522 );
2523 }
2524 Ok(())
2525}
2526
Frederick Mayle3a46b272025-02-10 21:55:49 -08002527fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002528 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2529
Frederick Mayle3a46b272025-02-10 21:55:49 -08002530 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002531 return Ok(result.clone());
2532 }
2533
2534 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2535 let mut early_vms = Vec::new();
2536 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2537 match entry {
2538 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2539 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2540 }
2541 }
2542
Frederick Mayle3a46b272025-02-10 21:55:49 -08002543 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002544 .with_context(|| format!("CID validation for {partition} failed"))?;
2545
Frederick Mayle3a46b272025-02-10 21:55:49 -08002546 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002547
2548 Ok(early_vms)
2549}
2550
2551fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2552 let mut found_vm: Option<&EarlyVm> = None;
2553
2554 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002555 if early_vm.name != name {
2556 continue;
2557 }
2558
Inseob Kimecde8c02024-09-03 13:11:08 +09002559 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002560 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002561 }
2562
2563 found_vm = Some(early_vm);
2564 }
2565
Inseob Kim7e1877b2024-11-07 17:28:56 +09002566 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002567}
2568
Frederick Mayle3a46b272025-02-10 21:55:49 -08002569fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002570 let early_vms = get_early_vms_in_partition(partition)
2571 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2572
2573 Ok(find_early_vm(&early_vms, name)
2574 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2575 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002576}
2577
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002578#[cfg(test)]
2579mod tests {
2580 use super::*;
2581
2582 #[test]
2583 fn test_is_allowed_label_for_partition() -> Result<()> {
2584 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002585 (CallingPartition::System, "u:object_r:system_file:s0", true),
2586 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2587 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2588 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2589 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2590 (CallingPartition::System, "invalid", false),
2591 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2592 (
2593 CallingPartition::System,
2594 "user:role:apk_data_file:severity:categories:extraneous",
2595 false,
2596 ),
2597 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2598 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002599 ];
2600
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002601 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002602 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002603 let result = check_label_is_allowed(&context, calling_partition);
2604 if expected_valid != result.is_ok() {
2605 bail!(
2606 "Expected label {label} to be {} for {calling_partition} partition",
2607 if expected_valid { "allowed" } else { "disallowed" }
2608 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002609 }
2610 }
2611 Ok(())
2612 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002613
2614 #[test]
2615 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2616 let apk = tempfile::tempfile().unwrap();
2617 let idsig = tempfile::tempfile().unwrap();
2618
2619 let ret = create_or_update_idsig_file(
2620 &ParcelFileDescriptor::new(apk),
2621 &ParcelFileDescriptor::new(idsig),
2622 );
2623 assert!(ret.is_err(), "should fail");
2624 Ok(())
2625 }
2626
2627 #[test]
2628 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2629 let tmp_dir = tempfile::TempDir::new().unwrap();
2630 let apk = File::open(tmp_dir.path()).unwrap();
2631 let idsig = tempfile::tempfile().unwrap();
2632
2633 let ret = create_or_update_idsig_file(
2634 &ParcelFileDescriptor::new(apk),
2635 &ParcelFileDescriptor::new(idsig),
2636 );
2637 assert!(ret.is_err(), "should fail");
2638 Ok(())
2639 }
2640
2641 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2642 /// on ext4 filesystem is passed.
2643 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2644 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2645 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2646 #[test]
2647 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2648 // APEXes are backed by the ext4.
2649 let apk = File::open("/apex/com.android.virt/").unwrap();
2650 let idsig = tempfile::tempfile().unwrap();
2651
2652 let ret = create_or_update_idsig_file(
2653 &ParcelFileDescriptor::new(apk),
2654 &ParcelFileDescriptor::new(idsig),
2655 );
2656 assert!(ret.is_err(), "should fail");
2657 Ok(())
2658 }
Jiyong Park8d192952023-06-26 14:29:51 +09002659
2660 #[test]
2661 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2662 use std::io::Seek;
2663
2664 // Pick any APK
2665 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2666 let mut idsig = tempfile::tempfile().unwrap();
2667
2668 create_or_update_idsig_file(
2669 &ParcelFileDescriptor::new(apk.try_clone()?),
2670 &ParcelFileDescriptor::new(idsig.try_clone()?),
2671 )?;
2672 let modified_orig = idsig.metadata()?.modified()?;
2673 apk.rewind()?;
2674 idsig.rewind()?;
2675
2676 // Call the function again
2677 create_or_update_idsig_file(
2678 &ParcelFileDescriptor::new(apk.try_clone()?),
2679 &ParcelFileDescriptor::new(idsig.try_clone()?),
2680 )?;
2681 let modified_new = idsig.metadata()?.modified()?;
2682 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2683 Ok(())
2684 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002685
2686 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002687 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2688 use std::io::Read;
2689
2690 // Pick any APK
2691 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2692 let idsig_empty = tempfile::tempfile().unwrap();
2693 let mut idsig_invalid = tempfile::tempfile().unwrap();
2694 idsig_invalid.write_all(b"Oops")?;
2695
2696 // Create new idsig
2697 create_or_update_idsig_file(
2698 &ParcelFileDescriptor::new(apk.try_clone()?),
2699 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2700 )?;
2701 apk.rewind()?;
2702
2703 // Update idsig_invalid
2704 create_or_update_idsig_file(
2705 &ParcelFileDescriptor::new(apk.try_clone()?),
2706 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2707 )?;
2708
2709 // Ensure the 2 idsig files have same size!
2710 assert!(
2711 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2712 "idsig files differ in size"
2713 );
2714 // Ensure the 2 idsig files have same content!
2715 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2716 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2717 }
2718 Ok(())
2719 }
2720 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002721 fn test_append_kernel_param_first_param() {
2722 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2723 append_kernel_param("foo=1", &mut vm_config);
2724 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2725 }
2726
2727 #[test]
2728 fn test_append_kernel_param() {
2729 let mut vm_config =
2730 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2731 append_kernel_param("bar=42", &mut vm_config);
2732 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2733 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002734
Inseob Kim46257382024-01-03 15:41:22 +09002735 fn test_extract_os_name_from_config_path(
2736 path: &Path,
2737 expected_result: Option<&str>,
2738 ) -> Result<()> {
2739 let result = extract_os_name_from_config_path(path);
2740 if result.as_deref() != expected_result {
2741 bail!("Expected {:?} but was {:?}", expected_result, &result)
2742 }
2743 Ok(())
2744 }
2745
2746 #[test]
2747 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2748 test_extract_os_name_from_config_path(
2749 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2750 Some("microdroid"),
2751 )
2752 }
2753
2754 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002755 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2756 test_extract_os_name_from_config_path(
2757 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2758 Some("microdroid_16k"),
2759 )
2760 }
2761
2762 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002763 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2764 test_extract_os_name_from_config_path(
2765 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2766 Some("microdroid_gki-android14-6.1"),
2767 )
2768 }
2769
2770 #[test]
2771 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2772 test_extract_os_name_from_config_path(
2773 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2774 None,
2775 )
2776 }
2777
2778 #[test]
2779 fn test_extract_os_name_from_configs() -> Result<()> {
2780 let tmp_dir = tempfile::TempDir::new()?;
2781 let tmp_dir_path = tmp_dir.path().to_owned();
2782
2783 let mut os_names: HashSet<String> = HashSet::new();
2784 os_names.insert("microdroid".to_owned());
2785 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2786 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2787
2788 // config files
2789 for os_name in &os_names {
2790 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2791 }
2792
2793 // fake files not related to configs
2794 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2795 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2796
2797 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2798 Some(s) => s.to_owned(),
2799 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2800 };
2801
2802 let result = extract_os_names_from_configs(&glob_pattern)?;
2803 if result != os_names {
2804 bail!("Expected {:?} but was {:?}", os_names, result);
2805 }
2806 Ok(())
2807 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002808
2809 #[test]
2810 fn test_find_early_vms_from_xml() -> Result<()> {
2811 let tmp_dir = tempfile::TempDir::new()?;
2812 let tmp_dir_path = tmp_dir.path().to_owned();
2813 let xml_path = tmp_dir_path.join("early_vms.xml");
2814
2815 std::fs::write(
2816 &xml_path,
2817 br#"<?xml version="1.0" encoding="utf-8"?>
2818 <early_vms>
2819 <early_vm>
2820 <name>vm_demo_native_early</name>
2821 <cid>123</cid>
2822 <path>/system/bin/vm_demo_native_early</path>
2823 </early_vm>
2824 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002825 <name>vm_demo_native_early_2</name>
2826 <cid>456</cid>
2827 <path>/system/bin/vm_demo_native_early_2</path>
2828 </early_vm>
2829 </early_vms>
2830 "#,
2831 )?;
2832
2833 let cid_range = 100..1000;
2834
2835 let early_vms = get_early_vms_in_path(&xml_path)?;
2836 validate_cid_range(&early_vms, &cid_range)?;
2837
2838 let test_cases = [
2839 (
2840 "vm_demo_native_early",
2841 EarlyVm {
2842 name: "vm_demo_native_early".to_owned(),
2843 cid: 123,
2844 path: "/system/bin/vm_demo_native_early".to_owned(),
2845 },
2846 ),
2847 (
2848 "vm_demo_native_early_2",
2849 EarlyVm {
2850 name: "vm_demo_native_early_2".to_owned(),
2851 cid: 456,
2852 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2853 },
2854 ),
2855 ];
2856
2857 for (name, expected) in test_cases {
2858 let result = find_early_vm(&early_vms, name)?;
2859 assert_eq!(result, &expected);
2860 }
2861
2862 Ok(())
2863 }
2864
2865 #[test]
2866 fn test_invalid_cid_validation() -> Result<()> {
2867 let tmp_dir = tempfile::TempDir::new()?;
2868 let xml_path = tmp_dir.path().join("early_vms.xml");
2869
2870 let cid_range = 100..1000;
2871
2872 for cid in [-1, 999999] {
2873 std::fs::write(
2874 &xml_path,
2875 format!(
2876 r#"<?xml version="1.0" encoding="utf-8"?>
2877 <early_vms>
2878 <early_vm>
2879 <name>vm_demo_invalid_cid</name>
2880 <cid>{cid}</cid>
2881 <path>/system/bin/vm_demo_invalid_cid</path>
2882 </early_vm>
2883 </early_vms>
2884 "#
2885 ),
2886 )?;
2887
2888 let early_vms = get_early_vms_in_path(&xml_path)?;
2889 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2890 }
2891
2892 Ok(())
2893 }
2894
2895 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002896 fn test_symlink_to_system_ext_supported() -> Result<()> {
2897 let link_path = Path::new("/system/system_ext/file");
2898 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002899 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002900 Ok(())
2901 }
2902
2903 #[test]
2904 fn test_symlink_to_product_supported() -> Result<()> {
2905 let link_path = Path::new("/system/product/file");
2906 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002907 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002908 Ok(())
2909 }
2910
2911 #[test]
Frederick Mayle2192baf2025-02-26 11:27:22 -08002912 fn test_vendor_in_data() {
2913 assert_eq!(
2914 CallingPartition::Vendor,
2915 find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap()
2916 );
2917 }
2918
2919 #[test]
Alice Wang78dd87a2025-02-13 08:56:07 +00002920 fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2921 let early_vm = EarlyVm {
2922 name: "vm_demo_native_early".to_owned(),
2923 cid: 123,
2924 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2925 };
2926 let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2927 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2928 }
2929
2930 #[test]
2931 fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2932 let early_vm = EarlyVm {
2933 name: "vm_demo_native_early".to_owned(),
2934 cid: 123,
2935 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2936 };
2937 let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2938 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2939 }
2940
2941 #[test]
2942 fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2943 let early_vm = EarlyVm {
2944 name: "vm_demo_native_early".to_owned(),
2945 cid: 123,
2946 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2947 };
2948 let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2949 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2950 }
2951
2952 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002953 fn test_duplicated_early_vms() -> Result<()> {
2954 let tmp_dir = tempfile::TempDir::new()?;
2955 let tmp_dir_path = tmp_dir.path().to_owned();
2956 let xml_path = tmp_dir_path.join("early_vms.xml");
2957
2958 std::fs::write(
2959 &xml_path,
2960 br#"<?xml version="1.0" encoding="utf-8"?>
2961 <early_vms>
2962 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002963 <name>vm_demo_duplicated_name</name>
2964 <cid>456</cid>
2965 <path>/system/bin/vm_demo_duplicated_name_1</path>
2966 </early_vm>
2967 <early_vm>
2968 <name>vm_demo_duplicated_name</name>
2969 <cid>789</cid>
2970 <path>/system/bin/vm_demo_duplicated_name_2</path>
2971 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002972 </early_vms>
2973 "#,
2974 )?;
2975
2976 let cid_range = 100..1000;
2977
Inseob Kim7e1877b2024-11-07 17:28:56 +09002978 let early_vms = get_early_vms_in_path(&xml_path)?;
2979 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002980
Inseob Kim7e1877b2024-11-07 17:28:56 +09002981 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002982
2983 Ok(())
2984 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002985}