blob: 76fc6571d2f683e73a92bfcbbc1ec686f96ac39c [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000073use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
Nikita Ioffe832410f2025-03-07 15:24:44 +0000120const VM_CAPABILITIES_HAL_IDENTIFIER: &str =
121 "android.hardware.virtualization.capabilities.IVmCapabilitiesService/default";
122
David Brazdilf50c7a62023-04-19 14:22:42 +0000123const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
124
125/// crosvm requires all partitions to be a multiple of 4KiB.
126const PARTITION_GRANULARITY_BYTES: u64 = 4096;
127
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000128const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
129
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100130pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
131 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900132 if cfg!(early) {
133 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
134 } else {
135 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
136 .expect("Could not connect to VirtualizationServiceInternal")
137 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100138 });
139static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
140 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000141
Inseob Kime3e932d2024-12-16 20:06:57 +0900142static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
143 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
144 match fs::read_link(&calling_exe_link) {
145 Ok(calling_exe_path) => Some(calling_exe_path),
146 Err(e) => {
147 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
148 // discourage vendor apps, regarding such cases as system is safer.
149 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
150 // apps.
151 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
152 None
153 }
154 }
155});
156
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000157// TODO(ioffe): add service for guest-ffa.
158const KNOWN_TEE_SERVICES: [&str; 0] = [];
159
160fn check_known_tee_service(tee_service: &str) -> binder::Result<()> {
161 if !KNOWN_TEE_SERVICES.contains(&tee_service) {
162 return Err(anyhow!("unknown tee_service {tee_service}"))
163 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
164 }
165 Ok(())
166}
167
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000168fn create_or_update_idsig_file(
169 input_fd: &ParcelFileDescriptor,
170 idsig_fd: &ParcelFileDescriptor,
171) -> Result<()> {
172 let mut input = clone_file(input_fd)?;
173 let metadata = input.metadata().context("failed to get input metadata")?;
174 if !metadata.is_file() {
175 bail!("input is not a regular file");
176 }
Alan Stokes25f69362023-03-06 16:51:54 +0000177 let mut sig =
178 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
179 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000180
181 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900182
183 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
184 // if the idsig file already has the same APK digest.
185 if output.metadata()?.len() > 0 {
186 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
187 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
188 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
189 return Ok(());
190 }
191 }
192 // if we fail to read v4signature from output, that's fine. User can pass a random file.
193 // We will anyway overwrite the file to the v4signature generated from input_fd.
194 }
195
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000196 output
197 .seek(SeekFrom::Start(0))
198 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000199 output.set_len(0).context("failed to set_len on the idsig output")?;
200 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000201 Ok(())
202}
203
Alan Stokes25f69362023-03-06 16:51:54 +0000204fn get_current_sdk() -> Result<u32> {
205 let current_sdk = system_properties::read("ro.build.version.sdk")?;
206 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
207 current_sdk.parse().context("Malformed SDK version")
208}
209
David Brazdil4b4c5102022-12-19 22:56:20 +0000210pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
211 for dir_entry in read_dir(path)? {
212 remove_file(dir_entry?.path())?;
213 }
214 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100215}
216
David Brazdil528e0472022-10-10 15:06:02 +0100217/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000218#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000219pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900220 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221}
222
Shikha Panward8e35422021-10-11 13:51:27 +0000223impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000225 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
226 let state = &mut *self.state.lock().unwrap();
227 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000228 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000229 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000230 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
231 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000232 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000233 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000234 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000235 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
236 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000237 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000238 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000239 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000240 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000241 .or(Err(StatusCode::UNKNOWN_ERROR))?;
242 }
243 Ok(())
244 }
245}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000246impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000247 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
248 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000249 ///
250 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000251 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000252 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000253 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900254 console_out_fd: Option<&ParcelFileDescriptor>,
255 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000256 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000257 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000258 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000259 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900260 let ret = self.create_vm_internal(
261 config,
262 console_out_fd,
263 console_in_fd,
264 log_fd,
265 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000266 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900267 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000268 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000269 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000270 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000271
Shikha Panwar61a74b52024-02-16 13:17:01 +0000272 /// Allocate a new instance_id to the VM
273 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000274 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000275 GLOBAL_SERVICE.allocateInstanceId()
276 }
277
Andrew Walbrandff3b942021-06-09 15:20:36 +0000278 /// Initialise an empty partition image of the given size to be used as a writable partition.
279 fn initializeWritablePartition(
280 &self,
281 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000282 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900283 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000284 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900285 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900286 let size_bytes = size_bytes
287 .try_into()
288 .with_context(|| format!("Invalid size: {}", size_bytes))
289 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000291 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000292 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000293 image
294 .seek(SeekFrom::Start(0))
295 .context("failed to move cursor to start")
296 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900297 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700298 // Set the file length. In most filesystems, this will not allocate any physical disk
299 // space, it will only change the logical size.
300 image
301 .set_len(size_bytes)
302 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900303 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000304
305 match partition_type {
306 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700307 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
308 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000309 _ => Err(Error::new(
310 ErrorKind::Unsupported,
311 format!("Unsupported partition type {:?}", partition_type),
312 )),
313 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
315 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000316
317 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000318 }
319
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800320 fn setEncryptedStorageSize(
321 &self,
322 image_fd: &ParcelFileDescriptor,
323 size: i64,
324 ) -> binder::Result<()> {
325 check_manage_access()?;
326
327 let size = size
328 .try_into()
329 .with_context(|| format!("Invalid size: {}", size))
330 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
331 let size = round_up(size, PARTITION_GRANULARITY_BYTES);
332
333 let image = clone_file(image_fd)?;
334 let image_size = image.metadata().unwrap().len();
335
336 if image_size > size {
337 return Err(Status::new_exception_str(
338 ExceptionCode::ILLEGAL_ARGUMENT,
339 Some("Can't shrink encrypted storage"),
340 ));
341 }
342 // Reset the file length. In most filesystems, this will not allocate any physical disk
343 // space, it will only change the logical size.
344 image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
345 Ok(())
346 }
347
Jiyong Park0a248432021-08-20 23:32:39 +0900348 /// Creates or update the idsig file by digesting the input APK file.
349 fn createOrUpdateIdsigFile(
350 &self,
351 input_fd: &ParcelFileDescriptor,
352 idsig_fd: &ParcelFileDescriptor,
353 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900354 check_manage_access()?;
355
Jiyong Park2227eaa2023-08-04 11:59:18 +0900356 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900357 Ok(())
358 }
359
Andrew Walbran320b5602021-03-04 16:11:12 +0000360 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
361 /// and as such is only permitted from the shell user.
362 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000363 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000364 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000365 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900366
367 /// Get a list of assignable device types.
368 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
369 // Delegate to the global service, including checking the permission.
370 GLOBAL_SERVICE.getAssignableDevices()
371 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100372
Inseob Kim46257382024-01-03 15:41:22 +0900373 /// Get a list of supported OSes.
374 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
375 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
376 }
377
Jaewan Kimabd328b2024-12-10 15:59:33 +0900378 /// Get printable debug policy for testing and debugging
379 fn getDebugPolicy(&self) -> binder::Result<String> {
380 let debug_policy = DebugPolicy::from_host();
381 Ok(format!("{debug_policy:?}"))
382 }
383
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100384 /// Returns whether given feature is enabled
385 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
386 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000387 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100388 }
Alice Wange64dd182024-01-17 15:57:55 +0000389
390 fn enableTestAttestation(&self) -> binder::Result<()> {
391 GLOBAL_SERVICE.enableTestAttestation()
392 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000393
394 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
395 check_manage_access()?;
396 GLOBAL_SERVICE.isRemoteAttestationSupported()
397 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000398
399 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
400 // The response is specific to Microdroid. Updatable VMs are only possible if device
401 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
402 // this, however other guest OSes may do things differently.
403 check_manage_access()?;
404 Ok(is_secretkeeper_supported())
405 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000406
Shikha Panwar07d701c2024-03-28 14:43:52 +0000407 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
408 check_manage_access()?;
409 GLOBAL_SERVICE.removeVmInstance(instance_id)
410 }
411
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000412 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
413 check_manage_access()?;
414 GLOBAL_SERVICE.claimVmInstance(instance_id)
415 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000416}
417
Inseob Kimecde8c02024-09-03 13:11:08 +0900418/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
419#[derive(Debug, Default)]
420struct EarlyVmContext {
421 /// The unique CID assigned to the VM for vsock communication.
422 cid: Cid,
423 /// Temporary directory for this VM instance.
424 temp_dir: PathBuf,
425}
426
427impl EarlyVmContext {
428 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
429 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
430 // should trust clients, e.g. they won't run two VMs at the same time
431 let _ = remove_dir_all(&temp_dir);
432 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
433
434 Ok(Self { cid, temp_dir })
435 }
436}
437
438impl Interface for EarlyVmContext {}
439
440impl Drop for EarlyVmContext {
441 fn drop(&mut self) {
442 if let Err(e) = remove_dir_all(&self.temp_dir) {
443 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
444 }
445 }
446}
447
448impl IGlobalVmContext for EarlyVmContext {
449 fn getCid(&self) -> binder::Result<i32> {
450 Ok(self.cid as i32)
451 }
452
453 fn getTemporaryDirectory(&self) -> binder::Result<String> {
454 Ok(self.temp_dir.to_string_lossy().to_string())
455 }
456
457 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
458 Err(Status::new_exception_str(
459 ExceptionCode::UNSUPPORTED_OPERATION,
460 Some("Early VM doesn't support setting host console name"),
461 ))
462 }
463}
464
Frederick Mayle3a46b272025-02-10 21:55:49 -0800465#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466enum CallingPartition {
467 Odm,
468 Product,
469 System,
470 SystemExt,
471 Vendor,
472 Unknown,
473}
474
475impl CallingPartition {
476 fn as_str(&self) -> &'static str {
477 match self {
478 CallingPartition::Odm => "odm",
479 CallingPartition::Product => "product",
480 CallingPartition::System => "system",
481 CallingPartition::SystemExt => "system_ext",
482 CallingPartition::Vendor => "vendor",
483 CallingPartition::Unknown => "[unknown]",
484 }
485 }
486}
487
488impl std::fmt::Display for CallingPartition {
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 write!(f, "{}", self.as_str())
491 }
492}
493
494fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800495 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800496 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900497 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000498 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800499 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000500 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800501 if path.starts_with("/system/product/") {
502 return Ok(CallingPartition::Product);
503 }
Frederick Mayle2192baf2025-02-26 11:27:22 -0800504 if path.starts_with("/data/nativetest/vendor/")
505 || path.starts_with("/data/nativetest64/vendor/")
506 {
507 return Ok(CallingPartition::Vendor);
508 }
509
Frederick Mayle3a46b272025-02-10 21:55:49 -0800510 let partition = {
511 let mut components = path.components();
512 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
513 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800514 .or_service_specific_exception(-1);
515 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800516
Frederick Mayle3a46b272025-02-10 21:55:49 -0800517 // If path is under /apex, find a partition of the preinstalled .apex path
518 if partition == "apex" {
519 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
520 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
521 .or_service_specific_exception(-1);
522 };
523 let apex_info_list = ApexInfoList::load()
524 .context("Failed to get apex info list")
525 .or_service_specific_exception(-1)?;
526 apex_info_list
527 .list
528 .iter()
529 .find(|apex_info| apex_info.name.as_str() == apex_name)
530 .map(|apex_info| apex_info.partition.to_lowercase())
531 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
532 .or_service_specific_exception(-1)?
533 } else {
534 partition.to_string_lossy().into_owned()
535 }
536 };
537 Ok(match partition.as_str() {
538 "odm" => CallingPartition::Odm,
539 "product" => CallingPartition::Product,
540 "system" => CallingPartition::System,
541 "system_ext" => CallingPartition::SystemExt,
542 "vendor" => CallingPartition::Vendor,
543 _ => {
544 warn!("unknown partition for '{}'", path.display());
545 CallingPartition::Unknown
546 }
547 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900548}
549
Jiyong Park8611a6c2021-07-09 18:17:44 +0900550impl VirtualizationService {
551 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000552 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900553 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000554
Inseob Kimecde8c02024-09-03 13:11:08 +0900555 fn create_early_vm_context(
556 &self,
557 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900558 calling_exe_path: Option<&Path>,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800559 calling_partition: CallingPartition,
Inseob Kimecde8c02024-09-03 13:11:08 +0900560 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900561 let name = match config {
562 VirtualMachineConfig::RawConfig(config) => &config.name,
563 VirtualMachineConfig::AppConfig(config) => &config.name,
564 };
Frederick Mayle3a46b272025-02-10 21:55:49 -0800565 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900566 .or_service_specific_exception(-1)?;
567 let calling_exe_path = match calling_exe_path {
568 Some(path) => path,
569 None => {
570 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
571 .or_service_specific_exception(-1)
572 }
573 };
Alice Wang78dd87a2025-02-13 08:56:07 +0000574 early_vm.check_exe_paths_match(calling_exe_path)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900575
576 let cid = early_vm.cid as Cid;
577 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
578
579 let context = EarlyVmContext::new(cid, temp_dir.clone())
580 .context(format!("Can't create early vm contexts for {cid}"))
581 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900582
Jiyong Park690c1ca2024-11-28 18:06:50 +0900583 if requires_vm_service(config) {
584 // Start VM service listening for connections from the new CID on port=CID.
585 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
586 let port = cid;
587 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
588 .context(format!("Could not start RpcServer on port {port}"))
589 .or_service_specific_exception(-1)?;
590 vm_server.start();
591 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
592 } else {
593 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
594 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900595 }
596
David Brazdil209074a2023-01-12 16:44:51 +0000597 fn create_vm_context(
598 &self,
599 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900600 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000601 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000602 const NUM_ATTEMPTS: usize = 5;
Jiyong Park18ceddc2025-03-18 13:30:02 +0900603 let name = get_name(config);
David Brazdil8cf8f482022-11-23 14:21:26 +0000604
605 for _ in 0..NUM_ATTEMPTS {
Jiyong Park18ceddc2025-03-18 13:30:02 +0900606 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(name, requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000607 let cid = vm_context.getCid()? as Cid;
608 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900609
610 // We don't need to start the VM service for custom VMs.
611 if !requires_vm_service(config) {
612 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
613 }
614
David Brazdil8cf8f482022-11-23 14:21:26 +0000615 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
616
617 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000618 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000619 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000620 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000621 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900622 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000623 }
624 Err(err) => {
625 warn!("Could not start RpcServer on port {}: {}", port, err);
626 }
627 }
628 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900629 Err(anyhow!("Too many attempts to create VM context failed"))
630 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000631 }
632
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000633 fn create_vm_internal(
634 &self,
635 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900636 console_out_fd: Option<&ParcelFileDescriptor>,
637 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000638 log_fd: Option<&ParcelFileDescriptor>,
639 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000640 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000641 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000642 let requester_uid = get_calling_uid();
643 let requester_debug_pid = get_calling_pid();
644
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800645 let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
646
Nikita Ioffe631717e2023-09-05 13:38:07 +0100647 check_config_features(config)?;
648
Inseob Kimecde8c02024-09-03 13:11:08 +0900649 if cfg!(early) {
650 check_config_allowed_for_early_vms(config)?;
651 }
652
Nikita Ioffeb1416122024-10-22 12:18:49 +0000653 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
654 info!("callers secontext: {}", caller_secontext);
655
David Brazdil209074a2023-01-12 16:44:51 +0000656 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900657 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800658 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900659 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900660 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900661 };
Inseob Kim1119d702022-05-02 18:01:58 +0900662
Alan Stokesfda70842023-12-20 17:50:14 +0000663 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100664 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900665 }
666
Nikita Ioffe5776f082023-02-10 21:38:26 +0000667 let gdb_port = extract_gdb_port(config);
668
669 // Additional permission checks if caller request gdb.
670 if gdb_port.is_some() {
671 check_gdb_allowed(config)?;
672 }
673
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800674 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900675 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800676 if let Some(dt_overlay) =
677 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
678 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900679 device_tree_overlays.push(dt_overlay);
680 }
681 if let Some(dtbo) = get_dtbo(config) {
682 let dtbo = File::from(
683 dtbo.as_ref()
684 .try_clone()
685 .context("Failed to create VM DTBO from ParcelFileDescriptor")
686 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
687 );
688 device_tree_overlays.push(dtbo);
689 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900690
Jaewan Kimf3143242024-03-15 06:56:31 +0000691 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000692 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900693 Some(prepare_ramdump_file(&temporary_directory)?)
694 } else {
695 None
696 };
697
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000698 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900699 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100700 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900701 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100702 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100703 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
704 Some(clone_file(fd)?)
705 } else if debug_config.dump_device_tree {
706 Some(prepare_dump_dt_file(&temporary_directory)?)
707 } else {
708 None
709 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000710
711 // Counter to generate unique IDs for temporary image files.
712 let mut next_temporary_image_id = 0;
713 // Files which are referred to from composite images. These must be mapped to the crosvm
714 // child process, and not closed before it is started.
715 let mut indirect_files = vec![];
716
Alan Stokes7bc146c2022-10-20 17:10:32 +0100717 let (is_app_config, config) = match config {
718 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
719 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900720 let config = load_app_config(config, &debug_config, &temporary_directory)
721 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900722 *is_protected = config.protectedVm;
723 let message = format!("Failed to load app config: {:?}", e);
724 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900725 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900726 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100727 (true, BorrowedOrOwned::Owned(config))
728 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000729 };
730 let config = config.as_ref();
731 *is_protected = config.protectedVm;
732
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000733 if !config.teeServices.is_empty() {
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000734 if !config.protectedVm {
735 return Err(anyhow!("only protected VMs can request tee services"))
736 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
737 }
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000738 check_tee_service_permission(&caller_secontext, &config.teeServices)
739 .with_log()
740 .or_binder_exception(ExceptionCode::SECURITY)?;
741 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000742
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000743 let mut system_tee_services = Vec::new();
744 let mut vendor_tee_services = Vec::new();
745 for tee_service in config.teeServices.clone() {
746 if !tee_service.starts_with("vendor.") {
747 check_known_tee_service(&tee_service)?;
748 system_tee_services.push(tee_service);
749 } else {
750 vendor_tee_services.push(tee_service);
751 }
752 }
753
754 // TODO(b/391774181): handle vendor tee services (which require talking to HAL) as well.
755 if !vendor_tee_services.is_empty() {
Nikita Ioffe832410f2025-03-07 15:24:44 +0000756 if !is_vm_capabilities_hal_supported() {
757 return Err(anyhow!(
758 "requesting access to tee services requires {VM_CAPABILITIES_HAL_IDENTIFIER}"
759 ))
760 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
761 }
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000762 return Err(anyhow!("support for vendor tee services is coming soon!"))
763 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
764 }
765
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000766 // TODO(b/391774181): remove this check in a follow-up patch.
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000767 if !system_tee_services.is_empty() {
768 return Err(anyhow!("support for system tee services is coming soon!"))
769 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
770 }
771
Jiyong Park3051ffe2024-11-26 14:41:58 +0900772 let kernel = maybe_clone_file(&config.kernel)?;
773 let initrd = maybe_clone_file(&config.initrd)?;
774
775 if config.protectedVm {
776 // Fail fast with a meaningful error message in case device doesn't support pVMs.
777 check_protected_vm_is_supported()?;
778
779 // In a protected VM, we require custom kernels to come from a trusted source
780 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800781 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
782 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900783
784 // Check if partition images are labeled incorrectly. This is to prevent random images
785 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
786 // from being loaded in a pVM. This applies to everything but the instance image in the
787 // raw config, and everything but the non-executable, generated partitions in the app
788 // config.
789 config
790 .disks
791 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800792 .flat_map(|disk| disk.image.as_ref())
793 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
794 .or_service_specific_exception(-1)?;
795 config
796 .disks
797 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900798 .flat_map(|disk| disk.partitions.iter())
799 .filter(|partition| {
800 if is_app_config {
801 !is_safe_app_partition(&partition.label)
802 } else {
803 !is_safe_raw_partition(&partition.label)
804 }
805 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800806 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900807 .or_service_specific_exception(-1)?;
808 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000809
Frederick Mayle279783a2025-03-18 16:16:45 -0700810 // Check if files for payloads and bases are on the same side of the Treble boundary as the
811 // calling process, as they may have unstable interfaces.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800812 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900813
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000814 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900815 write_zero_filler(&zero_filler_path)
816 .context("Failed to make composite image")
817 .with_log()
818 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000819
820 // Assemble disk images if needed.
821 let disks = config
822 .disks
823 .iter()
824 .map(|disk| {
825 assemble_disk_image(
826 disk,
827 &zero_filler_path,
828 &temporary_directory,
829 &mut next_temporary_image_id,
830 &mut indirect_files,
831 )
832 })
833 .collect::<Result<Vec<DiskFile>, _>>()?;
834
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700835 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
836
Jaewan Kimf43372b2024-12-13 18:33:58 +0900837 let (vfio_devices, dtbo) = match &config.devices {
838 AssignedDevices::Devices(devices) if !devices.is_empty() => {
839 let mut set = HashSet::new();
840 for device in devices.iter() {
841 let path = canonicalize(device)
842 .with_context(|| format!("can't canonicalize {device}"))
843 .or_service_specific_exception(-1)?;
844 if !set.insert(path) {
845 return Err(anyhow!("duplicated device {device}"))
846 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
847 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900848 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900849 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
850 let dtbo_file = File::from(
851 GLOBAL_SERVICE
852 .getDtboFile()?
853 .as_ref()
854 .try_clone()
855 .context("Failed to create VM DTBO from ParcelFileDescriptor")
856 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
857 );
858 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900859 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900860 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900861 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900862 let display_config = if cfg!(paravirtualized_devices) {
863 config
864 .displayConfig
865 .as_ref()
866 .map(DisplayConfig::new)
867 .transpose()
868 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
869 } else {
870 None
871 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700872 let gpu_config = if cfg!(paravirtualized_devices) {
873 config
874 .gpuConfig
875 .as_ref()
876 .map(GpuConfig::new)
877 .transpose()
878 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
879 } else {
880 None
881 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900882
Jeongik Chac181be72024-03-27 00:18:30 +0900883 let input_device_options = if cfg!(paravirtualized_devices) {
884 config
885 .inputDevices
886 .iter()
887 .map(to_input_device_option_from)
888 .collect::<Result<Vec<InputDeviceOption>, _>>()
889 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
890 } else {
891 vec![]
892 };
893
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900894 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900895 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900896 if *is_protected {
897 return Err(anyhow!("Network feature is not supported for pVM yet"))
898 .with_log()
899 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
900 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900901 Some(File::from(
902 GLOBAL_SERVICE
903 .createTapInterface(&get_this_pid().to_string())?
904 .as_ref()
905 .try_clone()
906 .context("Failed to get TAP interface from ParcelFileDescriptor")
907 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
908 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900909 } else {
910 None
911 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800912
913 let audio_config = if cfg!(paravirtualized_devices) {
914 config.audioConfig.as_ref().map(AudioConfig::new)
915 } else {
916 None
917 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900918
Elie Kheirallah29d72912024-08-07 20:17:26 +0000919 let usb_config = config
920 .usbConfig
921 .as_ref()
922 .map(UsbConfig::new)
923 .unwrap_or(Ok(UsbConfig { controller: false }))
924 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
925
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000926 let detect_hangup = is_app_config && gdb_port.is_none();
927
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800928 let custom_memory_backing_files = config
929 .customMemoryBackingFiles
930 .iter()
931 .map(|memory_backing_file| {
932 Ok((
933 clone_file(
934 memory_backing_file
935 .file
936 .as_ref()
937 .context("missing CustomMemoryBackingFile FD")
938 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
939 )?
940 .into(),
941 memory_backing_file.rangeStart as u64,
942 memory_backing_file.size as u64,
943 ))
944 })
945 .collect::<binder::Result<_>>()?;
946
Yuan Yao3843ea22025-02-27 06:22:20 +0000947 let memory_reclaim_supported =
948 system_properties::read_bool("hypervisor.memory_reclaim.supported", false)
949 .unwrap_or(false);
950
951 let balloon = config.balloon && memory_reclaim_supported;
952
953 if !balloon {
954 warn!(
955 "Memory balloon not enabled:
956 config.balloon={},hypervisor.memory_reclaim.supported={}",
957 config.balloon, memory_reclaim_supported
958 );
959 }
960
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000961 // Actually start the VM.
962 let crosvm_config = CrosvmConfig {
963 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000964 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000965 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000966 kernel,
967 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000968 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700969 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000970 params: config.params.to_owned(),
971 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900972 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700973 memory_mib: config
974 .memoryMib
975 .try_into()
976 .ok()
977 .and_then(NonZeroU32::new)
978 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800979 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000980 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900981 console_out_fd,
982 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000983 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900984 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000985 indirect_files,
986 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000987 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000988 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900989 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000990 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900991 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900992 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900993 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000994 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900995 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800996 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000997 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700998 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800999 audio_config,
Yuan Yao3843ea22025-02-27 06:22:20 +00001000 balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +00001001 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +00001002 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001003 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
1004 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -08001005 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001006 };
1007 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +01001008 VmInstance::new(
1009 crosvm_config,
1010 temporary_directory,
1011 requester_uid,
1012 requester_debug_pid,
1013 vm_context,
1014 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001015 .with_context(|| format!("Failed to create VM with config {:?}", config))
1016 .with_log()
1017 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001018 );
1019 state.add_vm(Arc::downgrade(&instance));
1020 Ok(VirtualMachine::create(instance))
1021 }
Jiyong Park8611a6c2021-07-09 18:17:44 +09001022}
1023
Alan Stokesfda70842023-12-20 17:50:14 +00001024/// Returns whether a VM config represents a "custom" virtual machine, which requires the
1025/// USE_CUSTOM_VIRTUAL_MACHINE.
1026fn is_custom_config(config: &VirtualMachineConfig) -> bool {
1027 match config {
1028 // Any raw (non-Microdroid) VM is considered custom.
1029 VirtualMachineConfig::RawConfig(_) => true,
1030 VirtualMachineConfig::AppConfig(config) => {
1031 // Some features are reserved for platform apps only, even when using
1032 // VirtualMachineAppConfig. Almost all of these features are grouped in the
1033 // CustomConfig struct:
1034 // - controlling CPUs;
1035 // - gdbPort is set, meaning that crosvm will start a gdb server;
1036 // - using anything other than the default kernel;
1037 // - specifying devices to be assigned.
1038 if config.customConfig.is_some() {
1039 true
1040 } else {
1041 // Additional custom features not included in CustomConfig:
1042 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +00001043 // - specifying extra APKs;
1044 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +09001045 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +00001046 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +09001047 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
1048 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +00001049 }
1050 }
1051 }
1052}
1053
Jiyong Park690c1ca2024-11-28 18:06:50 +09001054/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
1055/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
1056/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
1057/// "microdroid" we run VirtualMachineService
1058fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
1059 match config {
1060 VirtualMachineConfig::AppConfig(_) => true,
1061 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
1062 }
1063}
1064
Jiyong Park18ceddc2025-03-18 13:30:02 +09001065/// Returns the name of the config
1066fn get_name(config: &VirtualMachineConfig) -> &str {
1067 match config {
1068 VirtualMachineConfig::AppConfig(config) => &config.name,
1069 VirtualMachineConfig::RawConfig(config) => &config.name,
1070 }
1071}
1072
Seungjae Yoo14e60182024-02-21 13:28:31 +09001073fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
1074 let VirtualMachineConfig::AppConfig(config) = config else {
1075 return Ok(None);
1076 };
1077 let Some(custom_config) = &config.customConfig else {
1078 return Ok(None);
1079 };
1080 let Some(file) = custom_config.vendorImage.as_ref() else {
1081 return Ok(None);
1082 };
1083
1084 let file = clone_file(file)?;
1085 let size =
1086 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1087 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1088 .context("Failed to get vbmeta from microdroid-vendor.img")?;
1089
1090 for descriptor in vbmeta.descriptors()?.iter() {
1091 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1092 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1093 return Ok(Some(root_digest.as_bytes().to_vec()));
1094 }
1095 }
1096 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1097}
1098
Jaewan Kimf43372b2024-12-13 18:33:58 +09001099fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001100 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001101 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001102 temporary_directory: &Path,
1103) -> binder::Result<Option<File>> {
1104 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1105 // (e.g. instance-id)
1106 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1107 let host_ref_dt = if host_ref_dt.exists()
1108 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1109 {
1110 Some(host_ref_dt)
1111 } else {
1112 warn!("VM reference DT doesn't exist in host DT");
1113 None
1114 };
1115
1116 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1117 .context("Failed to extract vendor hashtree digest")
1118 .or_service_specific_exception(-1)?;
1119
Matt Gilbrideaade4272024-12-05 13:52:42 +00001120 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001121 info!(
1122 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1123 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1124 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001125 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001126 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001127 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001128 };
1129
Matt Gilbrideaade4272024-12-05 13:52:42 +00001130 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001131 let mut untrusted_props = Vec::with_capacity(2);
1132 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001133 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001134 let want_updatable = extract_want_updatable(config);
1135 if want_updatable && is_secretkeeper_supported() {
1136 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1137 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001138 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001139 let sk: Strong<dyn ISecretkeeper> =
1140 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1141 if sk.getInterfaceVersion()? >= 2 {
1142 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1143 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001144 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001145 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001146 }
1147 }
1148
1149 let device_tree_overlay = if host_ref_dt.is_some()
1150 || !untrusted_props.is_empty()
1151 || !trusted_props.is_empty()
1152 {
1153 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1154 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1155 let fdt =
1156 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1157 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1158 .or_service_specific_exception(-1)?;
1159 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1160 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1161 } else {
1162 None
1163 };
1164 Ok(device_tree_overlay)
1165}
1166
Jaewan Kimf43372b2024-12-13 18:33:58 +09001167fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1168 let VirtualMachineConfig::RawConfig(config) = config else {
1169 return None;
1170 };
1171 match &config.devices {
1172 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1173 _ => None,
1174 }
1175}
1176
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001177fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001178 let file = OpenOptions::new()
1179 .create_new(true)
1180 .read(true)
1181 .write(true)
1182 .open(zero_filler_path)
1183 .with_context(|| "Failed to create zero.img")?;
1184 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001185 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001186}
1187
David Brazdilf50c7a62023-04-19 14:22:42 +00001188fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1189 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1190 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1191 part.flush()
1192}
1193
1194fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1195 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1196 part.flush()
1197}
1198
1199fn round_up(input: u64, granularity: u64) -> u64 {
1200 if granularity == 0 {
1201 return input;
1202 }
1203 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1204 let result = input.checked_add(granularity - 1).unwrap_or(input);
1205 (result / granularity) * granularity
1206}
1207
Jeongik Chac181be72024-03-27 00:18:30 +09001208fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1209 Ok(match input_device {
1210 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1211 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1212 height: u32::try_from(single_touch.height)?,
1213 width: u32::try_from(single_touch.width)?,
1214 name: if !single_touch.name.is_empty() {
1215 Some(single_touch.name.clone())
1216 } else {
1217 None
1218 },
1219 },
1220 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1221 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1222 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001223 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1224 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1225 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001226 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1227 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1228 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001229 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1230 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1231 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001232 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1233 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1234 height: u32::try_from(trackpad.height)?,
1235 width: u32::try_from(trackpad.width)?,
1236 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1237 },
Jeongik Cha10494912024-07-16 11:19:50 +09001238 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1239 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1240 height: u32::try_from(multi_touch.height)?,
1241 width: u32::try_from(multi_touch.width)?,
1242 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1243 },
Jeongik Chac181be72024-03-27 00:18:30 +09001244 })
1245}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001246
1247fn assemble_shared_paths(
1248 shared_paths: &[SharedPath],
1249 temporary_directory: &Path,
1250) -> Result<Vec<SharedPathConfig>, Status> {
1251 if shared_paths.is_empty() {
1252 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1253 }
1254
1255 shared_paths
1256 .iter()
1257 .map(|path| {
1258 Ok(SharedPathConfig {
1259 path: path.sharedPath.clone(),
1260 host_uid: path.hostUid,
1261 host_gid: path.hostGid,
1262 guest_uid: path.guestUid,
1263 guest_gid: path.guestGid,
1264 mask: path.mask,
1265 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001266 socket_path: temporary_directory
1267 .join(&path.socketPath)
1268 .to_string_lossy()
1269 .to_string(),
1270 socket_fd: maybe_clone_file(&path.socketFd)?,
1271 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001272 })
1273 })
1274 .collect()
1275}
1276
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001277/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1278///
1279/// This may involve assembling a composite disk from a set of partition images.
1280fn assemble_disk_image(
1281 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001282 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001283 temporary_directory: &Path,
1284 next_temporary_image_id: &mut u64,
1285 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001286) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001287 let image = if !disk.partitions.is_empty() {
1288 if disk.image.is_some() {
1289 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001290 return Err(anyhow!("DiskImage contains both image and partitions"))
1291 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001292 }
1293
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001294 let composite_image_filenames =
1295 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1296 let (image, partition_files) = make_composite_image(
1297 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001298 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001299 &composite_image_filenames.composite,
1300 &composite_image_filenames.header,
1301 &composite_image_filenames.footer,
1302 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001303 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1304 .with_log()
1305 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001306
1307 // Pass the file descriptors for the various partition files to crosvm when it
1308 // is run.
1309 indirect_files.extend(partition_files);
1310
1311 image
1312 } else if let Some(image) = &disk.image {
1313 clone_file(image)?
1314 } else {
1315 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001316 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1317 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001318 };
1319
1320 Ok(DiskFile { image, writable: disk.writable })
1321}
1322
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001323fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1324 if let Some(ref mut params) = vm_config.params {
1325 params.push(' ');
1326 params.push_str(param)
1327 } else {
1328 vm_config.params = Some(param.to_owned())
1329 }
1330}
1331
Inseob Kim46257382024-01-03 15:41:22 +09001332fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1333 if config.extension()?.to_str()? != "json" {
1334 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001335 }
Inseob Kim46257382024-01-03 15:41:22 +09001336
1337 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1338}
1339
1340fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1341 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1342 let os_names =
1343 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1344
1345 Ok(os_names)
1346}
1347
1348fn get_supported_os_names() -> Result<HashSet<String>> {
1349 if !cfg!(vendor_modules) {
1350 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1351 }
1352
1353 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1354}
1355
1356fn is_valid_os(os_name: &str) -> bool {
1357 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001358}
1359
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001360fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1361 if !cfg!(vendor_modules) {
1362 return false;
1363 }
1364 match config {
1365 VirtualMachineConfig::RawConfig(_) => false,
1366 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1367 }
1368}
1369
Jooyung Han21e9b922021-06-26 04:14:16 +09001370fn load_app_config(
1371 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001372 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001373 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001374) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001375 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1376 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001377 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001378
Shikha Panwar22e70452022-10-10 18:32:55 +00001379 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1380 Some(clone_file(file)?)
1381 } else {
1382 None
1383 };
1384
Alan Stokesfda70842023-12-20 17:50:14 +00001385 let vm_payload_config;
1386 let extra_apk_files: Vec<_>;
1387 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001388 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001389 vm_payload_config =
1390 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1391 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1392 extra_apk_files = vm_payload_config
1393 .extra_apks
1394 .iter()
1395 .enumerate()
1396 .map(|(i, apk)| {
1397 File::open(PathBuf::from(&apk.path))
1398 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1399 })
1400 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001401 }
Alan Stokesfda70842023-12-20 17:50:14 +00001402 Payload::PayloadConfig(payload_config) => {
1403 vm_payload_config = create_vm_payload_config(payload_config)?;
1404 extra_apk_files =
1405 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1406 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001407 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001408
Inseob Kim89b24592024-02-23 18:59:43 +09001409 let payload_config_os = vm_payload_config.os.name.as_str();
1410 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1411 bail!("'os' in payload config is deprecated");
1412 }
1413
Inseob Kim172f9eb2023-11-06 17:02:08 +09001414 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001415 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001416 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001417 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001418 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001419
1420 // It is safe to construct a filename based on the os_name because we've already checked that it
1421 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001422 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1423 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001424 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001425
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001426 if let Some(custom_config) = &config.customConfig {
1427 if let Some(file) = custom_config.customKernelImage.as_ref() {
1428 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1429 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001430 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001431
1432 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001433 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001434 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001435 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001436
Jaewan Kimf43372b2024-12-13 18:33:58 +09001437 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001438 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001439
1440 for param in custom_config.extraKernelCmdlineParams.iter() {
1441 append_kernel_param(param, &mut vm_config);
1442 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001443
1444 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001445 }
1446
Andrew Walbrancc045902021-07-27 16:06:17 +00001447 if config.memoryMib > 0 {
1448 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001449 }
1450
Chris Wailes6177c662024-05-09 14:37:44 -07001451 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001452 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001453 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001454 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001455 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001456
Shikha Panwar22e70452022-10-10 18:32:55 +00001457 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001458 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001459
1460 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1461 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001462 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001463 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001464 temporary_directory,
1465 apk_file,
1466 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001467 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001468 &vm_payload_config,
1469 &mut vm_config,
1470 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001471
Andrew Walbrancc0db522021-07-12 17:03:42 +00001472 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001473}
1474
Frederick Mayle3a46b272025-02-10 21:55:49 -08001475fn check_partition_for_file(
1476 fd: &ParcelFileDescriptor,
1477 calling_partition: CallingPartition,
1478) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001479 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
Inseob Kim4d414452025-03-04 16:17:47 +09001480 let link = fs::read_link(&path).with_context(|| format!("can't read_link {path}"))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001481
1482 // microdroid vendor image is OK
1483 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1484 {
1485 return Ok(());
1486 }
1487
Inseob Kim4d414452025-03-04 16:17:47 +09001488 let fd_partition = find_partition(Some(&link))
1489 .with_context(|| format!("can't find_partition {}", link.display()))?;
1490 let is_fd_vendor =
1491 fd_partition == CallingPartition::Vendor || fd_partition == CallingPartition::Odm;
Frederick Mayle3a46b272025-02-10 21:55:49 -08001492 let is_caller_vendor =
1493 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001494
1495 if is_fd_vendor != is_caller_vendor {
1496 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001497 }
1498
1499 Ok(())
1500}
1501
Inseob Kime3e932d2024-12-16 20:06:57 +09001502fn check_partitions_for_files(
1503 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001504 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001505) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001506 config
1507 .disks
1508 .iter()
1509 .flat_map(|disk| disk.partitions.iter())
1510 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001511 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001512
Inseob Kime3e932d2024-12-16 20:06:57 +09001513 config
1514 .disks
1515 .iter()
1516 .filter_map(|disk| disk.image.as_ref())
1517 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1518
1519 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1520 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1521 config
1522 .bootloader
1523 .as_ref()
1524 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001525
1526 Ok(())
1527}
1528
Alan Stokes0d1ef782022-09-27 13:46:35 +01001529fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1530 let mut apk_zip = ZipArchive::new(apk_file)?;
1531 let config_file = apk_zip.by_name(config_path)?;
1532 Ok(serde_json::from_reader(config_file)?)
1533}
1534
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001535fn create_vm_payload_config(
1536 payload_config: &VirtualMachinePayloadConfig,
1537) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001538 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1539 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1540 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001541
1542 let payload_binary_name = &payload_config.payloadBinaryName;
1543 if payload_binary_name.contains('/') {
1544 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1545 }
1546
1547 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001548
1549 // The VM only cares about how many there are, these names are actually ignored.
1550 let extra_apk_count = payload_config.extraApks.len();
1551 let extra_apks =
1552 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1553
Nikita Ioffe901083f2025-01-20 01:54:28 +00001554 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1555 // The only payload delivered via Mainline module in this release requires
1556 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1557 // APIs, so we use the fact that the payload is granted
1558 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1559 // com.android.i18n APEX.
1560 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1561 // Microdroid pVMs.
1562 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1563 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1564 } else {
1565 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1566 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001567}
1568
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001569/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001570fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001571 temporary_directory: &Path,
1572 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001573) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001574 let id = *next_temporary_image_id;
1575 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001576 CompositeImageFilenames {
1577 composite: temporary_directory.join(format!("composite-{}.img", id)),
1578 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1579 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1580 }
1581}
1582
1583/// Filenames for a composite disk image, including header and footer partitions.
1584#[derive(Clone, Debug, Eq, PartialEq)]
1585struct CompositeImageFilenames {
1586 /// The composite disk image itself.
1587 composite: PathBuf,
1588 /// The header partition image.
1589 header: PathBuf,
1590 /// The footer partition image.
1591 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001592}
1593
Jiyong Park753553b2021-07-12 21:21:09 +09001594/// Checks whether the caller has a specific permission
1595fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001596 if cfg!(early) {
1597 // Skip permission check for early VMs, in favor of SELinux
1598 return Ok(());
1599 }
David Brazdil1f530702022-10-03 12:18:10 +01001600 let calling_pid = get_calling_pid();
1601 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001602 // Root can do anything
1603 if calling_uid == 0 {
1604 return Ok(());
1605 }
1606 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001607 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001608 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001609 Ok(())
1610 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001611 Err(anyhow!("does not have the {} permission", perm))
1612 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001613 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001614}
1615
Jiyong Park753553b2021-07-12 21:21:09 +09001616/// Check whether the caller of the current Binder method is allowed to manage VMs
1617fn check_manage_access() -> binder::Result<()> {
1618 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1619}
1620
Inseob Kim1119d702022-05-02 18:01:58 +09001621/// Check whether the caller of the current Binder method is allowed to create custom VMs
1622fn check_use_custom_virtual_machine() -> binder::Result<()> {
1623 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1624}
1625
Nikita Ioffe901083f2025-01-20 01:54:28 +00001626/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1627/// rollback protection schema.
1628fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1629 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1630}
1631
Alan Stokes185fe112023-01-10 16:20:55 +00001632/// Return whether a partition is exempt from selinux label checks, because we know that it does
1633/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001634fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001635 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001636 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001637 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001638 || label == "microdroid-apk-idsig"
1639 || label == "payload-metadata"
1640 || label.starts_with("extra-idsig-")
1641}
1642
Alice Wangc206b9b2023-08-28 14:13:51 +00001643/// Returns whether a partition with the given label is safe for a raw config VM.
1644fn is_safe_raw_partition(label: &str) -> bool {
1645 label == "vm-instance"
1646}
1647
Alan Stokes185fe112023-01-10 16:20:55 +00001648/// Check that a file SELinux label is acceptable.
1649///
1650/// 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 +09001651/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001652///
1653/// Note that sepolicy must also grant read access for these types to both virtualization
1654/// service and crosvm.
1655///
1656/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1657/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001658fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001659 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001660 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001661 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001662 | "staging_data_file" // updated/staged APEX images
1663 | "system_file" // immutable dm-verity protected partition
1664 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001665 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001666 => Ok(()),
Frederick Maylec8f27042025-02-26 12:35:26 -08001667 // It is difficult to require specific label types for vendor initiated VM's files.
1668 _ if calling_partition == CallingPartition::Vendor => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001669 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001670 }
1671}
1672
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001673fn check_label_for_partition(
1674 partition: &Partition,
1675 calling_partition: CallingPartition,
1676) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001677 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001678 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001679 .with_context(|| format!("Partition {} invalid", &partition.label))
1680}
1681
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001682fn check_label_for_kernel_files(
1683 kernel: &Option<File>,
1684 initrd: &Option<File>,
1685 calling_partition: CallingPartition,
1686) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001687 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001688 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001689 }
1690 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001691 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001692 }
1693 Ok(())
1694}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001695fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001696 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001697 name: &str,
1698 calling_partition: CallingPartition,
1699) -> Result<()> {
1700 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1701 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001702}
1703
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001704/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1705#[derive(Debug)]
1706struct VirtualMachine {
1707 instance: Arc<VmInstance>,
1708}
1709
1710impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001711 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001712 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001713 }
1714}
1715
1716impl Interface for VirtualMachine {}
1717
Devin Moore407df8f2024-08-27 19:39:16 +00001718impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001719 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001720 // Don't check permission. The owner of the VM might have passed this binder object to
1721 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001722 Ok(self.instance.cid as i32)
1723 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001724
Andrew Walbran6b650662021-09-07 13:13:23 +00001725 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001726 // Don't check permission. The owner of the VM might have passed this binder object to
1727 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001728 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001729 }
1730
1731 fn registerCallback(
1732 &self,
1733 callback: &Strong<dyn IVirtualMachineCallback>,
1734 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001735 // Don't check permission. The owner of the VM might have passed this binder object to
1736 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001737
1738 // Only register callback if it may be notified.
1739 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1740 let vm_state = self.instance.vm_state.lock().unwrap();
1741 if matches!(*vm_state, VmState::Dead) {
1742 warn!("Ignoring registerCallback() after VM is died");
1743 } else {
1744 self.instance.callbacks.add(callback.clone());
1745 }
1746 drop(vm_state);
1747
Andrew Walbrandae07162021-03-12 17:05:20 +00001748 Ok(())
1749 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001750
Andrew Walbranf8d94112021-09-07 11:45:36 +00001751 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001752 self.instance
1753 .start()
1754 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1755 .with_log()
1756 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001757 }
1758
Inseob Kima446f802022-07-11 19:46:37 +09001759 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001760 self.instance
1761 .kill()
1762 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1763 .with_log()
1764 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001765 }
1766
Yuan Yao3843ea22025-02-27 06:22:20 +00001767 fn isMemoryBalloonEnabled(&self) -> binder::Result<bool> {
1768 Ok(self.instance.balloon_enabled)
1769 }
1770
Keir Fraser48221ba2024-07-12 14:05:02 +00001771 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1772 let balloon = self
1773 .instance
1774 .get_memory_balloon()
1775 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1776 .with_log()
1777 .or_service_specific_exception(-1)?;
1778 Ok(balloon.try_into().unwrap())
1779 }
1780
1781 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001782 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001783 .set_memory_balloon(num_bytes.try_into().unwrap())
1784 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001785 .with_log()
1786 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001787 }
1788
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001789 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001790 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001791 return Err(Status::new_service_specific_error_str(
1792 IVirtualMachine::ERROR_UNEXPECTED,
1793 Some("Virtual Machine is not running"),
1794 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001795 }
Alan Stokes10c47672022-12-13 17:17:08 +00001796 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001797 if port < VSOCK_PRIV_PORT_MAX {
1798 return Err(Status::new_service_specific_error_str(
1799 IVirtualMachine::ERROR_UNEXPECTED,
1800 Some("Can't connect to privileged port {port}"),
1801 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001802 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001803 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1804 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001805 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001806 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001807 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001808
Devin Moore407df8f2024-08-27 19:39:16 +00001809 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1810 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1811 return Err(Status::new_service_specific_error_str(
1812 IVirtualMachine::ERROR_UNEXPECTED,
1813 Some("Virtual Machine is not running"),
1814 ));
1815 }
1816 let port = port as u32;
1817 if port < VSOCK_PRIV_PORT_MAX {
1818 return Err(Status::new_service_specific_error_str(
1819 IVirtualMachine::ERROR_UNEXPECTED,
1820 Some("Can't connect to privileged port {port}"),
1821 ));
1822 }
1823 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001824 let addr = sockaddr_vm {
1825 svm_family: AF_VSOCK as sa_family_t,
1826 svm_reserved1: 0,
1827 svm_port: port,
1828 svm_cid: cid,
1829 svm_zero: [0u8; 4],
1830 };
1831 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001832 let accessor = Accessor::new(name, get_connection_info);
1833 accessor
1834 .as_binder()
1835 .context("The newly created Accessor should always have a binder")
1836 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1837 }
1838
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001839 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1840 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1841 }
Jiyong Park23b67392024-07-04 13:51:42 +09001842
1843 fn suspend(&self) -> binder::Result<()> {
1844 self.instance
1845 .suspend()
1846 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1847 .with_log()
1848 .or_service_specific_exception(-1)
1849 }
1850
1851 fn resume(&self) -> binder::Result<()> {
1852 self.instance
1853 .resume()
1854 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1855 .with_log()
1856 .or_service_specific_exception(-1)
1857 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001858}
1859
1860impl Drop for VirtualMachine {
1861 fn drop(&mut self) {
1862 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001863 if let Err(e) = self.instance.kill() {
1864 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1865 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001866 }
1867}
1868
1869/// A set of Binders to be called back in response to various events on the VM, such as when it
1870/// dies.
1871#[derive(Debug, Default)]
1872pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1873
1874impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001875 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001876 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001877 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001878 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001879 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001880 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001881 }
1882 }
1883 }
1884
Inseob Kim14cb8692021-08-31 21:50:39 +09001885 /// Call all registered callbacks to notify that the payload is ready to serve.
1886 pub fn notify_payload_ready(&self, cid: Cid) {
1887 let callbacks = &*self.0.lock().unwrap();
1888 for callback in callbacks {
1889 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001890 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001891 }
1892 }
1893 }
1894
Inseob Kim2444af92021-08-31 01:22:50 +09001895 /// Call all registered callbacks to notify that the payload has finished.
1896 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1897 let callbacks = &*self.0.lock().unwrap();
1898 for callback in callbacks {
1899 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001900 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001901 }
1902 }
1903 }
1904
Jooyung Handd0a1732021-11-23 15:26:20 +09001905 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001906 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001907 let callbacks = &*self.0.lock().unwrap();
1908 for callback in callbacks {
1909 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001910 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001911 }
1912 }
1913 }
1914
Andrew Walbrandae07162021-03-12 17:05:20 +00001915 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001916 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001917 let mut callbacks = self.0.lock().unwrap();
1918 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001919 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001920 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001921 }
1922 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001923
1924 // Nothing to notify afterward because VM cannot be restarted.
1925 // Explicitly clear callbacks to prevent potential cyclic references
1926 // between callback and VmInstance.
1927 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001928 }
1929
1930 /// Add a new callback to the set.
1931 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1932 self.0.lock().unwrap().push(callback);
1933 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001934}
1935
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001936/// The mutable state of the VirtualizationService. There should only be one instance of this
1937/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001938#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001939struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001940 /// The VMs which have been started. When VMs are started a weak reference is added to this
1941 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1942 /// the Binder client are dropped the weak reference here will become invalid, and will be
1943 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001944 vms: Vec<Weak<VmInstance>>,
1945}
1946
1947impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001948 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001949 fn vms(&self) -> Vec<Arc<VmInstance>> {
1950 // Attempt to upgrade the weak pointers to strong pointers.
1951 self.vms.iter().filter_map(Weak::upgrade).collect()
1952 }
1953
1954 /// Add a new VM to the list.
1955 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1956 // Garbage collect any entries from the stored list which no longer exist.
1957 self.vms.retain(|vm| vm.strong_count() > 0);
1958
1959 // Actually add the new VM.
1960 self.vms.push(vm);
1961 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001962
Jiyong Park8611a6c2021-07-09 18:17:44 +09001963 /// Get a VM that corresponds to the given cid
1964 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1965 self.vms().into_iter().find(|vm| vm.cid == cid)
1966 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001967}
1968
Andrew Walbran6b650662021-09-07 13:13:23 +00001969/// Gets the `VirtualMachineState` of the given `VmInstance`.
1970fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001971 match &*instance.vm_state.lock().unwrap() {
1972 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1973 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001974 PayloadState::Starting => VirtualMachineState::STARTING,
1975 PayloadState::Started => VirtualMachineState::STARTED,
1976 PayloadState::Ready => VirtualMachineState::READY,
1977 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001978 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001979 },
1980 VmState::Dead => VirtualMachineState::DEAD,
1981 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001982 }
1983}
1984
David Brazdilf50c7a62023-04-19 14:22:42 +00001985/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001986pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1987 file.as_ref()
1988 .try_clone()
1989 .context("Failed to clone File from ParcelFileDescriptor")
1990 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001991 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001992}
1993
Andrew Walbrand3a84182021-09-07 14:48:52 +00001994/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001995fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001996 file.as_ref().map(clone_file).transpose()
1997}
1998
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001999/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09002000fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
2001 // SAFETY: ownership is transferred from stream to f
2002 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
2003 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002004}
2005
Jiyong Parkdcf17412022-02-08 15:07:23 +09002006/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002007fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
2008 VersionReq::parse(s)
2009 .with_context(|| format!("Invalid platform version requirement {}", s))
2010 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09002011}
2012
Jiyong Parked180932023-02-24 19:55:41 +09002013/// Create the empty ramdump file
2014fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
2015 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
2016 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
2017 // owner) for readout.
2018 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09002019 let ramdump = File::create(ramdump_path)
2020 .context("Failed to prepare ramdump file")
2021 .with_log()
2022 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09002023 Ok(ramdump)
2024}
2025
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01002026/// Create the empty device tree dump file
2027fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
2028 let path = temporary_directory.join("device_tree.dtb");
2029 let file = File::create(path)
2030 .context("Failed to prepare device tree dump file")
2031 .with_log()
2032 .or_service_specific_exception(-1)?;
2033 Ok(file)
2034}
2035
Nikita Ioffe5776f082023-02-10 21:38:26 +00002036fn is_protected(config: &VirtualMachineConfig) -> bool {
2037 match config {
2038 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
2039 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
2040 }
2041}
2042
2043fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
2044 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09002045 return Err(anyhow!("Can't use gdb with protected VMs"))
2046 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002047 }
2048
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002049 if get_debug_level(config) == Some(DebugLevel::NONE) {
2050 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
2051 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002052 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002053
2054 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00002055}
2056
Shikha Panwar61a74b52024-02-16 13:17:01 +00002057fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
2058 match config {
2059 VirtualMachineConfig::RawConfig(config) => config.instanceId,
2060 VirtualMachineConfig::AppConfig(config) => config.instanceId,
2061 }
2062}
2063
Alan Stokesc96b35e2024-05-03 13:21:20 +01002064fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
2065 match config {
2066 VirtualMachineConfig::RawConfig(_) => true,
2067 VirtualMachineConfig::AppConfig(config) => {
2068 let Some(custom) = &config.customConfig else { return true };
2069 custom.wantUpdatable
2070 }
2071 }
2072}
2073
Nikita Ioffe5776f082023-02-10 21:38:26 +00002074fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
2075 match config {
2076 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01002077 VirtualMachineConfig::AppConfig(config) => {
2078 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
2079 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00002080 }
2081}
2082
Nikita Ioffe631717e2023-09-05 13:38:07 +01002083fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2084 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2085 if let Some(custom_config) = &config.customConfig {
2086 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2087 return Err(anyhow!("vendor modules feature is disabled"))
2088 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2089 }
2090 }
2091 Ok(())
2092}
2093
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002094fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2095 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2096 if let Some(custom_config) = &config.customConfig {
2097 if !custom_config.devices.is_empty() {
2098 return Err(anyhow!("device assignment feature is disabled"))
2099 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2100 }
2101 }
2102 Ok(())
2103}
2104
Alan Stokesfda70842023-12-20 17:50:14 +00002105fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2106 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2107 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2108 if !payload_config.extraApks.is_empty() {
2109 return Err(anyhow!("multi-tenant feature is disabled"))
2110 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2111 }
2112 Ok(())
2113}
2114
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002115fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2116 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2117 if let Some(custom_config) = &config.customConfig {
2118 if !custom_config.extraKernelCmdlineParams.is_empty() {
2119 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2120 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2121 }
2122 }
2123 Ok(())
2124}
2125
Nikita Ioffe99548382024-10-21 15:54:46 +00002126fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2127 match config {
2128 VirtualMachineConfig::RawConfig(config) => {
2129 if !config.teeServices.is_empty() {
2130 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2131 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2132 }
2133 }
2134 VirtualMachineConfig::AppConfig(config) => {
2135 if let Some(custom_config) = &config.customConfig {
2136 if !custom_config.teeServices.is_empty() {
2137 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2138 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2139 }
2140 }
2141 }
2142 };
2143 Ok(())
2144}
2145
Nikita Ioffef934e812024-07-05 15:44:41 +00002146fn check_protected_vm_is_supported() -> binder::Result<()> {
2147 let is_pvm_supported =
2148 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2149 if is_pvm_supported {
2150 Ok(())
2151 } else {
2152 Err(anyhow!("pVM is not supported"))
2153 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2154 }
2155}
2156
Nikita Ioffe631717e2023-09-05 13:38:07 +01002157fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2158 if !cfg!(vendor_modules) {
2159 check_no_vendor_modules(config)?;
2160 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002161 if !cfg!(device_assignment) {
2162 check_no_devices(config)?;
2163 }
Alan Stokesfda70842023-12-20 17:50:14 +00002164 if !cfg!(multi_tenant) {
2165 check_no_extra_apks(config)?;
2166 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002167 if !cfg!(debuggable_vms_improvements) {
2168 check_no_extra_kernel_cmdline_params(config)?;
2169 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002170 if !cfg!(tee_services_allowlist) {
2171 check_no_tee_services(config)?;
2172 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002173 Ok(())
2174}
2175
Inseob Kimecde8c02024-09-03 13:11:08 +09002176fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2177 check_no_vendor_modules(config)?;
2178 check_no_devices(config)?;
2179
2180 Ok(())
2181}
2182
Inseob Kim0168b462022-12-27 14:54:35 +09002183fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002184 fd: Option<&ParcelFileDescriptor>,
2185 tag: String,
2186) -> Result<Option<File>, Status> {
2187 if let Some(fd) = fd {
2188 return Ok(Some(clone_file(fd)?));
2189 }
2190
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002191 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002192 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002193
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002194 let mut reader = BufReader::new(File::from(read_fd));
2195 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002196
Frederick Mayle26e41af2025-02-05 18:30:29 -08002197 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002198 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002199 buf.clear();
2200 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002201 match reader.read_until(b'\n', &mut buf) {
2202 Ok(0) => {
2203 // EOF
2204 return;
2205 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002206 Ok(_size) => {
2207 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002208 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002209 // Logs sent via TTY usually end lines with "\r\n".
2210 if buf.last() == Some(&b'\r') {
2211 buf.pop();
2212 }
Inseob Kim0168b462022-12-27 14:54:35 +09002213 }
2214 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2215 }
2216 Err(e) => {
2217 error!("Could not read console pipe: {:?}", e);
2218 return;
2219 }
2220 };
2221 });
2222
2223 Ok(Some(write_fd))
2224}
2225
Jooyung Han35edb8f2021-07-01 16:17:16 +09002226/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2227/// it doesn't require that T implements Clone.
2228enum BorrowedOrOwned<'a, T> {
2229 Borrowed(&'a T),
2230 Owned(T),
2231}
2232
Chris Wailes73a1eb72025-01-15 11:56:43 -08002233impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002234 fn as_ref(&self) -> &T {
2235 match self {
2236 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002237 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002238 }
2239 }
2240}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002241
2242/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2243#[derive(Debug, Default)]
2244struct VirtualMachineService {
2245 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002246 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002247}
2248
2249impl Interface for VirtualMachineService {}
2250
2251impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002252 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2253 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002254 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002255 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002256 vm.update_payload_state(PayloadState::Started)
2257 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002258 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002259
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002260 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2261 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002262 Ok(())
2263 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002264 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002265 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002266 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002267 }
Inseob Kim2444af92021-08-31 01:22:50 +09002268
Inseob Kimc7d28c72021-10-25 14:28:10 +00002269 fn notifyPayloadReady(&self) -> binder::Result<()> {
2270 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002271 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002272 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002273 vm.update_payload_state(PayloadState::Ready)
2274 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002275 vm.callbacks.notify_payload_ready(cid);
2276 Ok(())
2277 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002278 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002279 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002280 }
2281 }
2282
Inseob Kimc7d28c72021-10-25 14:28:10 +00002283 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2284 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002285 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002286 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002287 vm.update_payload_state(PayloadState::Finished)
2288 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002289 vm.callbacks.notify_payload_finished(cid, exit_code);
2290 Ok(())
2291 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002292 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002293 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002294 }
2295 }
2296
Alan Stokes2bead0d2022-09-05 16:58:34 +01002297 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002298 let cid = self.cid;
2299 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002300 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002301 vm.update_payload_state(PayloadState::Finished)
2302 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002303 vm.callbacks.notify_error(cid, error_code, message);
2304 Ok(())
2305 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002306 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002307 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002308 }
2309 }
Alice Wangc2fec932023-02-23 16:24:02 +00002310
Shikha Panware45e9422024-02-28 21:18:10 +00002311 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2312 if !is_secretkeeper_supported() {
2313 return Err(StatusCode::NAME_NOT_FOUND)?;
2314 }
2315 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2316 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002317 }
2318
Alice Wange64dd182024-01-17 15:57:55 +00002319 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2320 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002321 }
Shikha Panwareeae6402025-02-06 19:05:31 +00002322
2323 fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2324 GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2325 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002326}
2327
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002328fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002329 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2330 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002331}
2332
Nikita Ioffe832410f2025-03-07 15:24:44 +00002333fn is_vm_capabilities_hal_supported() -> bool {
2334 binder::is_declared(VM_CAPABILITIES_HAL_IDENTIFIER)
2335 .expect("failed to check if {VM_CAPABILITIES_HAL_IDENTIFIER} is present")
2336}
2337
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002338impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002339 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002340 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002341 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002342 BinderFeatures::default(),
2343 )
2344 }
2345}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002346
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002347struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2348
2349impl Interface for SecretkeeperProxy {}
2350
2351impl ISecretkeeper for SecretkeeperProxy {
2352 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2353 // Pass the request to the channel, and read the response.
2354 self.0.processSecretManagementRequest(req)
2355 }
2356
2357 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2358 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2359 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2360 }
2361
2362 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2363 self.0.deleteIds(ids)
2364 }
2365
2366 fn deleteAll(&self) -> binder::Result<()> {
2367 self.0.deleteAll()
2368 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002369
2370 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2371 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2372 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2373 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2374 // use this API from the proxy.
2375 Err(ExceptionCode::SECURITY.into())
2376 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002377}
2378
2379struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2380
2381impl Interface for AuthGraphKeyExchangeProxy {}
2382
2383impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2384 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2385 self.0.create()
2386 }
2387
2388 fn init(
2389 &self,
2390 peer_pub_key: &PubKey,
2391 peer_id: &Identity,
2392 peer_nonce: &[u8],
2393 peer_version: i32,
2394 ) -> binder::Result<KeInitResult> {
2395 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2396 }
2397
2398 fn finish(
2399 &self,
2400 peer_pub_key: &PubKey,
2401 peer_id: &Identity,
2402 peer_signature: &SessionIdSignature,
2403 peer_nonce: &[u8],
2404 peer_version: i32,
2405 own_key: &Key,
2406 ) -> binder::Result<SessionInfo> {
2407 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2408 }
2409
2410 fn authenticationComplete(
2411 &self,
2412 peer_signature: &SessionIdSignature,
2413 shared_keys: &[AuthgraphArc; 2],
2414 ) -> binder::Result<[AuthgraphArc; 2]> {
2415 self.0.authenticationComplete(peer_signature, shared_keys)
2416 }
2417}
2418
Inseob Kimecde8c02024-09-03 13:11:08 +09002419// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002420#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002421struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002422 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002423 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002424 path: String,
2425}
2426
2427#[derive(Debug, Default, Deserialize)]
2428struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002429 early_vm: Vec<EarlyVm>,
2430}
2431
Alice Wang78dd87a2025-02-13 08:56:07 +00002432impl EarlyVm {
2433 /// Verifies that the provided executable path matches the expected path stored in the XML
2434 /// configuration.
2435 /// If the provided path starts with `/system`, it will be stripped before comparison.
2436 fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2437 let actual_path = calling_exe_path.as_ref();
2438 if Path::new(&self.path)
2439 == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2440 {
2441 return Ok(());
2442 }
2443 Err(Status::new_service_specific_error_str(
2444 -1,
2445 Some(format!(
2446 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2447 self.name,
2448 self.path,
2449 actual_path.display()
2450 )),
2451 ))
2452 }
2453}
2454
Frederick Mayle3a46b272025-02-10 21:55:49 -08002455static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002456 LazyLock::new(|| Mutex::new(HashMap::new()));
2457
Frederick Mayle3a46b272025-02-10 21:55:49 -08002458fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002459 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002460 CallingPartition::System => 100..200,
2461 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2462 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2463 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002464 }
2465}
2466
Inseob Kim7e1877b2024-11-07 17:28:56 +09002467fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002468 if !xml_path.exists() {
2469 bail!("{} doesn't exist", xml_path.display());
2470 }
2471
2472 let xml =
2473 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2474 let xml = String::from_utf8(xml)
2475 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2476 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2477 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2478
Inseob Kim7e1877b2024-11-07 17:28:56 +09002479 Ok(early_vms.early_vm)
2480}
Inseob Kimecde8c02024-09-03 13:11:08 +09002481
Inseob Kim7e1877b2024-11-07 17:28:56 +09002482fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2483 for early_vm in early_vms {
2484 let cid = early_vm
2485 .cid
2486 .try_into()
2487 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2488
2489 ensure!(
2490 cid_range.contains(&cid),
2491 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2492 early_vm.name
2493 );
2494 }
2495 Ok(())
2496}
2497
Frederick Mayle3a46b272025-02-10 21:55:49 -08002498fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002499 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2500
Frederick Mayle3a46b272025-02-10 21:55:49 -08002501 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002502 return Ok(result.clone());
2503 }
2504
2505 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2506 let mut early_vms = Vec::new();
2507 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2508 match entry {
2509 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2510 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2511 }
2512 }
2513
Frederick Mayle3a46b272025-02-10 21:55:49 -08002514 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002515 .with_context(|| format!("CID validation for {partition} failed"))?;
2516
Frederick Mayle3a46b272025-02-10 21:55:49 -08002517 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002518
2519 Ok(early_vms)
2520}
2521
2522fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2523 let mut found_vm: Option<&EarlyVm> = None;
2524
2525 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002526 if early_vm.name != name {
2527 continue;
2528 }
2529
Inseob Kimecde8c02024-09-03 13:11:08 +09002530 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002531 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002532 }
2533
2534 found_vm = Some(early_vm);
2535 }
2536
Inseob Kim7e1877b2024-11-07 17:28:56 +09002537 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002538}
2539
Frederick Mayle3a46b272025-02-10 21:55:49 -08002540fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002541 let early_vms = get_early_vms_in_partition(partition)
2542 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2543
2544 Ok(find_early_vm(&early_vms, name)
2545 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2546 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002547}
2548
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002549#[cfg(test)]
2550mod tests {
2551 use super::*;
2552
2553 #[test]
2554 fn test_is_allowed_label_for_partition() -> Result<()> {
2555 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002556 (CallingPartition::System, "u:object_r:system_file:s0", true),
2557 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2558 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2559 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2560 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2561 (CallingPartition::System, "invalid", false),
2562 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2563 (
2564 CallingPartition::System,
2565 "user:role:apk_data_file:severity:categories:extraneous",
2566 false,
2567 ),
2568 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2569 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002570 ];
2571
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002572 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002573 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002574 let result = check_label_is_allowed(&context, calling_partition);
2575 if expected_valid != result.is_ok() {
2576 bail!(
2577 "Expected label {label} to be {} for {calling_partition} partition",
2578 if expected_valid { "allowed" } else { "disallowed" }
2579 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002580 }
2581 }
2582 Ok(())
2583 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002584
2585 #[test]
2586 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2587 let apk = tempfile::tempfile().unwrap();
2588 let idsig = tempfile::tempfile().unwrap();
2589
2590 let ret = create_or_update_idsig_file(
2591 &ParcelFileDescriptor::new(apk),
2592 &ParcelFileDescriptor::new(idsig),
2593 );
2594 assert!(ret.is_err(), "should fail");
2595 Ok(())
2596 }
2597
2598 #[test]
2599 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2600 let tmp_dir = tempfile::TempDir::new().unwrap();
2601 let apk = File::open(tmp_dir.path()).unwrap();
2602 let idsig = tempfile::tempfile().unwrap();
2603
2604 let ret = create_or_update_idsig_file(
2605 &ParcelFileDescriptor::new(apk),
2606 &ParcelFileDescriptor::new(idsig),
2607 );
2608 assert!(ret.is_err(), "should fail");
2609 Ok(())
2610 }
2611
2612 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2613 /// on ext4 filesystem is passed.
2614 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2615 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2616 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2617 #[test]
2618 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2619 // APEXes are backed by the ext4.
2620 let apk = File::open("/apex/com.android.virt/").unwrap();
2621 let idsig = tempfile::tempfile().unwrap();
2622
2623 let ret = create_or_update_idsig_file(
2624 &ParcelFileDescriptor::new(apk),
2625 &ParcelFileDescriptor::new(idsig),
2626 );
2627 assert!(ret.is_err(), "should fail");
2628 Ok(())
2629 }
Jiyong Park8d192952023-06-26 14:29:51 +09002630
2631 #[test]
2632 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2633 use std::io::Seek;
2634
2635 // Pick any APK
2636 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2637 let mut idsig = tempfile::tempfile().unwrap();
2638
2639 create_or_update_idsig_file(
2640 &ParcelFileDescriptor::new(apk.try_clone()?),
2641 &ParcelFileDescriptor::new(idsig.try_clone()?),
2642 )?;
2643 let modified_orig = idsig.metadata()?.modified()?;
2644 apk.rewind()?;
2645 idsig.rewind()?;
2646
2647 // Call the function again
2648 create_or_update_idsig_file(
2649 &ParcelFileDescriptor::new(apk.try_clone()?),
2650 &ParcelFileDescriptor::new(idsig.try_clone()?),
2651 )?;
2652 let modified_new = idsig.metadata()?.modified()?;
2653 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2654 Ok(())
2655 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002656
2657 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002658 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2659 use std::io::Read;
2660
2661 // Pick any APK
2662 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2663 let idsig_empty = tempfile::tempfile().unwrap();
2664 let mut idsig_invalid = tempfile::tempfile().unwrap();
2665 idsig_invalid.write_all(b"Oops")?;
2666
2667 // Create new idsig
2668 create_or_update_idsig_file(
2669 &ParcelFileDescriptor::new(apk.try_clone()?),
2670 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2671 )?;
2672 apk.rewind()?;
2673
2674 // Update idsig_invalid
2675 create_or_update_idsig_file(
2676 &ParcelFileDescriptor::new(apk.try_clone()?),
2677 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2678 )?;
2679
2680 // Ensure the 2 idsig files have same size!
2681 assert!(
2682 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2683 "idsig files differ in size"
2684 );
2685 // Ensure the 2 idsig files have same content!
2686 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2687 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2688 }
2689 Ok(())
2690 }
2691 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002692 fn test_append_kernel_param_first_param() {
2693 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2694 append_kernel_param("foo=1", &mut vm_config);
2695 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2696 }
2697
2698 #[test]
2699 fn test_append_kernel_param() {
2700 let mut vm_config =
2701 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2702 append_kernel_param("bar=42", &mut vm_config);
2703 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2704 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002705
Inseob Kim46257382024-01-03 15:41:22 +09002706 fn test_extract_os_name_from_config_path(
2707 path: &Path,
2708 expected_result: Option<&str>,
2709 ) -> Result<()> {
2710 let result = extract_os_name_from_config_path(path);
2711 if result.as_deref() != expected_result {
2712 bail!("Expected {:?} but was {:?}", expected_result, &result)
2713 }
2714 Ok(())
2715 }
2716
2717 #[test]
2718 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2719 test_extract_os_name_from_config_path(
2720 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2721 Some("microdroid"),
2722 )
2723 }
2724
2725 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002726 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2727 test_extract_os_name_from_config_path(
2728 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2729 Some("microdroid_16k"),
2730 )
2731 }
2732
2733 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002734 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2735 test_extract_os_name_from_config_path(
2736 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2737 Some("microdroid_gki-android14-6.1"),
2738 )
2739 }
2740
2741 #[test]
2742 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2743 test_extract_os_name_from_config_path(
2744 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2745 None,
2746 )
2747 }
2748
2749 #[test]
2750 fn test_extract_os_name_from_configs() -> Result<()> {
2751 let tmp_dir = tempfile::TempDir::new()?;
2752 let tmp_dir_path = tmp_dir.path().to_owned();
2753
2754 let mut os_names: HashSet<String> = HashSet::new();
2755 os_names.insert("microdroid".to_owned());
2756 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2757 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2758
2759 // config files
2760 for os_name in &os_names {
2761 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2762 }
2763
2764 // fake files not related to configs
2765 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2766 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2767
2768 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2769 Some(s) => s.to_owned(),
2770 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2771 };
2772
2773 let result = extract_os_names_from_configs(&glob_pattern)?;
2774 if result != os_names {
2775 bail!("Expected {:?} but was {:?}", os_names, result);
2776 }
2777 Ok(())
2778 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002779
2780 #[test]
2781 fn test_find_early_vms_from_xml() -> Result<()> {
2782 let tmp_dir = tempfile::TempDir::new()?;
2783 let tmp_dir_path = tmp_dir.path().to_owned();
2784 let xml_path = tmp_dir_path.join("early_vms.xml");
2785
2786 std::fs::write(
2787 &xml_path,
2788 br#"<?xml version="1.0" encoding="utf-8"?>
2789 <early_vms>
2790 <early_vm>
2791 <name>vm_demo_native_early</name>
2792 <cid>123</cid>
2793 <path>/system/bin/vm_demo_native_early</path>
2794 </early_vm>
2795 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002796 <name>vm_demo_native_early_2</name>
2797 <cid>456</cid>
2798 <path>/system/bin/vm_demo_native_early_2</path>
2799 </early_vm>
2800 </early_vms>
2801 "#,
2802 )?;
2803
2804 let cid_range = 100..1000;
2805
2806 let early_vms = get_early_vms_in_path(&xml_path)?;
2807 validate_cid_range(&early_vms, &cid_range)?;
2808
2809 let test_cases = [
2810 (
2811 "vm_demo_native_early",
2812 EarlyVm {
2813 name: "vm_demo_native_early".to_owned(),
2814 cid: 123,
2815 path: "/system/bin/vm_demo_native_early".to_owned(),
2816 },
2817 ),
2818 (
2819 "vm_demo_native_early_2",
2820 EarlyVm {
2821 name: "vm_demo_native_early_2".to_owned(),
2822 cid: 456,
2823 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2824 },
2825 ),
2826 ];
2827
2828 for (name, expected) in test_cases {
2829 let result = find_early_vm(&early_vms, name)?;
2830 assert_eq!(result, &expected);
2831 }
2832
2833 Ok(())
2834 }
2835
2836 #[test]
2837 fn test_invalid_cid_validation() -> Result<()> {
2838 let tmp_dir = tempfile::TempDir::new()?;
2839 let xml_path = tmp_dir.path().join("early_vms.xml");
2840
2841 let cid_range = 100..1000;
2842
2843 for cid in [-1, 999999] {
2844 std::fs::write(
2845 &xml_path,
2846 format!(
2847 r#"<?xml version="1.0" encoding="utf-8"?>
2848 <early_vms>
2849 <early_vm>
2850 <name>vm_demo_invalid_cid</name>
2851 <cid>{cid}</cid>
2852 <path>/system/bin/vm_demo_invalid_cid</path>
2853 </early_vm>
2854 </early_vms>
2855 "#
2856 ),
2857 )?;
2858
2859 let early_vms = get_early_vms_in_path(&xml_path)?;
2860 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2861 }
2862
2863 Ok(())
2864 }
2865
2866 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002867 fn test_symlink_to_system_ext_supported() -> Result<()> {
2868 let link_path = Path::new("/system/system_ext/file");
2869 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002870 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002871 Ok(())
2872 }
2873
2874 #[test]
2875 fn test_symlink_to_product_supported() -> Result<()> {
2876 let link_path = Path::new("/system/product/file");
2877 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002878 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002879 Ok(())
2880 }
2881
2882 #[test]
Frederick Mayle2192baf2025-02-26 11:27:22 -08002883 fn test_vendor_in_data() {
2884 assert_eq!(
2885 CallingPartition::Vendor,
2886 find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap()
2887 );
2888 }
2889
2890 #[test]
Alice Wang78dd87a2025-02-13 08:56:07 +00002891 fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2892 let early_vm = EarlyVm {
2893 name: "vm_demo_native_early".to_owned(),
2894 cid: 123,
2895 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2896 };
2897 let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2898 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2899 }
2900
2901 #[test]
2902 fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2903 let early_vm = EarlyVm {
2904 name: "vm_demo_native_early".to_owned(),
2905 cid: 123,
2906 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2907 };
2908 let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2909 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2910 }
2911
2912 #[test]
2913 fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2914 let early_vm = EarlyVm {
2915 name: "vm_demo_native_early".to_owned(),
2916 cid: 123,
2917 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2918 };
2919 let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2920 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2921 }
2922
2923 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002924 fn test_duplicated_early_vms() -> Result<()> {
2925 let tmp_dir = tempfile::TempDir::new()?;
2926 let tmp_dir_path = tmp_dir.path().to_owned();
2927 let xml_path = tmp_dir_path.join("early_vms.xml");
2928
2929 std::fs::write(
2930 &xml_path,
2931 br#"<?xml version="1.0" encoding="utf-8"?>
2932 <early_vms>
2933 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002934 <name>vm_demo_duplicated_name</name>
2935 <cid>456</cid>
2936 <path>/system/bin/vm_demo_duplicated_name_1</path>
2937 </early_vm>
2938 <early_vm>
2939 <name>vm_demo_duplicated_name</name>
2940 <cid>789</cid>
2941 <path>/system/bin/vm_demo_duplicated_name_2</path>
2942 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002943 </early_vms>
2944 "#,
2945 )?;
2946
2947 let cid_range = 100..1000;
2948
Inseob Kim7e1877b2024-11-07 17:28:56 +09002949 let early_vms = get_early_vms_in_path(&xml_path)?;
2950 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002951
Inseob Kim7e1877b2024-11-07 17:28:56 +09002952 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002953
2954 Ok(())
2955 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002956}