blob: e143c4132c43f92d22e185a04a373bc2df05f6bd [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
David Brazdilf50c7a62023-04-19 14:22:42 +0000120const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
121
122/// crosvm requires all partitions to be a multiple of 4KiB.
123const PARTITION_GRANULARITY_BYTES: u64 = 4096;
124
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000125const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
126
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100127pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
128 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900129 if cfg!(early) {
130 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
131 } else {
132 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
133 .expect("Could not connect to VirtualizationServiceInternal")
134 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100135 });
136static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
137 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000138
Inseob Kime3e932d2024-12-16 20:06:57 +0900139static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
140 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
141 match fs::read_link(&calling_exe_link) {
142 Ok(calling_exe_path) => Some(calling_exe_path),
143 Err(e) => {
144 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
145 // discourage vendor apps, regarding such cases as system is safer.
146 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
147 // apps.
148 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
149 None
150 }
151 }
152});
153
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000154// TODO(ioffe): add service for guest-ffa.
155const KNOWN_TEE_SERVICES: [&str; 0] = [];
156
157fn check_known_tee_service(tee_service: &str) -> binder::Result<()> {
158 if !KNOWN_TEE_SERVICES.contains(&tee_service) {
159 return Err(anyhow!("unknown tee_service {tee_service}"))
160 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
161 }
162 Ok(())
163}
164
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000165fn create_or_update_idsig_file(
166 input_fd: &ParcelFileDescriptor,
167 idsig_fd: &ParcelFileDescriptor,
168) -> Result<()> {
169 let mut input = clone_file(input_fd)?;
170 let metadata = input.metadata().context("failed to get input metadata")?;
171 if !metadata.is_file() {
172 bail!("input is not a regular file");
173 }
Alan Stokes25f69362023-03-06 16:51:54 +0000174 let mut sig =
175 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
176 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000177
178 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900179
180 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
181 // if the idsig file already has the same APK digest.
182 if output.metadata()?.len() > 0 {
183 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
184 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
185 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
186 return Ok(());
187 }
188 }
189 // if we fail to read v4signature from output, that's fine. User can pass a random file.
190 // We will anyway overwrite the file to the v4signature generated from input_fd.
191 }
192
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000193 output
194 .seek(SeekFrom::Start(0))
195 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000196 output.set_len(0).context("failed to set_len on the idsig output")?;
197 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000198 Ok(())
199}
200
Alan Stokes25f69362023-03-06 16:51:54 +0000201fn get_current_sdk() -> Result<u32> {
202 let current_sdk = system_properties::read("ro.build.version.sdk")?;
203 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
204 current_sdk.parse().context("Malformed SDK version")
205}
206
David Brazdil4b4c5102022-12-19 22:56:20 +0000207pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
208 for dir_entry in read_dir(path)? {
209 remove_file(dir_entry?.path())?;
210 }
211 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100212}
213
David Brazdil528e0472022-10-10 15:06:02 +0100214/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000215#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000216pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900217 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000218}
219
Shikha Panward8e35422021-10-11 13:51:27 +0000220impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000222 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
223 let state = &mut *self.state.lock().unwrap();
224 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000225 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000226 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000227 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
228 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000229 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000230 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000231 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000232 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
233 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000234 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000235 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000236 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000237 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000238 .or(Err(StatusCode::UNKNOWN_ERROR))?;
239 }
240 Ok(())
241 }
242}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000243impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000244 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
245 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000246 ///
247 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000248 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000249 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000250 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900251 console_out_fd: Option<&ParcelFileDescriptor>,
252 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000253 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000254 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000255 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000256 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900257 let ret = self.create_vm_internal(
258 config,
259 console_out_fd,
260 console_in_fd,
261 log_fd,
262 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000263 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900264 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000265 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000266 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000267 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000268
Shikha Panwar61a74b52024-02-16 13:17:01 +0000269 /// Allocate a new instance_id to the VM
270 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000271 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000272 GLOBAL_SERVICE.allocateInstanceId()
273 }
274
Andrew Walbrandff3b942021-06-09 15:20:36 +0000275 /// Initialise an empty partition image of the given size to be used as a writable partition.
276 fn initializeWritablePartition(
277 &self,
278 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000279 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900280 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000281 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900282 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 let size_bytes = size_bytes
284 .try_into()
285 .with_context(|| format!("Invalid size: {}", size_bytes))
286 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000287 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000288 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000289 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000290 image
291 .seek(SeekFrom::Start(0))
292 .context("failed to move cursor to start")
293 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900294 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700295 // Set the file length. In most filesystems, this will not allocate any physical disk
296 // space, it will only change the logical size.
297 image
298 .set_len(size_bytes)
299 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000301
302 match partition_type {
303 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700304 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
305 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000306 _ => Err(Error::new(
307 ErrorKind::Unsupported,
308 format!("Unsupported partition type {:?}", partition_type),
309 )),
310 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900311 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
312 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000313
314 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000315 }
316
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800317 fn setEncryptedStorageSize(
318 &self,
319 image_fd: &ParcelFileDescriptor,
320 size: i64,
321 ) -> binder::Result<()> {
322 check_manage_access()?;
323
324 let size = size
325 .try_into()
326 .with_context(|| format!("Invalid size: {}", size))
327 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
328 let size = round_up(size, PARTITION_GRANULARITY_BYTES);
329
330 let image = clone_file(image_fd)?;
331 let image_size = image.metadata().unwrap().len();
332
333 if image_size > size {
334 return Err(Status::new_exception_str(
335 ExceptionCode::ILLEGAL_ARGUMENT,
336 Some("Can't shrink encrypted storage"),
337 ));
338 }
339 // Reset the file length. In most filesystems, this will not allocate any physical disk
340 // space, it will only change the logical size.
341 image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
342 Ok(())
343 }
344
Jiyong Park0a248432021-08-20 23:32:39 +0900345 /// Creates or update the idsig file by digesting the input APK file.
346 fn createOrUpdateIdsigFile(
347 &self,
348 input_fd: &ParcelFileDescriptor,
349 idsig_fd: &ParcelFileDescriptor,
350 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900351 check_manage_access()?;
352
Jiyong Park2227eaa2023-08-04 11:59:18 +0900353 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900354 Ok(())
355 }
356
Andrew Walbran320b5602021-03-04 16:11:12 +0000357 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
358 /// and as such is only permitted from the shell user.
359 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000360 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000361 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000362 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900363
364 /// Get a list of assignable device types.
365 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
366 // Delegate to the global service, including checking the permission.
367 GLOBAL_SERVICE.getAssignableDevices()
368 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100369
Inseob Kim46257382024-01-03 15:41:22 +0900370 /// Get a list of supported OSes.
371 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
372 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
373 }
374
Jaewan Kimabd328b2024-12-10 15:59:33 +0900375 /// Get printable debug policy for testing and debugging
376 fn getDebugPolicy(&self) -> binder::Result<String> {
377 let debug_policy = DebugPolicy::from_host();
378 Ok(format!("{debug_policy:?}"))
379 }
380
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100381 /// Returns whether given feature is enabled
382 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
383 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000384 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100385 }
Alice Wange64dd182024-01-17 15:57:55 +0000386
387 fn enableTestAttestation(&self) -> binder::Result<()> {
388 GLOBAL_SERVICE.enableTestAttestation()
389 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000390
391 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
392 check_manage_access()?;
393 GLOBAL_SERVICE.isRemoteAttestationSupported()
394 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000395
396 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
397 // The response is specific to Microdroid. Updatable VMs are only possible if device
398 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
399 // this, however other guest OSes may do things differently.
400 check_manage_access()?;
401 Ok(is_secretkeeper_supported())
402 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000403
Shikha Panwar07d701c2024-03-28 14:43:52 +0000404 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
405 check_manage_access()?;
406 GLOBAL_SERVICE.removeVmInstance(instance_id)
407 }
408
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000409 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
410 check_manage_access()?;
411 GLOBAL_SERVICE.claimVmInstance(instance_id)
412 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000413}
414
Inseob Kimecde8c02024-09-03 13:11:08 +0900415/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
416#[derive(Debug, Default)]
417struct EarlyVmContext {
418 /// The unique CID assigned to the VM for vsock communication.
419 cid: Cid,
420 /// Temporary directory for this VM instance.
421 temp_dir: PathBuf,
422}
423
424impl EarlyVmContext {
425 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
426 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
427 // should trust clients, e.g. they won't run two VMs at the same time
428 let _ = remove_dir_all(&temp_dir);
429 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
430
431 Ok(Self { cid, temp_dir })
432 }
433}
434
435impl Interface for EarlyVmContext {}
436
437impl Drop for EarlyVmContext {
438 fn drop(&mut self) {
439 if let Err(e) = remove_dir_all(&self.temp_dir) {
440 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
441 }
442 }
443}
444
445impl IGlobalVmContext for EarlyVmContext {
446 fn getCid(&self) -> binder::Result<i32> {
447 Ok(self.cid as i32)
448 }
449
450 fn getTemporaryDirectory(&self) -> binder::Result<String> {
451 Ok(self.temp_dir.to_string_lossy().to_string())
452 }
453
454 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
455 Err(Status::new_exception_str(
456 ExceptionCode::UNSUPPORTED_OPERATION,
457 Some("Early VM doesn't support setting host console name"),
458 ))
459 }
460}
461
Frederick Mayle3a46b272025-02-10 21:55:49 -0800462#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
463enum CallingPartition {
464 Odm,
465 Product,
466 System,
467 SystemExt,
468 Vendor,
469 Unknown,
470}
471
472impl CallingPartition {
473 fn as_str(&self) -> &'static str {
474 match self {
475 CallingPartition::Odm => "odm",
476 CallingPartition::Product => "product",
477 CallingPartition::System => "system",
478 CallingPartition::SystemExt => "system_ext",
479 CallingPartition::Vendor => "vendor",
480 CallingPartition::Unknown => "[unknown]",
481 }
482 }
483}
484
485impl std::fmt::Display for CallingPartition {
486 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487 write!(f, "{}", self.as_str())
488 }
489}
490
491fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800492 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800493 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900494 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000495 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800496 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000497 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800498 if path.starts_with("/system/product/") {
499 return Ok(CallingPartition::Product);
500 }
Frederick Mayle2192baf2025-02-26 11:27:22 -0800501 if path.starts_with("/data/nativetest/vendor/")
502 || path.starts_with("/data/nativetest64/vendor/")
503 {
504 return Ok(CallingPartition::Vendor);
505 }
506
Frederick Mayle3a46b272025-02-10 21:55:49 -0800507 let partition = {
508 let mut components = path.components();
509 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
510 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800511 .or_service_specific_exception(-1);
512 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800513
Frederick Mayle3a46b272025-02-10 21:55:49 -0800514 // If path is under /apex, find a partition of the preinstalled .apex path
515 if partition == "apex" {
516 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
517 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
518 .or_service_specific_exception(-1);
519 };
520 let apex_info_list = ApexInfoList::load()
521 .context("Failed to get apex info list")
522 .or_service_specific_exception(-1)?;
523 apex_info_list
524 .list
525 .iter()
526 .find(|apex_info| apex_info.name.as_str() == apex_name)
527 .map(|apex_info| apex_info.partition.to_lowercase())
528 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
529 .or_service_specific_exception(-1)?
530 } else {
531 partition.to_string_lossy().into_owned()
532 }
533 };
534 Ok(match partition.as_str() {
535 "odm" => CallingPartition::Odm,
536 "product" => CallingPartition::Product,
537 "system" => CallingPartition::System,
538 "system_ext" => CallingPartition::SystemExt,
539 "vendor" => CallingPartition::Vendor,
540 _ => {
541 warn!("unknown partition for '{}'", path.display());
542 CallingPartition::Unknown
543 }
544 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900545}
546
Jiyong Park8611a6c2021-07-09 18:17:44 +0900547impl VirtualizationService {
548 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000549 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900550 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000551
Inseob Kimecde8c02024-09-03 13:11:08 +0900552 fn create_early_vm_context(
553 &self,
554 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900555 calling_exe_path: Option<&Path>,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800556 calling_partition: CallingPartition,
Inseob Kimecde8c02024-09-03 13:11:08 +0900557 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900558 let name = match config {
559 VirtualMachineConfig::RawConfig(config) => &config.name,
560 VirtualMachineConfig::AppConfig(config) => &config.name,
561 };
Frederick Mayle3a46b272025-02-10 21:55:49 -0800562 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900563 .or_service_specific_exception(-1)?;
564 let calling_exe_path = match calling_exe_path {
565 Some(path) => path,
566 None => {
567 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
568 .or_service_specific_exception(-1)
569 }
570 };
Alice Wang78dd87a2025-02-13 08:56:07 +0000571 early_vm.check_exe_paths_match(calling_exe_path)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900572
573 let cid = early_vm.cid as Cid;
574 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
575
576 let context = EarlyVmContext::new(cid, temp_dir.clone())
577 .context(format!("Can't create early vm contexts for {cid}"))
578 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900579
Jiyong Park690c1ca2024-11-28 18:06:50 +0900580 if requires_vm_service(config) {
581 // Start VM service listening for connections from the new CID on port=CID.
582 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
583 let port = cid;
584 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
585 .context(format!("Could not start RpcServer on port {port}"))
586 .or_service_specific_exception(-1)?;
587 vm_server.start();
588 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
589 } else {
590 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
591 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900592 }
593
David Brazdil209074a2023-01-12 16:44:51 +0000594 fn create_vm_context(
595 &self,
596 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900597 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000598 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000599 const NUM_ATTEMPTS: usize = 5;
Jiyong Park18ceddc2025-03-18 13:30:02 +0900600 let name = get_name(config);
David Brazdil8cf8f482022-11-23 14:21:26 +0000601
602 for _ in 0..NUM_ATTEMPTS {
Jiyong Park18ceddc2025-03-18 13:30:02 +0900603 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(name, requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000604 let cid = vm_context.getCid()? as Cid;
605 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900606
607 // We don't need to start the VM service for custom VMs.
608 if !requires_vm_service(config) {
609 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
610 }
611
David Brazdil8cf8f482022-11-23 14:21:26 +0000612 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
613
614 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000615 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000616 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000617 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000618 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900619 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000620 }
621 Err(err) => {
622 warn!("Could not start RpcServer on port {}: {}", port, err);
623 }
624 }
625 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900626 Err(anyhow!("Too many attempts to create VM context failed"))
627 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000628 }
629
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000630 fn create_vm_internal(
631 &self,
632 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900633 console_out_fd: Option<&ParcelFileDescriptor>,
634 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000635 log_fd: Option<&ParcelFileDescriptor>,
636 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000637 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000638 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000639 let requester_uid = get_calling_uid();
640 let requester_debug_pid = get_calling_pid();
641
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800642 let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
643
Frederick Mayle01dff422025-02-13 16:52:06 -0800644 let instance_id = extract_instance_id(config);
645 // Require vendor instance IDs to start with a specific prefix so that they don't conflict
646 // with system instance IDs.
647 //
648 // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
649 // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
650 // for now, we only check in one direction.
651 const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
652 if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
653 && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
654 {
655 return Err(anyhow!(
656 "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
657 hex::encode(instance_id)
658 ))
659 .or_service_specific_exception(-1);
660 }
661
Nikita Ioffe631717e2023-09-05 13:38:07 +0100662 check_config_features(config)?;
663
Inseob Kimecde8c02024-09-03 13:11:08 +0900664 if cfg!(early) {
665 check_config_allowed_for_early_vms(config)?;
666 }
667
Nikita Ioffeb1416122024-10-22 12:18:49 +0000668 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
669 info!("callers secontext: {}", caller_secontext);
670
David Brazdil209074a2023-01-12 16:44:51 +0000671 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900672 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800673 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900674 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900675 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900676 };
Inseob Kim1119d702022-05-02 18:01:58 +0900677
Alan Stokesfda70842023-12-20 17:50:14 +0000678 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100679 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900680 }
681
Nikita Ioffe5776f082023-02-10 21:38:26 +0000682 let gdb_port = extract_gdb_port(config);
683
684 // Additional permission checks if caller request gdb.
685 if gdb_port.is_some() {
686 check_gdb_allowed(config)?;
687 }
688
Jaewan Kimf43372b2024-12-13 18:33:58 +0900689 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800690 if let Some(dt_overlay) =
691 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
692 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900693 device_tree_overlays.push(dt_overlay);
694 }
695 if let Some(dtbo) = get_dtbo(config) {
696 let dtbo = File::from(
697 dtbo.as_ref()
698 .try_clone()
699 .context("Failed to create VM DTBO from ParcelFileDescriptor")
700 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
701 );
702 device_tree_overlays.push(dtbo);
703 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900704
Jaewan Kimf3143242024-03-15 06:56:31 +0000705 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000706 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900707 Some(prepare_ramdump_file(&temporary_directory)?)
708 } else {
709 None
710 };
711
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000712 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900713 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100714 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900715 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100716 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100717 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
718 Some(clone_file(fd)?)
719 } else if debug_config.dump_device_tree {
720 Some(prepare_dump_dt_file(&temporary_directory)?)
721 } else {
722 None
723 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000724
725 // Counter to generate unique IDs for temporary image files.
726 let mut next_temporary_image_id = 0;
727 // Files which are referred to from composite images. These must be mapped to the crosvm
728 // child process, and not closed before it is started.
729 let mut indirect_files = vec![];
730
Alan Stokes7bc146c2022-10-20 17:10:32 +0100731 let (is_app_config, config) = match config {
732 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
733 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900734 let config = load_app_config(config, &debug_config, &temporary_directory)
735 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900736 *is_protected = config.protectedVm;
737 let message = format!("Failed to load app config: {:?}", e);
738 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900739 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900740 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100741 (true, BorrowedOrOwned::Owned(config))
742 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000743 };
744 let config = config.as_ref();
745 *is_protected = config.protectedVm;
746
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000747 if !config.teeServices.is_empty() {
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000748 if !config.protectedVm {
749 return Err(anyhow!("only protected VMs can request tee services"))
750 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
751 }
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000752 check_tee_service_permission(&caller_secontext, &config.teeServices)
753 .with_log()
754 .or_binder_exception(ExceptionCode::SECURITY)?;
755 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000756
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000757 let mut system_tee_services = Vec::new();
758 let mut vendor_tee_services = Vec::new();
759 for tee_service in config.teeServices.clone() {
760 if !tee_service.starts_with("vendor.") {
761 check_known_tee_service(&tee_service)?;
762 system_tee_services.push(tee_service);
763 } else {
764 vendor_tee_services.push(tee_service);
765 }
766 }
767
768 // TODO(b/391774181): handle vendor tee services (which require talking to HAL) as well.
769 if !vendor_tee_services.is_empty() {
770 return Err(anyhow!("support for vendor tee services is coming soon!"))
771 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
772 }
773
Nikita Ioffe65e6fdb2025-02-17 17:00:27 +0000774 // TODO(b/391774181): remove this check in a follow-up patch.
Nikita Ioffe22e5d0a2025-02-17 16:36:52 +0000775 if !system_tee_services.is_empty() {
776 return Err(anyhow!("support for system tee services is coming soon!"))
777 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
778 }
779
Jiyong Park3051ffe2024-11-26 14:41:58 +0900780 let kernel = maybe_clone_file(&config.kernel)?;
781 let initrd = maybe_clone_file(&config.initrd)?;
782
783 if config.protectedVm {
784 // Fail fast with a meaningful error message in case device doesn't support pVMs.
785 check_protected_vm_is_supported()?;
786
787 // In a protected VM, we require custom kernels to come from a trusted source
788 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800789 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
790 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900791
792 // Check if partition images are labeled incorrectly. This is to prevent random images
793 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
794 // from being loaded in a pVM. This applies to everything but the instance image in the
795 // raw config, and everything but the non-executable, generated partitions in the app
796 // config.
797 config
798 .disks
799 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800800 .flat_map(|disk| disk.image.as_ref())
801 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
802 .or_service_specific_exception(-1)?;
803 config
804 .disks
805 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900806 .flat_map(|disk| disk.partitions.iter())
807 .filter(|partition| {
808 if is_app_config {
809 !is_safe_app_partition(&partition.label)
810 } else {
811 !is_safe_raw_partition(&partition.label)
812 }
813 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800814 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900815 .or_service_specific_exception(-1)?;
816 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000817
Inseob Kimff48a7c2024-02-26 22:07:21 +0900818 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
819 // have unstable interfaces.
820 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800821 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900822
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000823 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900824 write_zero_filler(&zero_filler_path)
825 .context("Failed to make composite image")
826 .with_log()
827 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000828
829 // Assemble disk images if needed.
830 let disks = config
831 .disks
832 .iter()
833 .map(|disk| {
834 assemble_disk_image(
835 disk,
836 &zero_filler_path,
837 &temporary_directory,
838 &mut next_temporary_image_id,
839 &mut indirect_files,
840 )
841 })
842 .collect::<Result<Vec<DiskFile>, _>>()?;
843
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700844 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
845
Jaewan Kimf43372b2024-12-13 18:33:58 +0900846 let (vfio_devices, dtbo) = match &config.devices {
847 AssignedDevices::Devices(devices) if !devices.is_empty() => {
848 let mut set = HashSet::new();
849 for device in devices.iter() {
850 let path = canonicalize(device)
851 .with_context(|| format!("can't canonicalize {device}"))
852 .or_service_specific_exception(-1)?;
853 if !set.insert(path) {
854 return Err(anyhow!("duplicated device {device}"))
855 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
856 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900857 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900858 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
859 let dtbo_file = File::from(
860 GLOBAL_SERVICE
861 .getDtboFile()?
862 .as_ref()
863 .try_clone()
864 .context("Failed to create VM DTBO from ParcelFileDescriptor")
865 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
866 );
867 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900868 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900869 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900870 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900871 let display_config = if cfg!(paravirtualized_devices) {
872 config
873 .displayConfig
874 .as_ref()
875 .map(DisplayConfig::new)
876 .transpose()
877 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
878 } else {
879 None
880 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700881 let gpu_config = if cfg!(paravirtualized_devices) {
882 config
883 .gpuConfig
884 .as_ref()
885 .map(GpuConfig::new)
886 .transpose()
887 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
888 } else {
889 None
890 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900891
Jeongik Chac181be72024-03-27 00:18:30 +0900892 let input_device_options = if cfg!(paravirtualized_devices) {
893 config
894 .inputDevices
895 .iter()
896 .map(to_input_device_option_from)
897 .collect::<Result<Vec<InputDeviceOption>, _>>()
898 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
899 } else {
900 vec![]
901 };
902
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900903 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900904 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900905 if *is_protected {
906 return Err(anyhow!("Network feature is not supported for pVM yet"))
907 .with_log()
908 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
909 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900910 Some(File::from(
911 GLOBAL_SERVICE
912 .createTapInterface(&get_this_pid().to_string())?
913 .as_ref()
914 .try_clone()
915 .context("Failed to get TAP interface from ParcelFileDescriptor")
916 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
917 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900918 } else {
919 None
920 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800921
922 let audio_config = if cfg!(paravirtualized_devices) {
923 config.audioConfig.as_ref().map(AudioConfig::new)
924 } else {
925 None
926 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900927
Elie Kheirallah29d72912024-08-07 20:17:26 +0000928 let usb_config = config
929 .usbConfig
930 .as_ref()
931 .map(UsbConfig::new)
932 .unwrap_or(Ok(UsbConfig { controller: false }))
933 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
934
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000935 let detect_hangup = is_app_config && gdb_port.is_none();
936
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800937 let custom_memory_backing_files = config
938 .customMemoryBackingFiles
939 .iter()
940 .map(|memory_backing_file| {
941 Ok((
942 clone_file(
943 memory_backing_file
944 .file
945 .as_ref()
946 .context("missing CustomMemoryBackingFile FD")
947 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
948 )?
949 .into(),
950 memory_backing_file.rangeStart as u64,
951 memory_backing_file.size as u64,
952 ))
953 })
954 .collect::<binder::Result<_>>()?;
955
Yuan Yao3843ea22025-02-27 06:22:20 +0000956 let memory_reclaim_supported =
957 system_properties::read_bool("hypervisor.memory_reclaim.supported", false)
958 .unwrap_or(false);
959
960 let balloon = config.balloon && memory_reclaim_supported;
961
962 if !balloon {
963 warn!(
964 "Memory balloon not enabled:
965 config.balloon={},hypervisor.memory_reclaim.supported={}",
966 config.balloon, memory_reclaim_supported
967 );
968 }
969
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000970 // Actually start the VM.
971 let crosvm_config = CrosvmConfig {
972 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000973 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000974 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000975 kernel,
976 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000977 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700978 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000979 params: config.params.to_owned(),
980 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900981 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700982 memory_mib: config
983 .memoryMib
984 .try_into()
985 .ok()
986 .and_then(NonZeroU32::new)
987 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800988 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000989 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900990 console_out_fd,
991 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000992 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900993 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000994 indirect_files,
995 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000996 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000997 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900998 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000999 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +09001000 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +09001001 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +09001002 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001003 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +09001004 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +08001005 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +00001006 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -07001007 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +08001008 audio_config,
Yuan Yao3843ea22025-02-27 06:22:20 +00001009 balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +00001010 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +00001011 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001012 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
1013 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -08001014 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001015 };
1016 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +01001017 VmInstance::new(
1018 crosvm_config,
1019 temporary_directory,
1020 requester_uid,
1021 requester_debug_pid,
1022 vm_context,
1023 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001024 .with_context(|| format!("Failed to create VM with config {:?}", config))
1025 .with_log()
1026 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +00001027 );
1028 state.add_vm(Arc::downgrade(&instance));
1029 Ok(VirtualMachine::create(instance))
1030 }
Jiyong Park8611a6c2021-07-09 18:17:44 +09001031}
1032
Alan Stokesfda70842023-12-20 17:50:14 +00001033/// Returns whether a VM config represents a "custom" virtual machine, which requires the
1034/// USE_CUSTOM_VIRTUAL_MACHINE.
1035fn is_custom_config(config: &VirtualMachineConfig) -> bool {
1036 match config {
1037 // Any raw (non-Microdroid) VM is considered custom.
1038 VirtualMachineConfig::RawConfig(_) => true,
1039 VirtualMachineConfig::AppConfig(config) => {
1040 // Some features are reserved for platform apps only, even when using
1041 // VirtualMachineAppConfig. Almost all of these features are grouped in the
1042 // CustomConfig struct:
1043 // - controlling CPUs;
1044 // - gdbPort is set, meaning that crosvm will start a gdb server;
1045 // - using anything other than the default kernel;
1046 // - specifying devices to be assigned.
1047 if config.customConfig.is_some() {
1048 true
1049 } else {
1050 // Additional custom features not included in CustomConfig:
1051 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +00001052 // - specifying extra APKs;
1053 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +09001054 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +00001055 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +09001056 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
1057 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +00001058 }
1059 }
1060 }
1061}
1062
Jiyong Park690c1ca2024-11-28 18:06:50 +09001063/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
1064/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
1065/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
1066/// "microdroid" we run VirtualMachineService
1067fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
1068 match config {
1069 VirtualMachineConfig::AppConfig(_) => true,
1070 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
1071 }
1072}
1073
Jiyong Park18ceddc2025-03-18 13:30:02 +09001074/// Returns the name of the config
1075fn get_name(config: &VirtualMachineConfig) -> &str {
1076 match config {
1077 VirtualMachineConfig::AppConfig(config) => &config.name,
1078 VirtualMachineConfig::RawConfig(config) => &config.name,
1079 }
1080}
1081
Seungjae Yoo14e60182024-02-21 13:28:31 +09001082fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
1083 let VirtualMachineConfig::AppConfig(config) = config else {
1084 return Ok(None);
1085 };
1086 let Some(custom_config) = &config.customConfig else {
1087 return Ok(None);
1088 };
1089 let Some(file) = custom_config.vendorImage.as_ref() else {
1090 return Ok(None);
1091 };
1092
1093 let file = clone_file(file)?;
1094 let size =
1095 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1096 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1097 .context("Failed to get vbmeta from microdroid-vendor.img")?;
1098
1099 for descriptor in vbmeta.descriptors()?.iter() {
1100 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1101 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1102 return Ok(Some(root_digest.as_bytes().to_vec()));
1103 }
1104 }
1105 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1106}
1107
Jaewan Kimf43372b2024-12-13 18:33:58 +09001108fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001109 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001110 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001111 temporary_directory: &Path,
1112) -> binder::Result<Option<File>> {
1113 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1114 // (e.g. instance-id)
1115 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1116 let host_ref_dt = if host_ref_dt.exists()
1117 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1118 {
1119 Some(host_ref_dt)
1120 } else {
1121 warn!("VM reference DT doesn't exist in host DT");
1122 None
1123 };
1124
1125 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1126 .context("Failed to extract vendor hashtree digest")
1127 .or_service_specific_exception(-1)?;
1128
Matt Gilbrideaade4272024-12-05 13:52:42 +00001129 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001130 info!(
1131 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1132 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1133 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001134 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001135 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001136 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001137 };
1138
Matt Gilbrideaade4272024-12-05 13:52:42 +00001139 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001140 let mut untrusted_props = Vec::with_capacity(2);
1141 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001142 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001143 let want_updatable = extract_want_updatable(config);
1144 if want_updatable && is_secretkeeper_supported() {
1145 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1146 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001147 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001148 let sk: Strong<dyn ISecretkeeper> =
1149 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1150 if sk.getInterfaceVersion()? >= 2 {
1151 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1152 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001153 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001154 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001155 }
1156 }
1157
1158 let device_tree_overlay = if host_ref_dt.is_some()
1159 || !untrusted_props.is_empty()
1160 || !trusted_props.is_empty()
1161 {
1162 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1163 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1164 let fdt =
1165 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1166 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1167 .or_service_specific_exception(-1)?;
1168 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1169 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1170 } else {
1171 None
1172 };
1173 Ok(device_tree_overlay)
1174}
1175
Jaewan Kimf43372b2024-12-13 18:33:58 +09001176fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1177 let VirtualMachineConfig::RawConfig(config) = config else {
1178 return None;
1179 };
1180 match &config.devices {
1181 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1182 _ => None,
1183 }
1184}
1185
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001186fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001187 let file = OpenOptions::new()
1188 .create_new(true)
1189 .read(true)
1190 .write(true)
1191 .open(zero_filler_path)
1192 .with_context(|| "Failed to create zero.img")?;
1193 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001194 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001195}
1196
David Brazdilf50c7a62023-04-19 14:22:42 +00001197fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1198 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1199 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1200 part.flush()
1201}
1202
1203fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1204 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1205 part.flush()
1206}
1207
1208fn round_up(input: u64, granularity: u64) -> u64 {
1209 if granularity == 0 {
1210 return input;
1211 }
1212 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1213 let result = input.checked_add(granularity - 1).unwrap_or(input);
1214 (result / granularity) * granularity
1215}
1216
Jeongik Chac181be72024-03-27 00:18:30 +09001217fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1218 Ok(match input_device {
1219 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1220 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1221 height: u32::try_from(single_touch.height)?,
1222 width: u32::try_from(single_touch.width)?,
1223 name: if !single_touch.name.is_empty() {
1224 Some(single_touch.name.clone())
1225 } else {
1226 None
1227 },
1228 },
1229 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1230 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1231 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001232 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1233 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1234 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001235 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1236 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1237 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001238 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1239 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1240 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001241 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1242 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1243 height: u32::try_from(trackpad.height)?,
1244 width: u32::try_from(trackpad.width)?,
1245 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1246 },
Jeongik Cha10494912024-07-16 11:19:50 +09001247 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1248 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1249 height: u32::try_from(multi_touch.height)?,
1250 width: u32::try_from(multi_touch.width)?,
1251 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1252 },
Jeongik Chac181be72024-03-27 00:18:30 +09001253 })
1254}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001255
1256fn assemble_shared_paths(
1257 shared_paths: &[SharedPath],
1258 temporary_directory: &Path,
1259) -> Result<Vec<SharedPathConfig>, Status> {
1260 if shared_paths.is_empty() {
1261 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1262 }
1263
1264 shared_paths
1265 .iter()
1266 .map(|path| {
1267 Ok(SharedPathConfig {
1268 path: path.sharedPath.clone(),
1269 host_uid: path.hostUid,
1270 host_gid: path.hostGid,
1271 guest_uid: path.guestUid,
1272 guest_gid: path.guestGid,
1273 mask: path.mask,
1274 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001275 socket_path: temporary_directory
1276 .join(&path.socketPath)
1277 .to_string_lossy()
1278 .to_string(),
1279 socket_fd: maybe_clone_file(&path.socketFd)?,
1280 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001281 })
1282 })
1283 .collect()
1284}
1285
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001286/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1287///
1288/// This may involve assembling a composite disk from a set of partition images.
1289fn assemble_disk_image(
1290 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001291 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001292 temporary_directory: &Path,
1293 next_temporary_image_id: &mut u64,
1294 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001295) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001296 let image = if !disk.partitions.is_empty() {
1297 if disk.image.is_some() {
1298 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001299 return Err(anyhow!("DiskImage contains both image and partitions"))
1300 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001301 }
1302
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001303 let composite_image_filenames =
1304 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1305 let (image, partition_files) = make_composite_image(
1306 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001307 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001308 &composite_image_filenames.composite,
1309 &composite_image_filenames.header,
1310 &composite_image_filenames.footer,
1311 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001312 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1313 .with_log()
1314 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001315
1316 // Pass the file descriptors for the various partition files to crosvm when it
1317 // is run.
1318 indirect_files.extend(partition_files);
1319
1320 image
1321 } else if let Some(image) = &disk.image {
1322 clone_file(image)?
1323 } else {
1324 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001325 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1326 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001327 };
1328
1329 Ok(DiskFile { image, writable: disk.writable })
1330}
1331
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001332fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1333 if let Some(ref mut params) = vm_config.params {
1334 params.push(' ');
1335 params.push_str(param)
1336 } else {
1337 vm_config.params = Some(param.to_owned())
1338 }
1339}
1340
Inseob Kim46257382024-01-03 15:41:22 +09001341fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1342 if config.extension()?.to_str()? != "json" {
1343 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001344 }
Inseob Kim46257382024-01-03 15:41:22 +09001345
1346 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1347}
1348
1349fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1350 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1351 let os_names =
1352 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1353
1354 Ok(os_names)
1355}
1356
1357fn get_supported_os_names() -> Result<HashSet<String>> {
1358 if !cfg!(vendor_modules) {
1359 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1360 }
1361
1362 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1363}
1364
1365fn is_valid_os(os_name: &str) -> bool {
1366 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001367}
1368
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001369fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1370 if !cfg!(vendor_modules) {
1371 return false;
1372 }
1373 match config {
1374 VirtualMachineConfig::RawConfig(_) => false,
1375 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1376 }
1377}
1378
Jooyung Han21e9b922021-06-26 04:14:16 +09001379fn load_app_config(
1380 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001381 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001382 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001383) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001384 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1385 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001386 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001387
Shikha Panwar22e70452022-10-10 18:32:55 +00001388 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1389 Some(clone_file(file)?)
1390 } else {
1391 None
1392 };
1393
Alan Stokesfda70842023-12-20 17:50:14 +00001394 let vm_payload_config;
1395 let extra_apk_files: Vec<_>;
1396 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001397 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001398 vm_payload_config =
1399 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1400 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1401 extra_apk_files = vm_payload_config
1402 .extra_apks
1403 .iter()
1404 .enumerate()
1405 .map(|(i, apk)| {
1406 File::open(PathBuf::from(&apk.path))
1407 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1408 })
1409 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001410 }
Alan Stokesfda70842023-12-20 17:50:14 +00001411 Payload::PayloadConfig(payload_config) => {
1412 vm_payload_config = create_vm_payload_config(payload_config)?;
1413 extra_apk_files =
1414 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1415 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001416 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001417
Inseob Kim89b24592024-02-23 18:59:43 +09001418 let payload_config_os = vm_payload_config.os.name.as_str();
1419 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1420 bail!("'os' in payload config is deprecated");
1421 }
1422
Inseob Kim172f9eb2023-11-06 17:02:08 +09001423 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001424 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001425 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001426 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001427 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001428
1429 // It is safe to construct a filename based on the os_name because we've already checked that it
1430 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001431 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1432 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001433 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001434
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001435 if let Some(custom_config) = &config.customConfig {
1436 if let Some(file) = custom_config.customKernelImage.as_ref() {
1437 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1438 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001439 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001440
1441 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001442 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001443 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001444 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001445
Jaewan Kimf43372b2024-12-13 18:33:58 +09001446 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001447 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001448
1449 for param in custom_config.extraKernelCmdlineParams.iter() {
1450 append_kernel_param(param, &mut vm_config);
1451 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001452
1453 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001454 }
1455
Andrew Walbrancc045902021-07-27 16:06:17 +00001456 if config.memoryMib > 0 {
1457 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001458 }
1459
Chris Wailes6177c662024-05-09 14:37:44 -07001460 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001461 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001462 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001463 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001464 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001465
Shikha Panwar22e70452022-10-10 18:32:55 +00001466 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001467 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001468
1469 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1470 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001471 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001472 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001473 temporary_directory,
1474 apk_file,
1475 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001476 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001477 &vm_payload_config,
1478 &mut vm_config,
1479 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001480
Andrew Walbrancc0db522021-07-12 17:03:42 +00001481 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001482}
1483
Frederick Mayle3a46b272025-02-10 21:55:49 -08001484fn check_partition_for_file(
1485 fd: &ParcelFileDescriptor,
1486 calling_partition: CallingPartition,
1487) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001488 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
Inseob Kim4d414452025-03-04 16:17:47 +09001489 let link = fs::read_link(&path).with_context(|| format!("can't read_link {path}"))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001490
1491 // microdroid vendor image is OK
1492 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1493 {
1494 return Ok(());
1495 }
1496
Inseob Kim4d414452025-03-04 16:17:47 +09001497 let fd_partition = find_partition(Some(&link))
1498 .with_context(|| format!("can't find_partition {}", link.display()))?;
1499 let is_fd_vendor =
1500 fd_partition == CallingPartition::Vendor || fd_partition == CallingPartition::Odm;
Frederick Mayle3a46b272025-02-10 21:55:49 -08001501 let is_caller_vendor =
1502 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001503
1504 if is_fd_vendor != is_caller_vendor {
1505 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001506 }
1507
1508 Ok(())
1509}
1510
Inseob Kime3e932d2024-12-16 20:06:57 +09001511fn check_partitions_for_files(
1512 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001513 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001514) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001515 config
1516 .disks
1517 .iter()
1518 .flat_map(|disk| disk.partitions.iter())
1519 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001520 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001521
Inseob Kime3e932d2024-12-16 20:06:57 +09001522 config
1523 .disks
1524 .iter()
1525 .filter_map(|disk| disk.image.as_ref())
1526 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1527
1528 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1529 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1530 config
1531 .bootloader
1532 .as_ref()
1533 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001534
1535 Ok(())
1536}
1537
Alan Stokes0d1ef782022-09-27 13:46:35 +01001538fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1539 let mut apk_zip = ZipArchive::new(apk_file)?;
1540 let config_file = apk_zip.by_name(config_path)?;
1541 Ok(serde_json::from_reader(config_file)?)
1542}
1543
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001544fn create_vm_payload_config(
1545 payload_config: &VirtualMachinePayloadConfig,
1546) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001547 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1548 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1549 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001550
1551 let payload_binary_name = &payload_config.payloadBinaryName;
1552 if payload_binary_name.contains('/') {
1553 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1554 }
1555
1556 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001557
1558 // The VM only cares about how many there are, these names are actually ignored.
1559 let extra_apk_count = payload_config.extraApks.len();
1560 let extra_apks =
1561 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1562
Nikita Ioffe901083f2025-01-20 01:54:28 +00001563 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1564 // The only payload delivered via Mainline module in this release requires
1565 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1566 // APIs, so we use the fact that the payload is granted
1567 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1568 // com.android.i18n APEX.
1569 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1570 // Microdroid pVMs.
1571 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1572 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1573 } else {
1574 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1575 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001576}
1577
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001578/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001579fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001580 temporary_directory: &Path,
1581 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001582) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001583 let id = *next_temporary_image_id;
1584 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001585 CompositeImageFilenames {
1586 composite: temporary_directory.join(format!("composite-{}.img", id)),
1587 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1588 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1589 }
1590}
1591
1592/// Filenames for a composite disk image, including header and footer partitions.
1593#[derive(Clone, Debug, Eq, PartialEq)]
1594struct CompositeImageFilenames {
1595 /// The composite disk image itself.
1596 composite: PathBuf,
1597 /// The header partition image.
1598 header: PathBuf,
1599 /// The footer partition image.
1600 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001601}
1602
Jiyong Park753553b2021-07-12 21:21:09 +09001603/// Checks whether the caller has a specific permission
1604fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001605 if cfg!(early) {
1606 // Skip permission check for early VMs, in favor of SELinux
1607 return Ok(());
1608 }
David Brazdil1f530702022-10-03 12:18:10 +01001609 let calling_pid = get_calling_pid();
1610 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001611 // Root can do anything
1612 if calling_uid == 0 {
1613 return Ok(());
1614 }
1615 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001616 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001617 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001618 Ok(())
1619 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001620 Err(anyhow!("does not have the {} permission", perm))
1621 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001622 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001623}
1624
Jiyong Park753553b2021-07-12 21:21:09 +09001625/// Check whether the caller of the current Binder method is allowed to manage VMs
1626fn check_manage_access() -> binder::Result<()> {
1627 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1628}
1629
Inseob Kim1119d702022-05-02 18:01:58 +09001630/// Check whether the caller of the current Binder method is allowed to create custom VMs
1631fn check_use_custom_virtual_machine() -> binder::Result<()> {
1632 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1633}
1634
Nikita Ioffe901083f2025-01-20 01:54:28 +00001635/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1636/// rollback protection schema.
1637fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1638 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1639}
1640
Alan Stokes185fe112023-01-10 16:20:55 +00001641/// Return whether a partition is exempt from selinux label checks, because we know that it does
1642/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001643fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001644 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001645 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001646 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001647 || label == "microdroid-apk-idsig"
1648 || label == "payload-metadata"
1649 || label.starts_with("extra-idsig-")
1650}
1651
Alice Wangc206b9b2023-08-28 14:13:51 +00001652/// Returns whether a partition with the given label is safe for a raw config VM.
1653fn is_safe_raw_partition(label: &str) -> bool {
1654 label == "vm-instance"
1655}
1656
Alan Stokes185fe112023-01-10 16:20:55 +00001657/// Check that a file SELinux label is acceptable.
1658///
1659/// 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 +09001660/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001661///
1662/// Note that sepolicy must also grant read access for these types to both virtualization
1663/// service and crosvm.
1664///
1665/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1666/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001667fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001668 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001669 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001670 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001671 | "staging_data_file" // updated/staged APEX images
1672 | "system_file" // immutable dm-verity protected partition
1673 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001674 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001675 => Ok(()),
Frederick Maylec8f27042025-02-26 12:35:26 -08001676 // It is difficult to require specific label types for vendor initiated VM's files.
1677 _ if calling_partition == CallingPartition::Vendor => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001678 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001679 }
1680}
1681
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001682fn check_label_for_partition(
1683 partition: &Partition,
1684 calling_partition: CallingPartition,
1685) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001686 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001687 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001688 .with_context(|| format!("Partition {} invalid", &partition.label))
1689}
1690
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001691fn check_label_for_kernel_files(
1692 kernel: &Option<File>,
1693 initrd: &Option<File>,
1694 calling_partition: CallingPartition,
1695) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001696 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001697 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001698 }
1699 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001700 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001701 }
1702 Ok(())
1703}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001704fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001705 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001706 name: &str,
1707 calling_partition: CallingPartition,
1708) -> Result<()> {
1709 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1710 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001711}
1712
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001713/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1714#[derive(Debug)]
1715struct VirtualMachine {
1716 instance: Arc<VmInstance>,
1717}
1718
1719impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001720 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001721 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001722 }
1723}
1724
1725impl Interface for VirtualMachine {}
1726
Devin Moore407df8f2024-08-27 19:39:16 +00001727impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001728 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001729 // Don't check permission. The owner of the VM might have passed this binder object to
1730 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001731 Ok(self.instance.cid as i32)
1732 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001733
Andrew Walbran6b650662021-09-07 13:13:23 +00001734 fn getState(&self) -> binder::Result<VirtualMachineState> {
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.
Andrew Walbran6b650662021-09-07 13:13:23 +00001737 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001738 }
1739
1740 fn registerCallback(
1741 &self,
1742 callback: &Strong<dyn IVirtualMachineCallback>,
1743 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001744 // Don't check permission. The owner of the VM might have passed this binder object to
1745 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001746
1747 // Only register callback if it may be notified.
1748 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1749 let vm_state = self.instance.vm_state.lock().unwrap();
1750 if matches!(*vm_state, VmState::Dead) {
1751 warn!("Ignoring registerCallback() after VM is died");
1752 } else {
1753 self.instance.callbacks.add(callback.clone());
1754 }
1755 drop(vm_state);
1756
Andrew Walbrandae07162021-03-12 17:05:20 +00001757 Ok(())
1758 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001759
Andrew Walbranf8d94112021-09-07 11:45:36 +00001760 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001761 self.instance
1762 .start()
1763 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1764 .with_log()
1765 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001766 }
1767
Inseob Kima446f802022-07-11 19:46:37 +09001768 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001769 self.instance
1770 .kill()
1771 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1772 .with_log()
1773 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001774 }
1775
Yuan Yao3843ea22025-02-27 06:22:20 +00001776 fn isMemoryBalloonEnabled(&self) -> binder::Result<bool> {
1777 Ok(self.instance.balloon_enabled)
1778 }
1779
Keir Fraser48221ba2024-07-12 14:05:02 +00001780 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1781 let balloon = self
1782 .instance
1783 .get_memory_balloon()
1784 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1785 .with_log()
1786 .or_service_specific_exception(-1)?;
1787 Ok(balloon.try_into().unwrap())
1788 }
1789
1790 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001791 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001792 .set_memory_balloon(num_bytes.try_into().unwrap())
1793 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001794 .with_log()
1795 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001796 }
1797
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001798 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001799 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001800 return Err(Status::new_service_specific_error_str(
1801 IVirtualMachine::ERROR_UNEXPECTED,
1802 Some("Virtual Machine is not running"),
1803 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001804 }
Alan Stokes10c47672022-12-13 17:17:08 +00001805 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001806 if port < VSOCK_PRIV_PORT_MAX {
1807 return Err(Status::new_service_specific_error_str(
1808 IVirtualMachine::ERROR_UNEXPECTED,
1809 Some("Can't connect to privileged port {port}"),
1810 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001811 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001812 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1813 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001814 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001815 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001816 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001817
Devin Moore407df8f2024-08-27 19:39:16 +00001818 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1819 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1820 return Err(Status::new_service_specific_error_str(
1821 IVirtualMachine::ERROR_UNEXPECTED,
1822 Some("Virtual Machine is not running"),
1823 ));
1824 }
1825 let port = port as u32;
1826 if port < VSOCK_PRIV_PORT_MAX {
1827 return Err(Status::new_service_specific_error_str(
1828 IVirtualMachine::ERROR_UNEXPECTED,
1829 Some("Can't connect to privileged port {port}"),
1830 ));
1831 }
1832 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001833 let addr = sockaddr_vm {
1834 svm_family: AF_VSOCK as sa_family_t,
1835 svm_reserved1: 0,
1836 svm_port: port,
1837 svm_cid: cid,
1838 svm_zero: [0u8; 4],
1839 };
1840 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001841 let accessor = Accessor::new(name, get_connection_info);
1842 accessor
1843 .as_binder()
1844 .context("The newly created Accessor should always have a binder")
1845 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1846 }
1847
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001848 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1849 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1850 }
Jiyong Park23b67392024-07-04 13:51:42 +09001851
1852 fn suspend(&self) -> binder::Result<()> {
1853 self.instance
1854 .suspend()
1855 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1856 .with_log()
1857 .or_service_specific_exception(-1)
1858 }
1859
1860 fn resume(&self) -> binder::Result<()> {
1861 self.instance
1862 .resume()
1863 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1864 .with_log()
1865 .or_service_specific_exception(-1)
1866 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001867}
1868
1869impl Drop for VirtualMachine {
1870 fn drop(&mut self) {
1871 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001872 if let Err(e) = self.instance.kill() {
1873 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1874 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001875 }
1876}
1877
1878/// A set of Binders to be called back in response to various events on the VM, such as when it
1879/// dies.
1880#[derive(Debug, Default)]
1881pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1882
1883impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001884 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001885 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001886 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001887 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001888 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001889 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001890 }
1891 }
1892 }
1893
Inseob Kim14cb8692021-08-31 21:50:39 +09001894 /// Call all registered callbacks to notify that the payload is ready to serve.
1895 pub fn notify_payload_ready(&self, cid: Cid) {
1896 let callbacks = &*self.0.lock().unwrap();
1897 for callback in callbacks {
1898 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001899 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001900 }
1901 }
1902 }
1903
Inseob Kim2444af92021-08-31 01:22:50 +09001904 /// Call all registered callbacks to notify that the payload has finished.
1905 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1906 let callbacks = &*self.0.lock().unwrap();
1907 for callback in callbacks {
1908 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001909 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001910 }
1911 }
1912 }
1913
Jooyung Handd0a1732021-11-23 15:26:20 +09001914 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001915 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001916 let callbacks = &*self.0.lock().unwrap();
1917 for callback in callbacks {
1918 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001919 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001920 }
1921 }
1922 }
1923
Andrew Walbrandae07162021-03-12 17:05:20 +00001924 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001925 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001926 let mut callbacks = self.0.lock().unwrap();
1927 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001928 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001929 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001930 }
1931 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001932
1933 // Nothing to notify afterward because VM cannot be restarted.
1934 // Explicitly clear callbacks to prevent potential cyclic references
1935 // between callback and VmInstance.
1936 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001937 }
1938
1939 /// Add a new callback to the set.
1940 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1941 self.0.lock().unwrap().push(callback);
1942 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001943}
1944
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001945/// The mutable state of the VirtualizationService. There should only be one instance of this
1946/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001947#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001948struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001949 /// The VMs which have been started. When VMs are started a weak reference is added to this
1950 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1951 /// the Binder client are dropped the weak reference here will become invalid, and will be
1952 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001953 vms: Vec<Weak<VmInstance>>,
1954}
1955
1956impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001957 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001958 fn vms(&self) -> Vec<Arc<VmInstance>> {
1959 // Attempt to upgrade the weak pointers to strong pointers.
1960 self.vms.iter().filter_map(Weak::upgrade).collect()
1961 }
1962
1963 /// Add a new VM to the list.
1964 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1965 // Garbage collect any entries from the stored list which no longer exist.
1966 self.vms.retain(|vm| vm.strong_count() > 0);
1967
1968 // Actually add the new VM.
1969 self.vms.push(vm);
1970 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001971
Jiyong Park8611a6c2021-07-09 18:17:44 +09001972 /// Get a VM that corresponds to the given cid
1973 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1974 self.vms().into_iter().find(|vm| vm.cid == cid)
1975 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001976}
1977
Andrew Walbran6b650662021-09-07 13:13:23 +00001978/// Gets the `VirtualMachineState` of the given `VmInstance`.
1979fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001980 match &*instance.vm_state.lock().unwrap() {
1981 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1982 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001983 PayloadState::Starting => VirtualMachineState::STARTING,
1984 PayloadState::Started => VirtualMachineState::STARTED,
1985 PayloadState::Ready => VirtualMachineState::READY,
1986 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001987 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001988 },
1989 VmState::Dead => VirtualMachineState::DEAD,
1990 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001991 }
1992}
1993
David Brazdilf50c7a62023-04-19 14:22:42 +00001994/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001995pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1996 file.as_ref()
1997 .try_clone()
1998 .context("Failed to clone File from ParcelFileDescriptor")
1999 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00002000 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00002001}
2002
Andrew Walbrand3a84182021-09-07 14:48:52 +00002003/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002004fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00002005 file.as_ref().map(clone_file).transpose()
2006}
2007
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002008/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09002009fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
2010 // SAFETY: ownership is transferred from stream to f
2011 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
2012 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00002013}
2014
Jiyong Parkdcf17412022-02-08 15:07:23 +09002015/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09002016fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
2017 VersionReq::parse(s)
2018 .with_context(|| format!("Invalid platform version requirement {}", s))
2019 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09002020}
2021
Jiyong Parked180932023-02-24 19:55:41 +09002022/// Create the empty ramdump file
2023fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
2024 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
2025 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
2026 // owner) for readout.
2027 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09002028 let ramdump = File::create(ramdump_path)
2029 .context("Failed to prepare ramdump file")
2030 .with_log()
2031 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09002032 Ok(ramdump)
2033}
2034
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01002035/// Create the empty device tree dump file
2036fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
2037 let path = temporary_directory.join("device_tree.dtb");
2038 let file = File::create(path)
2039 .context("Failed to prepare device tree dump file")
2040 .with_log()
2041 .or_service_specific_exception(-1)?;
2042 Ok(file)
2043}
2044
Nikita Ioffe5776f082023-02-10 21:38:26 +00002045fn is_protected(config: &VirtualMachineConfig) -> bool {
2046 match config {
2047 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
2048 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
2049 }
2050}
2051
2052fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
2053 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09002054 return Err(anyhow!("Can't use gdb with protected VMs"))
2055 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002056 }
2057
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002058 if get_debug_level(config) == Some(DebugLevel::NONE) {
2059 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
2060 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00002061 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01002062
2063 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00002064}
2065
Shikha Panwar61a74b52024-02-16 13:17:01 +00002066fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
2067 match config {
2068 VirtualMachineConfig::RawConfig(config) => config.instanceId,
2069 VirtualMachineConfig::AppConfig(config) => config.instanceId,
2070 }
2071}
2072
Alan Stokesc96b35e2024-05-03 13:21:20 +01002073fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
2074 match config {
2075 VirtualMachineConfig::RawConfig(_) => true,
2076 VirtualMachineConfig::AppConfig(config) => {
2077 let Some(custom) = &config.customConfig else { return true };
2078 custom.wantUpdatable
2079 }
2080 }
2081}
2082
Nikita Ioffe5776f082023-02-10 21:38:26 +00002083fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
2084 match config {
2085 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01002086 VirtualMachineConfig::AppConfig(config) => {
2087 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
2088 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00002089 }
2090}
2091
Nikita Ioffe631717e2023-09-05 13:38:07 +01002092fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2093 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2094 if let Some(custom_config) = &config.customConfig {
2095 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2096 return Err(anyhow!("vendor modules feature is disabled"))
2097 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2098 }
2099 }
2100 Ok(())
2101}
2102
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002103fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2104 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2105 if let Some(custom_config) = &config.customConfig {
2106 if !custom_config.devices.is_empty() {
2107 return Err(anyhow!("device assignment feature is disabled"))
2108 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2109 }
2110 }
2111 Ok(())
2112}
2113
Alan Stokesfda70842023-12-20 17:50:14 +00002114fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2115 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2116 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2117 if !payload_config.extraApks.is_empty() {
2118 return Err(anyhow!("multi-tenant feature is disabled"))
2119 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2120 }
2121 Ok(())
2122}
2123
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002124fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2125 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2126 if let Some(custom_config) = &config.customConfig {
2127 if !custom_config.extraKernelCmdlineParams.is_empty() {
2128 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2129 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2130 }
2131 }
2132 Ok(())
2133}
2134
Nikita Ioffe99548382024-10-21 15:54:46 +00002135fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2136 match config {
2137 VirtualMachineConfig::RawConfig(config) => {
2138 if !config.teeServices.is_empty() {
2139 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2140 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2141 }
2142 }
2143 VirtualMachineConfig::AppConfig(config) => {
2144 if let Some(custom_config) = &config.customConfig {
2145 if !custom_config.teeServices.is_empty() {
2146 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2147 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2148 }
2149 }
2150 }
2151 };
2152 Ok(())
2153}
2154
Nikita Ioffef934e812024-07-05 15:44:41 +00002155fn check_protected_vm_is_supported() -> binder::Result<()> {
2156 let is_pvm_supported =
2157 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2158 if is_pvm_supported {
2159 Ok(())
2160 } else {
2161 Err(anyhow!("pVM is not supported"))
2162 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2163 }
2164}
2165
Nikita Ioffe631717e2023-09-05 13:38:07 +01002166fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2167 if !cfg!(vendor_modules) {
2168 check_no_vendor_modules(config)?;
2169 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002170 if !cfg!(device_assignment) {
2171 check_no_devices(config)?;
2172 }
Alan Stokesfda70842023-12-20 17:50:14 +00002173 if !cfg!(multi_tenant) {
2174 check_no_extra_apks(config)?;
2175 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002176 if !cfg!(debuggable_vms_improvements) {
2177 check_no_extra_kernel_cmdline_params(config)?;
2178 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002179 if !cfg!(tee_services_allowlist) {
2180 check_no_tee_services(config)?;
2181 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002182 Ok(())
2183}
2184
Inseob Kimecde8c02024-09-03 13:11:08 +09002185fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2186 check_no_vendor_modules(config)?;
2187 check_no_devices(config)?;
2188
2189 Ok(())
2190}
2191
Inseob Kim0168b462022-12-27 14:54:35 +09002192fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002193 fd: Option<&ParcelFileDescriptor>,
2194 tag: String,
2195) -> Result<Option<File>, Status> {
2196 if let Some(fd) = fd {
2197 return Ok(Some(clone_file(fd)?));
2198 }
2199
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002200 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002201 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002202
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002203 let mut reader = BufReader::new(File::from(read_fd));
2204 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002205
Frederick Mayle26e41af2025-02-05 18:30:29 -08002206 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002207 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002208 buf.clear();
2209 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002210 match reader.read_until(b'\n', &mut buf) {
2211 Ok(0) => {
2212 // EOF
2213 return;
2214 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002215 Ok(_size) => {
2216 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002217 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002218 // Logs sent via TTY usually end lines with "\r\n".
2219 if buf.last() == Some(&b'\r') {
2220 buf.pop();
2221 }
Inseob Kim0168b462022-12-27 14:54:35 +09002222 }
2223 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2224 }
2225 Err(e) => {
2226 error!("Could not read console pipe: {:?}", e);
2227 return;
2228 }
2229 };
2230 });
2231
2232 Ok(Some(write_fd))
2233}
2234
Jooyung Han35edb8f2021-07-01 16:17:16 +09002235/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2236/// it doesn't require that T implements Clone.
2237enum BorrowedOrOwned<'a, T> {
2238 Borrowed(&'a T),
2239 Owned(T),
2240}
2241
Chris Wailes73a1eb72025-01-15 11:56:43 -08002242impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002243 fn as_ref(&self) -> &T {
2244 match self {
2245 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002246 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002247 }
2248 }
2249}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002250
2251/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2252#[derive(Debug, Default)]
2253struct VirtualMachineService {
2254 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002255 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002256}
2257
2258impl Interface for VirtualMachineService {}
2259
2260impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002261 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2262 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002263 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002264 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002265 vm.update_payload_state(PayloadState::Started)
2266 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002267 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002268
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002269 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2270 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002271 Ok(())
2272 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002273 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002274 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002275 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002276 }
Inseob Kim2444af92021-08-31 01:22:50 +09002277
Inseob Kimc7d28c72021-10-25 14:28:10 +00002278 fn notifyPayloadReady(&self) -> binder::Result<()> {
2279 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002280 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002281 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002282 vm.update_payload_state(PayloadState::Ready)
2283 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002284 vm.callbacks.notify_payload_ready(cid);
2285 Ok(())
2286 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002287 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002288 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002289 }
2290 }
2291
Inseob Kimc7d28c72021-10-25 14:28:10 +00002292 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2293 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002294 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002295 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002296 vm.update_payload_state(PayloadState::Finished)
2297 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002298 vm.callbacks.notify_payload_finished(cid, exit_code);
2299 Ok(())
2300 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002301 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002302 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002303 }
2304 }
2305
Alan Stokes2bead0d2022-09-05 16:58:34 +01002306 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002307 let cid = self.cid;
2308 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002309 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002310 vm.update_payload_state(PayloadState::Finished)
2311 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002312 vm.callbacks.notify_error(cid, error_code, message);
2313 Ok(())
2314 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002315 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002316 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002317 }
2318 }
Alice Wangc2fec932023-02-23 16:24:02 +00002319
Shikha Panware45e9422024-02-28 21:18:10 +00002320 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2321 if !is_secretkeeper_supported() {
2322 return Err(StatusCode::NAME_NOT_FOUND)?;
2323 }
2324 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2325 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002326 }
2327
Alice Wange64dd182024-01-17 15:57:55 +00002328 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2329 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002330 }
Shikha Panwareeae6402025-02-06 19:05:31 +00002331
2332 fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2333 GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2334 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002335}
2336
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002337fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002338 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2339 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002340}
2341
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002342impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002343 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002344 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002345 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002346 BinderFeatures::default(),
2347 )
2348 }
2349}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002350
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002351struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2352
2353impl Interface for SecretkeeperProxy {}
2354
2355impl ISecretkeeper for SecretkeeperProxy {
2356 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2357 // Pass the request to the channel, and read the response.
2358 self.0.processSecretManagementRequest(req)
2359 }
2360
2361 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2362 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2363 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2364 }
2365
2366 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2367 self.0.deleteIds(ids)
2368 }
2369
2370 fn deleteAll(&self) -> binder::Result<()> {
2371 self.0.deleteAll()
2372 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002373
2374 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2375 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2376 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2377 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2378 // use this API from the proxy.
2379 Err(ExceptionCode::SECURITY.into())
2380 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002381}
2382
2383struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2384
2385impl Interface for AuthGraphKeyExchangeProxy {}
2386
2387impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2388 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2389 self.0.create()
2390 }
2391
2392 fn init(
2393 &self,
2394 peer_pub_key: &PubKey,
2395 peer_id: &Identity,
2396 peer_nonce: &[u8],
2397 peer_version: i32,
2398 ) -> binder::Result<KeInitResult> {
2399 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2400 }
2401
2402 fn finish(
2403 &self,
2404 peer_pub_key: &PubKey,
2405 peer_id: &Identity,
2406 peer_signature: &SessionIdSignature,
2407 peer_nonce: &[u8],
2408 peer_version: i32,
2409 own_key: &Key,
2410 ) -> binder::Result<SessionInfo> {
2411 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2412 }
2413
2414 fn authenticationComplete(
2415 &self,
2416 peer_signature: &SessionIdSignature,
2417 shared_keys: &[AuthgraphArc; 2],
2418 ) -> binder::Result<[AuthgraphArc; 2]> {
2419 self.0.authenticationComplete(peer_signature, shared_keys)
2420 }
2421}
2422
Inseob Kimecde8c02024-09-03 13:11:08 +09002423// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002424#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002425struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002426 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002427 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002428 path: String,
2429}
2430
2431#[derive(Debug, Default, Deserialize)]
2432struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002433 early_vm: Vec<EarlyVm>,
2434}
2435
Alice Wang78dd87a2025-02-13 08:56:07 +00002436impl EarlyVm {
2437 /// Verifies that the provided executable path matches the expected path stored in the XML
2438 /// configuration.
2439 /// If the provided path starts with `/system`, it will be stripped before comparison.
2440 fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2441 let actual_path = calling_exe_path.as_ref();
2442 if Path::new(&self.path)
2443 == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2444 {
2445 return Ok(());
2446 }
2447 Err(Status::new_service_specific_error_str(
2448 -1,
2449 Some(format!(
2450 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2451 self.name,
2452 self.path,
2453 actual_path.display()
2454 )),
2455 ))
2456 }
2457}
2458
Frederick Mayle3a46b272025-02-10 21:55:49 -08002459static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002460 LazyLock::new(|| Mutex::new(HashMap::new()));
2461
Frederick Mayle3a46b272025-02-10 21:55:49 -08002462fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002463 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002464 CallingPartition::System => 100..200,
2465 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2466 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2467 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002468 }
2469}
2470
Inseob Kim7e1877b2024-11-07 17:28:56 +09002471fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002472 if !xml_path.exists() {
2473 bail!("{} doesn't exist", xml_path.display());
2474 }
2475
2476 let xml =
2477 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2478 let xml = String::from_utf8(xml)
2479 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2480 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2481 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2482
Inseob Kim7e1877b2024-11-07 17:28:56 +09002483 Ok(early_vms.early_vm)
2484}
Inseob Kimecde8c02024-09-03 13:11:08 +09002485
Inseob Kim7e1877b2024-11-07 17:28:56 +09002486fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2487 for early_vm in early_vms {
2488 let cid = early_vm
2489 .cid
2490 .try_into()
2491 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2492
2493 ensure!(
2494 cid_range.contains(&cid),
2495 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2496 early_vm.name
2497 );
2498 }
2499 Ok(())
2500}
2501
Frederick Mayle3a46b272025-02-10 21:55:49 -08002502fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002503 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2504
Frederick Mayle3a46b272025-02-10 21:55:49 -08002505 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002506 return Ok(result.clone());
2507 }
2508
2509 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2510 let mut early_vms = Vec::new();
2511 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2512 match entry {
2513 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2514 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2515 }
2516 }
2517
Frederick Mayle3a46b272025-02-10 21:55:49 -08002518 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002519 .with_context(|| format!("CID validation for {partition} failed"))?;
2520
Frederick Mayle3a46b272025-02-10 21:55:49 -08002521 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002522
2523 Ok(early_vms)
2524}
2525
2526fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2527 let mut found_vm: Option<&EarlyVm> = None;
2528
2529 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002530 if early_vm.name != name {
2531 continue;
2532 }
2533
Inseob Kimecde8c02024-09-03 13:11:08 +09002534 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002535 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002536 }
2537
2538 found_vm = Some(early_vm);
2539 }
2540
Inseob Kim7e1877b2024-11-07 17:28:56 +09002541 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002542}
2543
Frederick Mayle3a46b272025-02-10 21:55:49 -08002544fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002545 let early_vms = get_early_vms_in_partition(partition)
2546 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2547
2548 Ok(find_early_vm(&early_vms, name)
2549 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2550 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002551}
2552
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002553#[cfg(test)]
2554mod tests {
2555 use super::*;
2556
2557 #[test]
2558 fn test_is_allowed_label_for_partition() -> Result<()> {
2559 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002560 (CallingPartition::System, "u:object_r:system_file:s0", true),
2561 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2562 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2563 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2564 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2565 (CallingPartition::System, "invalid", false),
2566 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2567 (
2568 CallingPartition::System,
2569 "user:role:apk_data_file:severity:categories:extraneous",
2570 false,
2571 ),
2572 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2573 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002574 ];
2575
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002576 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002577 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002578 let result = check_label_is_allowed(&context, calling_partition);
2579 if expected_valid != result.is_ok() {
2580 bail!(
2581 "Expected label {label} to be {} for {calling_partition} partition",
2582 if expected_valid { "allowed" } else { "disallowed" }
2583 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002584 }
2585 }
2586 Ok(())
2587 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002588
2589 #[test]
2590 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2591 let apk = tempfile::tempfile().unwrap();
2592 let idsig = tempfile::tempfile().unwrap();
2593
2594 let ret = create_or_update_idsig_file(
2595 &ParcelFileDescriptor::new(apk),
2596 &ParcelFileDescriptor::new(idsig),
2597 );
2598 assert!(ret.is_err(), "should fail");
2599 Ok(())
2600 }
2601
2602 #[test]
2603 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2604 let tmp_dir = tempfile::TempDir::new().unwrap();
2605 let apk = File::open(tmp_dir.path()).unwrap();
2606 let idsig = tempfile::tempfile().unwrap();
2607
2608 let ret = create_or_update_idsig_file(
2609 &ParcelFileDescriptor::new(apk),
2610 &ParcelFileDescriptor::new(idsig),
2611 );
2612 assert!(ret.is_err(), "should fail");
2613 Ok(())
2614 }
2615
2616 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2617 /// on ext4 filesystem is passed.
2618 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2619 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2620 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2621 #[test]
2622 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2623 // APEXes are backed by the ext4.
2624 let apk = File::open("/apex/com.android.virt/").unwrap();
2625 let idsig = tempfile::tempfile().unwrap();
2626
2627 let ret = create_or_update_idsig_file(
2628 &ParcelFileDescriptor::new(apk),
2629 &ParcelFileDescriptor::new(idsig),
2630 );
2631 assert!(ret.is_err(), "should fail");
2632 Ok(())
2633 }
Jiyong Park8d192952023-06-26 14:29:51 +09002634
2635 #[test]
2636 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2637 use std::io::Seek;
2638
2639 // Pick any APK
2640 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2641 let mut idsig = tempfile::tempfile().unwrap();
2642
2643 create_or_update_idsig_file(
2644 &ParcelFileDescriptor::new(apk.try_clone()?),
2645 &ParcelFileDescriptor::new(idsig.try_clone()?),
2646 )?;
2647 let modified_orig = idsig.metadata()?.modified()?;
2648 apk.rewind()?;
2649 idsig.rewind()?;
2650
2651 // Call the function again
2652 create_or_update_idsig_file(
2653 &ParcelFileDescriptor::new(apk.try_clone()?),
2654 &ParcelFileDescriptor::new(idsig.try_clone()?),
2655 )?;
2656 let modified_new = idsig.metadata()?.modified()?;
2657 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2658 Ok(())
2659 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002660
2661 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002662 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2663 use std::io::Read;
2664
2665 // Pick any APK
2666 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2667 let idsig_empty = tempfile::tempfile().unwrap();
2668 let mut idsig_invalid = tempfile::tempfile().unwrap();
2669 idsig_invalid.write_all(b"Oops")?;
2670
2671 // Create new idsig
2672 create_or_update_idsig_file(
2673 &ParcelFileDescriptor::new(apk.try_clone()?),
2674 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2675 )?;
2676 apk.rewind()?;
2677
2678 // Update idsig_invalid
2679 create_or_update_idsig_file(
2680 &ParcelFileDescriptor::new(apk.try_clone()?),
2681 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2682 )?;
2683
2684 // Ensure the 2 idsig files have same size!
2685 assert!(
2686 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2687 "idsig files differ in size"
2688 );
2689 // Ensure the 2 idsig files have same content!
2690 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2691 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2692 }
2693 Ok(())
2694 }
2695 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002696 fn test_append_kernel_param_first_param() {
2697 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2698 append_kernel_param("foo=1", &mut vm_config);
2699 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2700 }
2701
2702 #[test]
2703 fn test_append_kernel_param() {
2704 let mut vm_config =
2705 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2706 append_kernel_param("bar=42", &mut vm_config);
2707 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2708 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002709
Inseob Kim46257382024-01-03 15:41:22 +09002710 fn test_extract_os_name_from_config_path(
2711 path: &Path,
2712 expected_result: Option<&str>,
2713 ) -> Result<()> {
2714 let result = extract_os_name_from_config_path(path);
2715 if result.as_deref() != expected_result {
2716 bail!("Expected {:?} but was {:?}", expected_result, &result)
2717 }
2718 Ok(())
2719 }
2720
2721 #[test]
2722 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2723 test_extract_os_name_from_config_path(
2724 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2725 Some("microdroid"),
2726 )
2727 }
2728
2729 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002730 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2731 test_extract_os_name_from_config_path(
2732 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2733 Some("microdroid_16k"),
2734 )
2735 }
2736
2737 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002738 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2739 test_extract_os_name_from_config_path(
2740 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2741 Some("microdroid_gki-android14-6.1"),
2742 )
2743 }
2744
2745 #[test]
2746 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2747 test_extract_os_name_from_config_path(
2748 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2749 None,
2750 )
2751 }
2752
2753 #[test]
2754 fn test_extract_os_name_from_configs() -> Result<()> {
2755 let tmp_dir = tempfile::TempDir::new()?;
2756 let tmp_dir_path = tmp_dir.path().to_owned();
2757
2758 let mut os_names: HashSet<String> = HashSet::new();
2759 os_names.insert("microdroid".to_owned());
2760 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2761 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2762
2763 // config files
2764 for os_name in &os_names {
2765 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2766 }
2767
2768 // fake files not related to configs
2769 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2770 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2771
2772 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2773 Some(s) => s.to_owned(),
2774 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2775 };
2776
2777 let result = extract_os_names_from_configs(&glob_pattern)?;
2778 if result != os_names {
2779 bail!("Expected {:?} but was {:?}", os_names, result);
2780 }
2781 Ok(())
2782 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002783
2784 #[test]
2785 fn test_find_early_vms_from_xml() -> Result<()> {
2786 let tmp_dir = tempfile::TempDir::new()?;
2787 let tmp_dir_path = tmp_dir.path().to_owned();
2788 let xml_path = tmp_dir_path.join("early_vms.xml");
2789
2790 std::fs::write(
2791 &xml_path,
2792 br#"<?xml version="1.0" encoding="utf-8"?>
2793 <early_vms>
2794 <early_vm>
2795 <name>vm_demo_native_early</name>
2796 <cid>123</cid>
2797 <path>/system/bin/vm_demo_native_early</path>
2798 </early_vm>
2799 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002800 <name>vm_demo_native_early_2</name>
2801 <cid>456</cid>
2802 <path>/system/bin/vm_demo_native_early_2</path>
2803 </early_vm>
2804 </early_vms>
2805 "#,
2806 )?;
2807
2808 let cid_range = 100..1000;
2809
2810 let early_vms = get_early_vms_in_path(&xml_path)?;
2811 validate_cid_range(&early_vms, &cid_range)?;
2812
2813 let test_cases = [
2814 (
2815 "vm_demo_native_early",
2816 EarlyVm {
2817 name: "vm_demo_native_early".to_owned(),
2818 cid: 123,
2819 path: "/system/bin/vm_demo_native_early".to_owned(),
2820 },
2821 ),
2822 (
2823 "vm_demo_native_early_2",
2824 EarlyVm {
2825 name: "vm_demo_native_early_2".to_owned(),
2826 cid: 456,
2827 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2828 },
2829 ),
2830 ];
2831
2832 for (name, expected) in test_cases {
2833 let result = find_early_vm(&early_vms, name)?;
2834 assert_eq!(result, &expected);
2835 }
2836
2837 Ok(())
2838 }
2839
2840 #[test]
2841 fn test_invalid_cid_validation() -> Result<()> {
2842 let tmp_dir = tempfile::TempDir::new()?;
2843 let xml_path = tmp_dir.path().join("early_vms.xml");
2844
2845 let cid_range = 100..1000;
2846
2847 for cid in [-1, 999999] {
2848 std::fs::write(
2849 &xml_path,
2850 format!(
2851 r#"<?xml version="1.0" encoding="utf-8"?>
2852 <early_vms>
2853 <early_vm>
2854 <name>vm_demo_invalid_cid</name>
2855 <cid>{cid}</cid>
2856 <path>/system/bin/vm_demo_invalid_cid</path>
2857 </early_vm>
2858 </early_vms>
2859 "#
2860 ),
2861 )?;
2862
2863 let early_vms = get_early_vms_in_path(&xml_path)?;
2864 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2865 }
2866
2867 Ok(())
2868 }
2869
2870 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002871 fn test_symlink_to_system_ext_supported() -> Result<()> {
2872 let link_path = Path::new("/system/system_ext/file");
2873 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002874 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002875 Ok(())
2876 }
2877
2878 #[test]
2879 fn test_symlink_to_product_supported() -> Result<()> {
2880 let link_path = Path::new("/system/product/file");
2881 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002882 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002883 Ok(())
2884 }
2885
2886 #[test]
Frederick Mayle2192baf2025-02-26 11:27:22 -08002887 fn test_vendor_in_data() {
2888 assert_eq!(
2889 CallingPartition::Vendor,
2890 find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap()
2891 );
2892 }
2893
2894 #[test]
Alice Wang78dd87a2025-02-13 08:56:07 +00002895 fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2896 let early_vm = EarlyVm {
2897 name: "vm_demo_native_early".to_owned(),
2898 cid: 123,
2899 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2900 };
2901 let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2902 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2903 }
2904
2905 #[test]
2906 fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2907 let early_vm = EarlyVm {
2908 name: "vm_demo_native_early".to_owned(),
2909 cid: 123,
2910 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2911 };
2912 let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2913 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2914 }
2915
2916 #[test]
2917 fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2918 let early_vm = EarlyVm {
2919 name: "vm_demo_native_early".to_owned(),
2920 cid: 123,
2921 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2922 };
2923 let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2924 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2925 }
2926
2927 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002928 fn test_duplicated_early_vms() -> Result<()> {
2929 let tmp_dir = tempfile::TempDir::new()?;
2930 let tmp_dir_path = tmp_dir.path().to_owned();
2931 let xml_path = tmp_dir_path.join("early_vms.xml");
2932
2933 std::fs::write(
2934 &xml_path,
2935 br#"<?xml version="1.0" encoding="utf-8"?>
2936 <early_vms>
2937 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002938 <name>vm_demo_duplicated_name</name>
2939 <cid>456</cid>
2940 <path>/system/bin/vm_demo_duplicated_name_1</path>
2941 </early_vm>
2942 <early_vm>
2943 <name>vm_demo_duplicated_name</name>
2944 <cid>789</cid>
2945 <path>/system/bin/vm_demo_duplicated_name_2</path>
2946 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002947 </early_vms>
2948 "#,
2949 )?;
2950
2951 let cid_range = 100..1000;
2952
Inseob Kim7e1877b2024-11-07 17:28:56 +09002953 let early_vms = get_early_vms_in_path(&xml_path)?;
2954 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002955
Inseob Kim7e1877b2024-11-07 17:28:56 +09002956 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002957
2958 Ok(())
2959 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002960}