blob: 3deb67cd597b2495cea54ccbe0015ad0344a1950 [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 Ioffef1ce9872022-12-09 13:31:59 +0000154fn create_or_update_idsig_file(
155 input_fd: &ParcelFileDescriptor,
156 idsig_fd: &ParcelFileDescriptor,
157) -> Result<()> {
158 let mut input = clone_file(input_fd)?;
159 let metadata = input.metadata().context("failed to get input metadata")?;
160 if !metadata.is_file() {
161 bail!("input is not a regular file");
162 }
Alan Stokes25f69362023-03-06 16:51:54 +0000163 let mut sig =
164 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
165 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000166
167 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900168
169 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
170 // if the idsig file already has the same APK digest.
171 if output.metadata()?.len() > 0 {
172 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
173 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
174 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
175 return Ok(());
176 }
177 }
178 // if we fail to read v4signature from output, that's fine. User can pass a random file.
179 // We will anyway overwrite the file to the v4signature generated from input_fd.
180 }
181
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000182 output
183 .seek(SeekFrom::Start(0))
184 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000185 output.set_len(0).context("failed to set_len on the idsig output")?;
186 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000187 Ok(())
188}
189
Alan Stokes25f69362023-03-06 16:51:54 +0000190fn get_current_sdk() -> Result<u32> {
191 let current_sdk = system_properties::read("ro.build.version.sdk")?;
192 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
193 current_sdk.parse().context("Malformed SDK version")
194}
195
David Brazdil4b4c5102022-12-19 22:56:20 +0000196pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
197 for dir_entry in read_dir(path)? {
198 remove_file(dir_entry?.path())?;
199 }
200 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100201}
202
David Brazdil528e0472022-10-10 15:06:02 +0100203/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000204#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000205pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900206 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207}
208
Shikha Panward8e35422021-10-11 13:51:27 +0000209impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000211 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
212 let state = &mut *self.state.lock().unwrap();
213 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000214 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000215 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000216 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
217 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000218 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000219 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000220 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
222 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000223 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000225 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000226 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000227 .or(Err(StatusCode::UNKNOWN_ERROR))?;
228 }
229 Ok(())
230 }
231}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000232impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
234 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000235 ///
236 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000238 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000239 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900240 console_out_fd: Option<&ParcelFileDescriptor>,
241 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000242 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000243 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000244 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000245 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900246 let ret = self.create_vm_internal(
247 config,
248 console_out_fd,
249 console_in_fd,
250 log_fd,
251 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000252 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900253 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000254 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000255 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000256 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000257
Shikha Panwar61a74b52024-02-16 13:17:01 +0000258 /// Allocate a new instance_id to the VM
259 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000260 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000261 GLOBAL_SERVICE.allocateInstanceId()
262 }
263
Andrew Walbrandff3b942021-06-09 15:20:36 +0000264 /// Initialise an empty partition image of the given size to be used as a writable partition.
265 fn initializeWritablePartition(
266 &self,
267 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000268 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900269 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000270 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900271 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900272 let size_bytes = size_bytes
273 .try_into()
274 .with_context(|| format!("Invalid size: {}", size_bytes))
275 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000277 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000279 image
280 .seek(SeekFrom::Start(0))
281 .context("failed to move cursor to start")
282 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700284 // Set the file length. In most filesystems, this will not allocate any physical disk
285 // space, it will only change the logical size.
286 image
287 .set_len(size_bytes)
288 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900289 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290
291 match partition_type {
292 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700293 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
294 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000295 _ => Err(Error::new(
296 ErrorKind::Unsupported,
297 format!("Unsupported partition type {:?}", partition_type),
298 )),
299 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
301 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000302
303 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000304 }
305
Jiyong Park0a248432021-08-20 23:32:39 +0900306 /// Creates or update the idsig file by digesting the input APK file.
307 fn createOrUpdateIdsigFile(
308 &self,
309 input_fd: &ParcelFileDescriptor,
310 idsig_fd: &ParcelFileDescriptor,
311 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900312 check_manage_access()?;
313
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900315 Ok(())
316 }
317
Andrew Walbran320b5602021-03-04 16:11:12 +0000318 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
319 /// and as such is only permitted from the shell user.
320 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000321 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000322 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000323 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900324
325 /// Get a list of assignable device types.
326 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
327 // Delegate to the global service, including checking the permission.
328 GLOBAL_SERVICE.getAssignableDevices()
329 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100330
Inseob Kim46257382024-01-03 15:41:22 +0900331 /// Get a list of supported OSes.
332 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
333 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
334 }
335
Jaewan Kimabd328b2024-12-10 15:59:33 +0900336 /// Get printable debug policy for testing and debugging
337 fn getDebugPolicy(&self) -> binder::Result<String> {
338 let debug_policy = DebugPolicy::from_host();
339 Ok(format!("{debug_policy:?}"))
340 }
341
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100342 /// Returns whether given feature is enabled
343 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
344 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000345 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100346 }
Alice Wange64dd182024-01-17 15:57:55 +0000347
348 fn enableTestAttestation(&self) -> binder::Result<()> {
349 GLOBAL_SERVICE.enableTestAttestation()
350 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000351
352 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
353 check_manage_access()?;
354 GLOBAL_SERVICE.isRemoteAttestationSupported()
355 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000356
357 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
358 // The response is specific to Microdroid. Updatable VMs are only possible if device
359 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
360 // this, however other guest OSes may do things differently.
361 check_manage_access()?;
362 Ok(is_secretkeeper_supported())
363 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000364
Shikha Panwar07d701c2024-03-28 14:43:52 +0000365 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
366 check_manage_access()?;
367 GLOBAL_SERVICE.removeVmInstance(instance_id)
368 }
369
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000370 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
371 check_manage_access()?;
372 GLOBAL_SERVICE.claimVmInstance(instance_id)
373 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000374}
375
Inseob Kimecde8c02024-09-03 13:11:08 +0900376/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
377#[derive(Debug, Default)]
378struct EarlyVmContext {
379 /// The unique CID assigned to the VM for vsock communication.
380 cid: Cid,
381 /// Temporary directory for this VM instance.
382 temp_dir: PathBuf,
383}
384
385impl EarlyVmContext {
386 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
387 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
388 // should trust clients, e.g. they won't run two VMs at the same time
389 let _ = remove_dir_all(&temp_dir);
390 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
391
392 Ok(Self { cid, temp_dir })
393 }
394}
395
396impl Interface for EarlyVmContext {}
397
398impl Drop for EarlyVmContext {
399 fn drop(&mut self) {
400 if let Err(e) = remove_dir_all(&self.temp_dir) {
401 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
402 }
403 }
404}
405
406impl IGlobalVmContext for EarlyVmContext {
407 fn getCid(&self) -> binder::Result<i32> {
408 Ok(self.cid as i32)
409 }
410
411 fn getTemporaryDirectory(&self) -> binder::Result<String> {
412 Ok(self.temp_dir.to_string_lossy().to_string())
413 }
414
415 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
416 Err(Status::new_exception_str(
417 ExceptionCode::UNSUPPORTED_OPERATION,
418 Some("Early VM doesn't support setting host console name"),
419 ))
420 }
421}
422
Inseob Kime3e932d2024-12-16 20:06:57 +0900423fn find_partition(path: Option<&Path>) -> binder::Result<String> {
424 let path = match path {
425 Some(path) => path,
426 None => return Ok("system".to_owned()),
427 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000428 if path.starts_with("/system/system_ext/") {
429 return Ok("system_ext".to_owned());
430 } else if path.starts_with("/system/product/") {
431 return Ok("product".to_owned());
432 }
Inseob Kimf79c5722024-12-16 17:29:57 +0900433 let mut components = path.components();
434 match components.nth(1) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900435 Some(std::path::Component::Normal(partition)) => {
Inseob Kimf79c5722024-12-16 17:29:57 +0900436 if partition != "apex" {
437 return Ok(partition.to_string_lossy().into_owned());
438 }
439
440 // If path is under /apex, find a partition of the preinstalled .apex path
441 let apex_name = match components.next() {
442 Some(std::path::Component::Normal(name)) => name.to_string_lossy(),
443 _ => {
444 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
445 .or_service_specific_exception(-1)
446 }
447 };
448
449 let apex_info_list = ApexInfoList::load()
450 .context("Failed to get apex info list")
451 .or_service_specific_exception(-1)?;
452
453 for apex_info in apex_info_list.list.iter() {
454 if apex_info.name == apex_name {
455 return Ok(apex_info.partition.to_lowercase());
456 }
457 }
458
459 Err(anyhow!("Can't find apex info for '{apex_name}'")).or_service_specific_exception(-1)
Inseob Kimecde8c02024-09-03 13:11:08 +0900460 }
461 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
462 .or_service_specific_exception(-1),
463 }
464}
465
Jiyong Park8611a6c2021-07-09 18:17:44 +0900466impl VirtualizationService {
467 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000468 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900469 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470
Inseob Kimecde8c02024-09-03 13:11:08 +0900471 fn create_early_vm_context(
472 &self,
473 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900474 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900475 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900476 let name = match config {
477 VirtualMachineConfig::RawConfig(config) => &config.name,
478 VirtualMachineConfig::AppConfig(config) => &config.name,
479 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900480 let calling_partition = find_partition(calling_exe_path)?;
481 let early_vm = find_early_vm_for_partition(&calling_partition, name)
482 .or_service_specific_exception(-1)?;
483 let calling_exe_path = match calling_exe_path {
484 Some(path) => path,
485 None => {
486 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
487 .or_service_specific_exception(-1)
488 }
489 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000490 let expected_exe_path = Path::new(&early_vm.path);
491 if expected_exe_path != calling_exe_path
492 && Path::new("/system").join(expected_exe_path) != calling_exe_path
493 {
Inseob Kimecde8c02024-09-03 13:11:08 +0900494 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900495 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900496 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900497 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900498 ))
499 .or_service_specific_exception(-1);
500 }
501
502 let cid = early_vm.cid as Cid;
503 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
504
505 let context = EarlyVmContext::new(cid, temp_dir.clone())
506 .context(format!("Can't create early vm contexts for {cid}"))
507 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900508
Jiyong Park690c1ca2024-11-28 18:06:50 +0900509 if requires_vm_service(config) {
510 // Start VM service listening for connections from the new CID on port=CID.
511 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
512 let port = cid;
513 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
514 .context(format!("Could not start RpcServer on port {port}"))
515 .or_service_specific_exception(-1)?;
516 vm_server.start();
517 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
518 } else {
519 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
520 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900521 }
522
David Brazdil209074a2023-01-12 16:44:51 +0000523 fn create_vm_context(
524 &self,
525 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900526 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000527 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000528 const NUM_ATTEMPTS: usize = 5;
529
530 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000531 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000532 let cid = vm_context.getCid()? as Cid;
533 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900534
535 // We don't need to start the VM service for custom VMs.
536 if !requires_vm_service(config) {
537 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
538 }
539
David Brazdil8cf8f482022-11-23 14:21:26 +0000540 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
541
542 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000543 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000544 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000545 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000546 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900547 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000548 }
549 Err(err) => {
550 warn!("Could not start RpcServer on port {}: {}", port, err);
551 }
552 }
553 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900554 Err(anyhow!("Too many attempts to create VM context failed"))
555 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000556 }
557
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000558 fn create_vm_internal(
559 &self,
560 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900561 console_out_fd: Option<&ParcelFileDescriptor>,
562 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000563 log_fd: Option<&ParcelFileDescriptor>,
564 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000565 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000566 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000567 let requester_uid = get_calling_uid();
568 let requester_debug_pid = get_calling_pid();
569
Nikita Ioffe631717e2023-09-05 13:38:07 +0100570 check_config_features(config)?;
571
Inseob Kimecde8c02024-09-03 13:11:08 +0900572 if cfg!(early) {
573 check_config_allowed_for_early_vms(config)?;
574 }
575
Nikita Ioffeb1416122024-10-22 12:18:49 +0000576 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
577 info!("callers secontext: {}", caller_secontext);
578
David Brazdil209074a2023-01-12 16:44:51 +0000579 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900580 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900581 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900582 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900583 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900584 };
Inseob Kim1119d702022-05-02 18:01:58 +0900585
Alan Stokesfda70842023-12-20 17:50:14 +0000586 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100587 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900588 }
589
Nikita Ioffe5776f082023-02-10 21:38:26 +0000590 let gdb_port = extract_gdb_port(config);
591
592 // Additional permission checks if caller request gdb.
593 if gdb_port.is_some() {
594 check_gdb_allowed(config)?;
595 }
596
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800597 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900598 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800599 if let Some(dt_overlay) =
600 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
601 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900602 device_tree_overlays.push(dt_overlay);
603 }
604 if let Some(dtbo) = get_dtbo(config) {
605 let dtbo = File::from(
606 dtbo.as_ref()
607 .try_clone()
608 .context("Failed to create VM DTBO from ParcelFileDescriptor")
609 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
610 );
611 device_tree_overlays.push(dtbo);
612 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900613
Jaewan Kimf3143242024-03-15 06:56:31 +0000614 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000615 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900616 Some(prepare_ramdump_file(&temporary_directory)?)
617 } else {
618 None
619 };
620
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000621 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900622 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100623 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900624 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100625 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100626 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
627 Some(clone_file(fd)?)
628 } else if debug_config.dump_device_tree {
629 Some(prepare_dump_dt_file(&temporary_directory)?)
630 } else {
631 None
632 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000633
634 // Counter to generate unique IDs for temporary image files.
635 let mut next_temporary_image_id = 0;
636 // Files which are referred to from composite images. These must be mapped to the crosvm
637 // child process, and not closed before it is started.
638 let mut indirect_files = vec![];
639
Alan Stokes7bc146c2022-10-20 17:10:32 +0100640 let (is_app_config, config) = match config {
641 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
642 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900643 let config = load_app_config(config, &debug_config, &temporary_directory)
644 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900645 *is_protected = config.protectedVm;
646 let message = format!("Failed to load app config: {:?}", e);
647 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900648 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900649 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100650 (true, BorrowedOrOwned::Owned(config))
651 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000652 };
653 let config = config.as_ref();
654 *is_protected = config.protectedVm;
655
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000656 if !config.teeServices.is_empty() {
657 check_tee_service_permission(&caller_secontext, &config.teeServices)
658 .with_log()
659 .or_binder_exception(ExceptionCode::SECURITY)?;
660 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000661
Jiyong Park3051ffe2024-11-26 14:41:58 +0900662 let kernel = maybe_clone_file(&config.kernel)?;
663 let initrd = maybe_clone_file(&config.initrd)?;
664
665 if config.protectedVm {
666 // Fail fast with a meaningful error message in case device doesn't support pVMs.
667 check_protected_vm_is_supported()?;
668
669 // In a protected VM, we require custom kernels to come from a trusted source
670 // (b/237054515).
671 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
672
673 // Check if partition images are labeled incorrectly. This is to prevent random images
674 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
675 // from being loaded in a pVM. This applies to everything but the instance image in the
676 // raw config, and everything but the non-executable, generated partitions in the app
677 // config.
678 config
679 .disks
680 .iter()
681 .flat_map(|disk| disk.partitions.iter())
682 .filter(|partition| {
683 if is_app_config {
684 !is_safe_app_partition(&partition.label)
685 } else {
686 !is_safe_raw_partition(&partition.label)
687 }
688 })
689 .try_for_each(check_label_for_partition)
690 .or_service_specific_exception(-1)?;
691 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000692
Inseob Kimff48a7c2024-02-26 22:07:21 +0900693 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
694 // have unstable interfaces.
695 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Inseob Kime3e932d2024-12-16 20:06:57 +0900696 check_partitions_for_files(config, &find_partition(CALLING_EXE_PATH.as_deref())?)
697 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900698
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000699 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900700 write_zero_filler(&zero_filler_path)
701 .context("Failed to make composite image")
702 .with_log()
703 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000704
705 // Assemble disk images if needed.
706 let disks = config
707 .disks
708 .iter()
709 .map(|disk| {
710 assemble_disk_image(
711 disk,
712 &zero_filler_path,
713 &temporary_directory,
714 &mut next_temporary_image_id,
715 &mut indirect_files,
716 )
717 })
718 .collect::<Result<Vec<DiskFile>, _>>()?;
719
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700720 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
721
Jaewan Kimf43372b2024-12-13 18:33:58 +0900722 let (vfio_devices, dtbo) = match &config.devices {
723 AssignedDevices::Devices(devices) if !devices.is_empty() => {
724 let mut set = HashSet::new();
725 for device in devices.iter() {
726 let path = canonicalize(device)
727 .with_context(|| format!("can't canonicalize {device}"))
728 .or_service_specific_exception(-1)?;
729 if !set.insert(path) {
730 return Err(anyhow!("duplicated device {device}"))
731 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
732 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900733 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900734 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
735 let dtbo_file = File::from(
736 GLOBAL_SERVICE
737 .getDtboFile()?
738 .as_ref()
739 .try_clone()
740 .context("Failed to create VM DTBO from ParcelFileDescriptor")
741 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
742 );
743 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900744 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900745 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900746 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900747 let display_config = if cfg!(paravirtualized_devices) {
748 config
749 .displayConfig
750 .as_ref()
751 .map(DisplayConfig::new)
752 .transpose()
753 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
754 } else {
755 None
756 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700757 let gpu_config = if cfg!(paravirtualized_devices) {
758 config
759 .gpuConfig
760 .as_ref()
761 .map(GpuConfig::new)
762 .transpose()
763 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
764 } else {
765 None
766 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900767
Jeongik Chac181be72024-03-27 00:18:30 +0900768 let input_device_options = if cfg!(paravirtualized_devices) {
769 config
770 .inputDevices
771 .iter()
772 .map(to_input_device_option_from)
773 .collect::<Result<Vec<InputDeviceOption>, _>>()
774 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
775 } else {
776 vec![]
777 };
778
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900779 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900780 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900781 if *is_protected {
782 return Err(anyhow!("Network feature is not supported for pVM yet"))
783 .with_log()
784 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
785 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900786 Some(File::from(
787 GLOBAL_SERVICE
788 .createTapInterface(&get_this_pid().to_string())?
789 .as_ref()
790 .try_clone()
791 .context("Failed to get TAP interface from ParcelFileDescriptor")
792 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
793 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900794 } else {
795 None
796 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800797
798 let audio_config = if cfg!(paravirtualized_devices) {
799 config.audioConfig.as_ref().map(AudioConfig::new)
800 } else {
801 None
802 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900803
Elie Kheirallah29d72912024-08-07 20:17:26 +0000804 let usb_config = config
805 .usbConfig
806 .as_ref()
807 .map(UsbConfig::new)
808 .unwrap_or(Ok(UsbConfig { controller: false }))
809 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
810
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000811 let detect_hangup = is_app_config && gdb_port.is_none();
812
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000813 // Actually start the VM.
814 let crosvm_config = CrosvmConfig {
815 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000816 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000817 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000818 kernel,
819 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000820 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700821 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000822 params: config.params.to_owned(),
823 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900824 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700825 memory_mib: config
826 .memoryMib
827 .try_into()
828 .ok()
829 .and_then(NonZeroU32::new)
830 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800831 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000832 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900833 console_out_fd,
834 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000835 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900836 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000837 indirect_files,
838 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000839 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000840 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900841 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000842 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900843 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900844 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900845 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000846 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900847 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800848 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000849 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700850 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800851 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800852 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000853 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000854 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800855 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
856 instance_id,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000857 };
858 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100859 VmInstance::new(
860 crosvm_config,
861 temporary_directory,
862 requester_uid,
863 requester_debug_pid,
864 vm_context,
865 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900866 .with_context(|| format!("Failed to create VM with config {:?}", config))
867 .with_log()
868 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000869 );
870 state.add_vm(Arc::downgrade(&instance));
871 Ok(VirtualMachine::create(instance))
872 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900873}
874
Alan Stokesfda70842023-12-20 17:50:14 +0000875/// Returns whether a VM config represents a "custom" virtual machine, which requires the
876/// USE_CUSTOM_VIRTUAL_MACHINE.
877fn is_custom_config(config: &VirtualMachineConfig) -> bool {
878 match config {
879 // Any raw (non-Microdroid) VM is considered custom.
880 VirtualMachineConfig::RawConfig(_) => true,
881 VirtualMachineConfig::AppConfig(config) => {
882 // Some features are reserved for platform apps only, even when using
883 // VirtualMachineAppConfig. Almost all of these features are grouped in the
884 // CustomConfig struct:
885 // - controlling CPUs;
886 // - gdbPort is set, meaning that crosvm will start a gdb server;
887 // - using anything other than the default kernel;
888 // - specifying devices to be assigned.
889 if config.customConfig.is_some() {
890 true
891 } else {
892 // Additional custom features not included in CustomConfig:
893 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000894 // - specifying extra APKs;
895 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900896 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000897 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900898 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
899 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000900 }
901 }
902 }
903}
904
Jiyong Park690c1ca2024-11-28 18:06:50 +0900905/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
906/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
907/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
908/// "microdroid" we run VirtualMachineService
909fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
910 match config {
911 VirtualMachineConfig::AppConfig(_) => true,
912 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
913 }
914}
915
Seungjae Yoo14e60182024-02-21 13:28:31 +0900916fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
917 let VirtualMachineConfig::AppConfig(config) = config else {
918 return Ok(None);
919 };
920 let Some(custom_config) = &config.customConfig else {
921 return Ok(None);
922 };
923 let Some(file) = custom_config.vendorImage.as_ref() else {
924 return Ok(None);
925 };
926
927 let file = clone_file(file)?;
928 let size =
929 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
930 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
931 .context("Failed to get vbmeta from microdroid-vendor.img")?;
932
933 for descriptor in vbmeta.descriptors()?.iter() {
934 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
935 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
936 return Ok(Some(root_digest.as_bytes().to_vec()));
937 }
938 }
939 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
940}
941
Jaewan Kimf43372b2024-12-13 18:33:58 +0900942fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000943 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800944 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000945 temporary_directory: &Path,
946) -> binder::Result<Option<File>> {
947 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
948 // (e.g. instance-id)
949 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
950 let host_ref_dt = if host_ref_dt.exists()
951 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
952 {
953 Some(host_ref_dt)
954 } else {
955 warn!("VM reference DT doesn't exist in host DT");
956 None
957 };
958
959 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
960 .context("Failed to extract vendor hashtree digest")
961 .or_service_specific_exception(-1)?;
962
Matt Gilbrideaade4272024-12-05 13:52:42 +0000963 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000964 info!(
965 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
966 match the trusted digest in the pvmfw config, causing the VM to fail to start."
967 );
Alan Stokesf46a17c2025-01-05 15:50:18 +0000968 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000969 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000970 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000971 };
972
Matt Gilbrideaade4272024-12-05 13:52:42 +0000973 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000974 let mut untrusted_props = Vec::with_capacity(2);
975 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000976 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000977 let want_updatable = extract_want_updatable(config);
978 if want_updatable && is_secretkeeper_supported() {
979 // Let guest know that it can defer rollback protection to Secretkeeper by setting
980 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000981 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +0000982 let sk: Strong<dyn ISecretkeeper> =
983 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
984 if sk.getInterfaceVersion()? >= 2 {
985 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
986 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000987 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +0000988 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000989 }
990 }
991
992 let device_tree_overlay = if host_ref_dt.is_some()
993 || !untrusted_props.is_empty()
994 || !trusted_props.is_empty()
995 {
996 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
997 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
998 let fdt =
999 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1000 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1001 .or_service_specific_exception(-1)?;
1002 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1003 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1004 } else {
1005 None
1006 };
1007 Ok(device_tree_overlay)
1008}
1009
Jaewan Kimf43372b2024-12-13 18:33:58 +09001010fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1011 let VirtualMachineConfig::RawConfig(config) = config else {
1012 return None;
1013 };
1014 match &config.devices {
1015 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1016 _ => None,
1017 }
1018}
1019
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001020fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001021 let file = OpenOptions::new()
1022 .create_new(true)
1023 .read(true)
1024 .write(true)
1025 .open(zero_filler_path)
1026 .with_context(|| "Failed to create zero.img")?;
1027 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001028 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001029}
1030
David Brazdilf50c7a62023-04-19 14:22:42 +00001031fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1032 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1033 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1034 part.flush()
1035}
1036
1037fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1038 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1039 part.flush()
1040}
1041
1042fn round_up(input: u64, granularity: u64) -> u64 {
1043 if granularity == 0 {
1044 return input;
1045 }
1046 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1047 let result = input.checked_add(granularity - 1).unwrap_or(input);
1048 (result / granularity) * granularity
1049}
1050
Jeongik Chac181be72024-03-27 00:18:30 +09001051fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1052 Ok(match input_device {
1053 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1054 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1055 height: u32::try_from(single_touch.height)?,
1056 width: u32::try_from(single_touch.width)?,
1057 name: if !single_touch.name.is_empty() {
1058 Some(single_touch.name.clone())
1059 } else {
1060 None
1061 },
1062 },
1063 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1064 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1065 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001066 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1067 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1068 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001069 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1070 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1071 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001072 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1073 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1074 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001075 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1076 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1077 height: u32::try_from(trackpad.height)?,
1078 width: u32::try_from(trackpad.width)?,
1079 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1080 },
Jeongik Cha10494912024-07-16 11:19:50 +09001081 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1082 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1083 height: u32::try_from(multi_touch.height)?,
1084 width: u32::try_from(multi_touch.width)?,
1085 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1086 },
Jeongik Chac181be72024-03-27 00:18:30 +09001087 })
1088}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001089
1090fn assemble_shared_paths(
1091 shared_paths: &[SharedPath],
1092 temporary_directory: &Path,
1093) -> Result<Vec<SharedPathConfig>, Status> {
1094 if shared_paths.is_empty() {
1095 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1096 }
1097
1098 shared_paths
1099 .iter()
1100 .map(|path| {
1101 Ok(SharedPathConfig {
1102 path: path.sharedPath.clone(),
1103 host_uid: path.hostUid,
1104 host_gid: path.hostGid,
1105 guest_uid: path.guestUid,
1106 guest_gid: path.guestGid,
1107 mask: path.mask,
1108 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001109 socket_path: temporary_directory
1110 .join(&path.socketPath)
1111 .to_string_lossy()
1112 .to_string(),
1113 socket_fd: maybe_clone_file(&path.socketFd)?,
1114 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001115 })
1116 })
1117 .collect()
1118}
1119
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001120/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1121///
1122/// This may involve assembling a composite disk from a set of partition images.
1123fn assemble_disk_image(
1124 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001125 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001126 temporary_directory: &Path,
1127 next_temporary_image_id: &mut u64,
1128 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001129) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001130 let image = if !disk.partitions.is_empty() {
1131 if disk.image.is_some() {
1132 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001133 return Err(anyhow!("DiskImage contains both image and partitions"))
1134 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001135 }
1136
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001137 let composite_image_filenames =
1138 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1139 let (image, partition_files) = make_composite_image(
1140 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001141 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001142 &composite_image_filenames.composite,
1143 &composite_image_filenames.header,
1144 &composite_image_filenames.footer,
1145 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001146 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1147 .with_log()
1148 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001149
1150 // Pass the file descriptors for the various partition files to crosvm when it
1151 // is run.
1152 indirect_files.extend(partition_files);
1153
1154 image
1155 } else if let Some(image) = &disk.image {
1156 clone_file(image)?
1157 } else {
1158 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001159 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1160 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001161 };
1162
1163 Ok(DiskFile { image, writable: disk.writable })
1164}
1165
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001166fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1167 if let Some(ref mut params) = vm_config.params {
1168 params.push(' ');
1169 params.push_str(param)
1170 } else {
1171 vm_config.params = Some(param.to_owned())
1172 }
1173}
1174
Inseob Kim46257382024-01-03 15:41:22 +09001175fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1176 if config.extension()?.to_str()? != "json" {
1177 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001178 }
Inseob Kim46257382024-01-03 15:41:22 +09001179
1180 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1181}
1182
1183fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1184 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1185 let os_names =
1186 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1187
1188 Ok(os_names)
1189}
1190
1191fn get_supported_os_names() -> Result<HashSet<String>> {
1192 if !cfg!(vendor_modules) {
1193 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1194 }
1195
1196 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1197}
1198
1199fn is_valid_os(os_name: &str) -> bool {
1200 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001201}
1202
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001203fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1204 if !cfg!(vendor_modules) {
1205 return false;
1206 }
1207 match config {
1208 VirtualMachineConfig::RawConfig(_) => false,
1209 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1210 }
1211}
1212
Jooyung Han21e9b922021-06-26 04:14:16 +09001213fn load_app_config(
1214 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001215 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001216 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001217) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001218 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1219 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001220 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001221
Shikha Panwar22e70452022-10-10 18:32:55 +00001222 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1223 Some(clone_file(file)?)
1224 } else {
1225 None
1226 };
1227
Alan Stokesfda70842023-12-20 17:50:14 +00001228 let vm_payload_config;
1229 let extra_apk_files: Vec<_>;
1230 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001231 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001232 vm_payload_config =
1233 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1234 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1235 extra_apk_files = vm_payload_config
1236 .extra_apks
1237 .iter()
1238 .enumerate()
1239 .map(|(i, apk)| {
1240 File::open(PathBuf::from(&apk.path))
1241 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1242 })
1243 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001244 }
Alan Stokesfda70842023-12-20 17:50:14 +00001245 Payload::PayloadConfig(payload_config) => {
1246 vm_payload_config = create_vm_payload_config(payload_config)?;
1247 extra_apk_files =
1248 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1249 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001250 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001251
Inseob Kim89b24592024-02-23 18:59:43 +09001252 let payload_config_os = vm_payload_config.os.name.as_str();
1253 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1254 bail!("'os' in payload config is deprecated");
1255 }
1256
Inseob Kim172f9eb2023-11-06 17:02:08 +09001257 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001258 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001259 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001260 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001261 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001262
1263 // It is safe to construct a filename based on the os_name because we've already checked that it
1264 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001265 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1266 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001267 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001268
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001269 if let Some(custom_config) = &config.customConfig {
1270 if let Some(file) = custom_config.customKernelImage.as_ref() {
1271 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1272 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001273 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001274
1275 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001276 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001277 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001278 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001279
Jaewan Kimf43372b2024-12-13 18:33:58 +09001280 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001281 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001282
1283 for param in custom_config.extraKernelCmdlineParams.iter() {
1284 append_kernel_param(param, &mut vm_config);
1285 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001286
1287 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001288 }
1289
Andrew Walbrancc045902021-07-27 16:06:17 +00001290 if config.memoryMib > 0 {
1291 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001292 }
1293
Chris Wailes6177c662024-05-09 14:37:44 -07001294 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001295 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001296 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001297 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001298 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001299
Shikha Panwar22e70452022-10-10 18:32:55 +00001300 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001301 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001302
1303 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1304 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001305 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001306 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001307 temporary_directory,
1308 apk_file,
1309 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001310 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001311 &vm_payload_config,
1312 &mut vm_config,
1313 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001314
Andrew Walbrancc0db522021-07-12 17:03:42 +00001315 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001316}
1317
Inseob Kime3e932d2024-12-16 20:06:57 +09001318fn check_partition_for_file(fd: &ParcelFileDescriptor, calling_partition: &str) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001319 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1320 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1321
1322 // microdroid vendor image is OK
1323 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1324 {
1325 return Ok(());
1326 }
1327
Inseob Kime3e932d2024-12-16 20:06:57 +09001328 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
1329 let is_caller_vendor = calling_partition == "vendor" || calling_partition == "odm";
1330
1331 if is_fd_vendor != is_caller_vendor {
1332 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001333 }
1334
1335 Ok(())
1336}
1337
Inseob Kime3e932d2024-12-16 20:06:57 +09001338fn check_partitions_for_files(
1339 config: &VirtualMachineRawConfig,
1340 calling_partition: &str,
1341) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001342 config
1343 .disks
1344 .iter()
1345 .flat_map(|disk| disk.partitions.iter())
1346 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001347 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001348
Inseob Kime3e932d2024-12-16 20:06:57 +09001349 config
1350 .disks
1351 .iter()
1352 .filter_map(|disk| disk.image.as_ref())
1353 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1354
1355 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1356 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1357 config
1358 .bootloader
1359 .as_ref()
1360 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001361
1362 Ok(())
1363}
1364
Alan Stokes0d1ef782022-09-27 13:46:35 +01001365fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1366 let mut apk_zip = ZipArchive::new(apk_file)?;
1367 let config_file = apk_zip.by_name(config_path)?;
1368 Ok(serde_json::from_reader(config_file)?)
1369}
1370
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001371fn create_vm_payload_config(
1372 payload_config: &VirtualMachinePayloadConfig,
1373) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001374 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1375 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1376 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001377
1378 let payload_binary_name = &payload_config.payloadBinaryName;
1379 if payload_binary_name.contains('/') {
1380 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1381 }
1382
1383 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001384
1385 // The VM only cares about how many there are, these names are actually ignored.
1386 let extra_apk_count = payload_config.extraApks.len();
1387 let extra_apks =
1388 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1389
Nikita Ioffe901083f2025-01-20 01:54:28 +00001390 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1391 // The only payload delivered via Mainline module in this release requires
1392 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1393 // APIs, so we use the fact that the payload is granted
1394 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1395 // com.android.i18n APEX.
1396 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1397 // Microdroid pVMs.
1398 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1399 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1400 } else {
1401 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1402 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001403}
1404
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001405/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001406fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001407 temporary_directory: &Path,
1408 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001409) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001410 let id = *next_temporary_image_id;
1411 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001412 CompositeImageFilenames {
1413 composite: temporary_directory.join(format!("composite-{}.img", id)),
1414 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1415 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1416 }
1417}
1418
1419/// Filenames for a composite disk image, including header and footer partitions.
1420#[derive(Clone, Debug, Eq, PartialEq)]
1421struct CompositeImageFilenames {
1422 /// The composite disk image itself.
1423 composite: PathBuf,
1424 /// The header partition image.
1425 header: PathBuf,
1426 /// The footer partition image.
1427 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001428}
1429
Jiyong Park753553b2021-07-12 21:21:09 +09001430/// Checks whether the caller has a specific permission
1431fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001432 if cfg!(early) {
1433 // Skip permission check for early VMs, in favor of SELinux
1434 return Ok(());
1435 }
David Brazdil1f530702022-10-03 12:18:10 +01001436 let calling_pid = get_calling_pid();
1437 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001438 // Root can do anything
1439 if calling_uid == 0 {
1440 return Ok(());
1441 }
1442 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001443 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001444 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001445 Ok(())
1446 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001447 Err(anyhow!("does not have the {} permission", perm))
1448 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001449 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001450}
1451
Jiyong Park753553b2021-07-12 21:21:09 +09001452/// Check whether the caller of the current Binder method is allowed to manage VMs
1453fn check_manage_access() -> binder::Result<()> {
1454 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1455}
1456
Inseob Kim1119d702022-05-02 18:01:58 +09001457/// Check whether the caller of the current Binder method is allowed to create custom VMs
1458fn check_use_custom_virtual_machine() -> binder::Result<()> {
1459 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1460}
1461
Nikita Ioffe901083f2025-01-20 01:54:28 +00001462/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1463/// rollback protection schema.
1464fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1465 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1466}
1467
Alan Stokes185fe112023-01-10 16:20:55 +00001468/// Return whether a partition is exempt from selinux label checks, because we know that it does
1469/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001470fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001471 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001472 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001473 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001474 || label == "microdroid-apk-idsig"
1475 || label == "payload-metadata"
1476 || label.starts_with("extra-idsig-")
1477}
1478
Alice Wangc206b9b2023-08-28 14:13:51 +00001479/// Returns whether a partition with the given label is safe for a raw config VM.
1480fn is_safe_raw_partition(label: &str) -> bool {
1481 label == "vm-instance"
1482}
1483
Alan Stokes185fe112023-01-10 16:20:55 +00001484/// Check that a file SELinux label is acceptable.
1485///
1486/// 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 +09001487/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001488///
1489/// Note that sepolicy must also grant read access for these types to both virtualization
1490/// service and crosvm.
1491///
1492/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1493/// user devices (W^X).
1494fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1495 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001496 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001497 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001498 | "staging_data_file" // updated/staged APEX images
1499 | "system_file" // immutable dm-verity protected partition
1500 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001501 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001502 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001503 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001504 }
1505}
1506
Alan Stokes185fe112023-01-10 16:20:55 +00001507fn check_label_for_partition(partition: &Partition) -> Result<()> {
1508 let file = partition.image.as_ref().unwrap().as_ref();
1509 check_label_is_allowed(&getfilecon(file)?)
1510 .with_context(|| format!("Partition {} invalid", &partition.label))
1511}
1512
1513fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1514 if let Some(f) = kernel {
1515 check_label_for_file(f, "kernel")?;
1516 }
1517 if let Some(f) = initrd {
1518 check_label_for_file(f, "initrd")?;
1519 }
1520 Ok(())
1521}
1522fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1523 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1524}
1525
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001526/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1527#[derive(Debug)]
1528struct VirtualMachine {
1529 instance: Arc<VmInstance>,
1530}
1531
1532impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001533 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001534 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001535 }
1536}
1537
1538impl Interface for VirtualMachine {}
1539
Devin Moore407df8f2024-08-27 19:39:16 +00001540impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001541 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001542 // Don't check permission. The owner of the VM might have passed this binder object to
1543 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001544 Ok(self.instance.cid as i32)
1545 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001546
Andrew Walbran6b650662021-09-07 13:13:23 +00001547 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001548 // Don't check permission. The owner of the VM might have passed this binder object to
1549 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001550 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001551 }
1552
1553 fn registerCallback(
1554 &self,
1555 callback: &Strong<dyn IVirtualMachineCallback>,
1556 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001557 // Don't check permission. The owner of the VM might have passed this binder object to
1558 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001559
1560 // Only register callback if it may be notified.
1561 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1562 let vm_state = self.instance.vm_state.lock().unwrap();
1563 if matches!(*vm_state, VmState::Dead) {
1564 warn!("Ignoring registerCallback() after VM is died");
1565 } else {
1566 self.instance.callbacks.add(callback.clone());
1567 }
1568 drop(vm_state);
1569
Andrew Walbrandae07162021-03-12 17:05:20 +00001570 Ok(())
1571 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001572
Andrew Walbranf8d94112021-09-07 11:45:36 +00001573 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001574 self.instance
1575 .start()
1576 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1577 .with_log()
1578 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001579 }
1580
Inseob Kima446f802022-07-11 19:46:37 +09001581 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001582 self.instance
1583 .kill()
1584 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1585 .with_log()
1586 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001587 }
1588
Keir Fraser48221ba2024-07-12 14:05:02 +00001589 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1590 let balloon = self
1591 .instance
1592 .get_memory_balloon()
1593 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1594 .with_log()
1595 .or_service_specific_exception(-1)?;
1596 Ok(balloon.try_into().unwrap())
1597 }
1598
1599 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001600 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001601 .set_memory_balloon(num_bytes.try_into().unwrap())
1602 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001603 .with_log()
1604 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001605 }
1606
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001607 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001608 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001609 return Err(Status::new_service_specific_error_str(
1610 IVirtualMachine::ERROR_UNEXPECTED,
1611 Some("Virtual Machine is not running"),
1612 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001613 }
Alan Stokes10c47672022-12-13 17:17:08 +00001614 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001615 if port < VSOCK_PRIV_PORT_MAX {
1616 return Err(Status::new_service_specific_error_str(
1617 IVirtualMachine::ERROR_UNEXPECTED,
1618 Some("Can't connect to privileged port {port}"),
1619 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001620 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001621 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1622 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001623 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001624 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001625 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001626
Devin Moore407df8f2024-08-27 19:39:16 +00001627 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1628 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1629 return Err(Status::new_service_specific_error_str(
1630 IVirtualMachine::ERROR_UNEXPECTED,
1631 Some("Virtual Machine is not running"),
1632 ));
1633 }
1634 let port = port as u32;
1635 if port < VSOCK_PRIV_PORT_MAX {
1636 return Err(Status::new_service_specific_error_str(
1637 IVirtualMachine::ERROR_UNEXPECTED,
1638 Some("Can't connect to privileged port {port}"),
1639 ));
1640 }
1641 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001642 let addr = sockaddr_vm {
1643 svm_family: AF_VSOCK as sa_family_t,
1644 svm_reserved1: 0,
1645 svm_port: port,
1646 svm_cid: cid,
1647 svm_zero: [0u8; 4],
1648 };
1649 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001650 let accessor = Accessor::new(name, get_connection_info);
1651 accessor
1652 .as_binder()
1653 .context("The newly created Accessor should always have a binder")
1654 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1655 }
1656
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001657 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1658 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1659 }
Jiyong Park23b67392024-07-04 13:51:42 +09001660
1661 fn suspend(&self) -> binder::Result<()> {
1662 self.instance
1663 .suspend()
1664 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1665 .with_log()
1666 .or_service_specific_exception(-1)
1667 }
1668
1669 fn resume(&self) -> binder::Result<()> {
1670 self.instance
1671 .resume()
1672 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1673 .with_log()
1674 .or_service_specific_exception(-1)
1675 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001676}
1677
1678impl Drop for VirtualMachine {
1679 fn drop(&mut self) {
1680 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001681 if let Err(e) = self.instance.kill() {
1682 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1683 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001684 }
1685}
1686
1687/// A set of Binders to be called back in response to various events on the VM, such as when it
1688/// dies.
1689#[derive(Debug, Default)]
1690pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1691
1692impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001693 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001694 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001695 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001696 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001697 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001698 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001699 }
1700 }
1701 }
1702
Inseob Kim14cb8692021-08-31 21:50:39 +09001703 /// Call all registered callbacks to notify that the payload is ready to serve.
1704 pub fn notify_payload_ready(&self, cid: Cid) {
1705 let callbacks = &*self.0.lock().unwrap();
1706 for callback in callbacks {
1707 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001708 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001709 }
1710 }
1711 }
1712
Inseob Kim2444af92021-08-31 01:22:50 +09001713 /// Call all registered callbacks to notify that the payload has finished.
1714 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1715 let callbacks = &*self.0.lock().unwrap();
1716 for callback in callbacks {
1717 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001718 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001719 }
1720 }
1721 }
1722
Jooyung Handd0a1732021-11-23 15:26:20 +09001723 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001724 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001725 let callbacks = &*self.0.lock().unwrap();
1726 for callback in callbacks {
1727 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001728 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001729 }
1730 }
1731 }
1732
Andrew Walbrandae07162021-03-12 17:05:20 +00001733 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001734 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001735 let mut callbacks = self.0.lock().unwrap();
1736 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001737 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001738 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001739 }
1740 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001741
1742 // Nothing to notify afterward because VM cannot be restarted.
1743 // Explicitly clear callbacks to prevent potential cyclic references
1744 // between callback and VmInstance.
1745 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001746 }
1747
1748 /// Add a new callback to the set.
1749 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1750 self.0.lock().unwrap().push(callback);
1751 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001752}
1753
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001754/// The mutable state of the VirtualizationService. There should only be one instance of this
1755/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001756#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001757struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001758 /// The VMs which have been started. When VMs are started a weak reference is added to this
1759 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1760 /// the Binder client are dropped the weak reference here will become invalid, and will be
1761 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001762 vms: Vec<Weak<VmInstance>>,
1763}
1764
1765impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001766 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001767 fn vms(&self) -> Vec<Arc<VmInstance>> {
1768 // Attempt to upgrade the weak pointers to strong pointers.
1769 self.vms.iter().filter_map(Weak::upgrade).collect()
1770 }
1771
1772 /// Add a new VM to the list.
1773 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1774 // Garbage collect any entries from the stored list which no longer exist.
1775 self.vms.retain(|vm| vm.strong_count() > 0);
1776
1777 // Actually add the new VM.
1778 self.vms.push(vm);
1779 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001780
Jiyong Park8611a6c2021-07-09 18:17:44 +09001781 /// Get a VM that corresponds to the given cid
1782 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1783 self.vms().into_iter().find(|vm| vm.cid == cid)
1784 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001785}
1786
Andrew Walbran6b650662021-09-07 13:13:23 +00001787/// Gets the `VirtualMachineState` of the given `VmInstance`.
1788fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001789 match &*instance.vm_state.lock().unwrap() {
1790 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1791 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001792 PayloadState::Starting => VirtualMachineState::STARTING,
1793 PayloadState::Started => VirtualMachineState::STARTED,
1794 PayloadState::Ready => VirtualMachineState::READY,
1795 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001796 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001797 },
1798 VmState::Dead => VirtualMachineState::DEAD,
1799 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001800 }
1801}
1802
David Brazdilf50c7a62023-04-19 14:22:42 +00001803/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001804pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1805 file.as_ref()
1806 .try_clone()
1807 .context("Failed to clone File from ParcelFileDescriptor")
1808 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001809 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001810}
1811
Andrew Walbrand3a84182021-09-07 14:48:52 +00001812/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001813fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001814 file.as_ref().map(clone_file).transpose()
1815}
1816
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001817/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001818fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1819 // SAFETY: ownership is transferred from stream to f
1820 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1821 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001822}
1823
Jiyong Parkdcf17412022-02-08 15:07:23 +09001824/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001825fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1826 VersionReq::parse(s)
1827 .with_context(|| format!("Invalid platform version requirement {}", s))
1828 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001829}
1830
Jiyong Parked180932023-02-24 19:55:41 +09001831/// Create the empty ramdump file
1832fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1833 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1834 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1835 // owner) for readout.
1836 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001837 let ramdump = File::create(ramdump_path)
1838 .context("Failed to prepare ramdump file")
1839 .with_log()
1840 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001841 Ok(ramdump)
1842}
1843
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001844/// Create the empty device tree dump file
1845fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1846 let path = temporary_directory.join("device_tree.dtb");
1847 let file = File::create(path)
1848 .context("Failed to prepare device tree dump file")
1849 .with_log()
1850 .or_service_specific_exception(-1)?;
1851 Ok(file)
1852}
1853
Nikita Ioffe5776f082023-02-10 21:38:26 +00001854fn is_protected(config: &VirtualMachineConfig) -> bool {
1855 match config {
1856 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1857 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1858 }
1859}
1860
1861fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1862 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001863 return Err(anyhow!("Can't use gdb with protected VMs"))
1864 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001865 }
1866
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001867 if get_debug_level(config) == Some(DebugLevel::NONE) {
1868 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1869 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001870 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001871
1872 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001873}
1874
Shikha Panwar61a74b52024-02-16 13:17:01 +00001875fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1876 match config {
1877 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1878 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1879 }
1880}
1881
Alan Stokesc96b35e2024-05-03 13:21:20 +01001882fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1883 match config {
1884 VirtualMachineConfig::RawConfig(_) => true,
1885 VirtualMachineConfig::AppConfig(config) => {
1886 let Some(custom) = &config.customConfig else { return true };
1887 custom.wantUpdatable
1888 }
1889 }
1890}
1891
Nikita Ioffe5776f082023-02-10 21:38:26 +00001892fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1893 match config {
1894 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001895 VirtualMachineConfig::AppConfig(config) => {
1896 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1897 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001898 }
1899}
1900
Nikita Ioffe631717e2023-09-05 13:38:07 +01001901fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1902 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1903 if let Some(custom_config) = &config.customConfig {
1904 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1905 return Err(anyhow!("vendor modules feature is disabled"))
1906 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1907 }
1908 }
1909 Ok(())
1910}
1911
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001912fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1913 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1914 if let Some(custom_config) = &config.customConfig {
1915 if !custom_config.devices.is_empty() {
1916 return Err(anyhow!("device assignment feature is disabled"))
1917 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1918 }
1919 }
1920 Ok(())
1921}
1922
Alan Stokesfda70842023-12-20 17:50:14 +00001923fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1924 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1925 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1926 if !payload_config.extraApks.is_empty() {
1927 return Err(anyhow!("multi-tenant feature is disabled"))
1928 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1929 }
1930 Ok(())
1931}
1932
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001933fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1934 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1935 if let Some(custom_config) = &config.customConfig {
1936 if !custom_config.extraKernelCmdlineParams.is_empty() {
1937 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1938 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1939 }
1940 }
1941 Ok(())
1942}
1943
Nikita Ioffe99548382024-10-21 15:54:46 +00001944fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1945 match config {
1946 VirtualMachineConfig::RawConfig(config) => {
1947 if !config.teeServices.is_empty() {
1948 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1949 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1950 }
1951 }
1952 VirtualMachineConfig::AppConfig(config) => {
1953 if let Some(custom_config) = &config.customConfig {
1954 if !custom_config.teeServices.is_empty() {
1955 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1956 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1957 }
1958 }
1959 }
1960 };
1961 Ok(())
1962}
1963
Nikita Ioffef934e812024-07-05 15:44:41 +00001964fn check_protected_vm_is_supported() -> binder::Result<()> {
1965 let is_pvm_supported =
1966 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1967 if is_pvm_supported {
1968 Ok(())
1969 } else {
1970 Err(anyhow!("pVM is not supported"))
1971 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1972 }
1973}
1974
Nikita Ioffe631717e2023-09-05 13:38:07 +01001975fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1976 if !cfg!(vendor_modules) {
1977 check_no_vendor_modules(config)?;
1978 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001979 if !cfg!(device_assignment) {
1980 check_no_devices(config)?;
1981 }
Alan Stokesfda70842023-12-20 17:50:14 +00001982 if !cfg!(multi_tenant) {
1983 check_no_extra_apks(config)?;
1984 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001985 if !cfg!(debuggable_vms_improvements) {
1986 check_no_extra_kernel_cmdline_params(config)?;
1987 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001988 if !cfg!(tee_services_allowlist) {
1989 check_no_tee_services(config)?;
1990 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001991 Ok(())
1992}
1993
Inseob Kimecde8c02024-09-03 13:11:08 +09001994fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1995 check_no_vendor_modules(config)?;
1996 check_no_devices(config)?;
1997
1998 Ok(())
1999}
2000
Inseob Kim0168b462022-12-27 14:54:35 +09002001fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002002 fd: Option<&ParcelFileDescriptor>,
2003 tag: String,
2004) -> Result<Option<File>, Status> {
2005 if let Some(fd) = fd {
2006 return Ok(Some(clone_file(fd)?));
2007 }
2008
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002009 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002010 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002011
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002012 let mut reader = BufReader::new(File::from(read_fd));
2013 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002014
Frederick Mayle26e41af2025-02-05 18:30:29 -08002015 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002016 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002017 buf.clear();
2018 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002019 match reader.read_until(b'\n', &mut buf) {
2020 Ok(0) => {
2021 // EOF
2022 return;
2023 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002024 Ok(_size) => {
2025 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002026 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002027 // Logs sent via TTY usually end lines with "\r\n".
2028 if buf.last() == Some(&b'\r') {
2029 buf.pop();
2030 }
Inseob Kim0168b462022-12-27 14:54:35 +09002031 }
2032 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2033 }
2034 Err(e) => {
2035 error!("Could not read console pipe: {:?}", e);
2036 return;
2037 }
2038 };
2039 });
2040
2041 Ok(Some(write_fd))
2042}
2043
Jooyung Han35edb8f2021-07-01 16:17:16 +09002044/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2045/// it doesn't require that T implements Clone.
2046enum BorrowedOrOwned<'a, T> {
2047 Borrowed(&'a T),
2048 Owned(T),
2049}
2050
Chris Wailes73a1eb72025-01-15 11:56:43 -08002051impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002052 fn as_ref(&self) -> &T {
2053 match self {
2054 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002055 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002056 }
2057 }
2058}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002059
2060/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2061#[derive(Debug, Default)]
2062struct VirtualMachineService {
2063 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002064 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002065}
2066
2067impl Interface for VirtualMachineService {}
2068
2069impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002070 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2071 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002072 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002073 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002074 vm.update_payload_state(PayloadState::Started)
2075 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002076 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002077
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002078 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2079 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002080 Ok(())
2081 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002082 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002083 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002084 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002085 }
Inseob Kim2444af92021-08-31 01:22:50 +09002086
Inseob Kimc7d28c72021-10-25 14:28:10 +00002087 fn notifyPayloadReady(&self) -> binder::Result<()> {
2088 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002089 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002090 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002091 vm.update_payload_state(PayloadState::Ready)
2092 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002093 vm.callbacks.notify_payload_ready(cid);
2094 Ok(())
2095 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002096 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002097 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002098 }
2099 }
2100
Inseob Kimc7d28c72021-10-25 14:28:10 +00002101 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2102 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002103 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002104 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002105 vm.update_payload_state(PayloadState::Finished)
2106 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002107 vm.callbacks.notify_payload_finished(cid, exit_code);
2108 Ok(())
2109 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002110 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002111 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002112 }
2113 }
2114
Alan Stokes2bead0d2022-09-05 16:58:34 +01002115 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002116 let cid = self.cid;
2117 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002118 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002119 vm.update_payload_state(PayloadState::Finished)
2120 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002121 vm.callbacks.notify_error(cid, error_code, message);
2122 Ok(())
2123 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002124 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002125 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002126 }
2127 }
Alice Wangc2fec932023-02-23 16:24:02 +00002128
Shikha Panware45e9422024-02-28 21:18:10 +00002129 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2130 if !is_secretkeeper_supported() {
2131 return Err(StatusCode::NAME_NOT_FOUND)?;
2132 }
2133 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2134 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002135 }
2136
Alice Wange64dd182024-01-17 15:57:55 +00002137 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2138 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002139 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002140}
2141
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002142fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002143 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2144 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002145}
2146
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002147impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002148 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002149 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002150 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002151 BinderFeatures::default(),
2152 )
2153 }
2154}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002155
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002156struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2157
2158impl Interface for SecretkeeperProxy {}
2159
2160impl ISecretkeeper for SecretkeeperProxy {
2161 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2162 // Pass the request to the channel, and read the response.
2163 self.0.processSecretManagementRequest(req)
2164 }
2165
2166 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2167 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2168 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2169 }
2170
2171 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2172 self.0.deleteIds(ids)
2173 }
2174
2175 fn deleteAll(&self) -> binder::Result<()> {
2176 self.0.deleteAll()
2177 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002178
2179 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2180 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2181 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2182 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2183 // use this API from the proxy.
2184 Err(ExceptionCode::SECURITY.into())
2185 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002186}
2187
2188struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2189
2190impl Interface for AuthGraphKeyExchangeProxy {}
2191
2192impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2193 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2194 self.0.create()
2195 }
2196
2197 fn init(
2198 &self,
2199 peer_pub_key: &PubKey,
2200 peer_id: &Identity,
2201 peer_nonce: &[u8],
2202 peer_version: i32,
2203 ) -> binder::Result<KeInitResult> {
2204 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2205 }
2206
2207 fn finish(
2208 &self,
2209 peer_pub_key: &PubKey,
2210 peer_id: &Identity,
2211 peer_signature: &SessionIdSignature,
2212 peer_nonce: &[u8],
2213 peer_version: i32,
2214 own_key: &Key,
2215 ) -> binder::Result<SessionInfo> {
2216 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2217 }
2218
2219 fn authenticationComplete(
2220 &self,
2221 peer_signature: &SessionIdSignature,
2222 shared_keys: &[AuthgraphArc; 2],
2223 ) -> binder::Result<[AuthgraphArc; 2]> {
2224 self.0.authenticationComplete(peer_signature, shared_keys)
2225 }
2226}
2227
Inseob Kimecde8c02024-09-03 13:11:08 +09002228// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002229#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002230struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002231 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002232 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002233 path: String,
2234}
2235
2236#[derive(Debug, Default, Deserialize)]
2237struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002238 early_vm: Vec<EarlyVm>,
2239}
2240
Inseob Kim7e1877b2024-11-07 17:28:56 +09002241static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2242 LazyLock::new(|| Mutex::new(HashMap::new()));
2243
Inseob Kimecde8c02024-09-03 13:11:08 +09002244fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2245 match partition {
2246 "system" => Ok(100..200),
2247 "system_ext" | "product" => Ok(200..300),
Inseob Kime3e932d2024-12-16 20:06:57 +09002248 "vendor" | "odm" => Ok(300..400),
Inseob Kimecde8c02024-09-03 13:11:08 +09002249 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2250 }
2251}
2252
Inseob Kim7e1877b2024-11-07 17:28:56 +09002253fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002254 if !xml_path.exists() {
2255 bail!("{} doesn't exist", xml_path.display());
2256 }
2257
2258 let xml =
2259 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2260 let xml = String::from_utf8(xml)
2261 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2262 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2263 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2264
Inseob Kim7e1877b2024-11-07 17:28:56 +09002265 Ok(early_vms.early_vm)
2266}
Inseob Kimecde8c02024-09-03 13:11:08 +09002267
Inseob Kim7e1877b2024-11-07 17:28:56 +09002268fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2269 for early_vm in early_vms {
2270 let cid = early_vm
2271 .cid
2272 .try_into()
2273 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2274
2275 ensure!(
2276 cid_range.contains(&cid),
2277 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2278 early_vm.name
2279 );
2280 }
2281 Ok(())
2282}
2283
2284fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2285 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2286
2287 if let Some(result) = cache.get(partition) {
2288 return Ok(result.clone());
2289 }
2290
2291 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2292 let mut early_vms = Vec::new();
2293 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2294 match entry {
2295 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2296 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2297 }
2298 }
2299
2300 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2301 .with_context(|| format!("CID validation for {partition} failed"))?;
2302
2303 cache.insert(partition.to_owned(), early_vms.clone());
2304
2305 Ok(early_vms)
2306}
2307
2308fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2309 let mut found_vm: Option<&EarlyVm> = None;
2310
2311 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002312 if early_vm.name != name {
2313 continue;
2314 }
2315
Inseob Kimecde8c02024-09-03 13:11:08 +09002316 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002317 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002318 }
2319
2320 found_vm = Some(early_vm);
2321 }
2322
Inseob Kim7e1877b2024-11-07 17:28:56 +09002323 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002324}
2325
2326fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002327 let early_vms = get_early_vms_in_partition(partition)
2328 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2329
2330 Ok(find_early_vm(&early_vms, name)
2331 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2332 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002333}
2334
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002335#[cfg(test)]
2336mod tests {
2337 use super::*;
2338
2339 #[test]
2340 fn test_is_allowed_label_for_partition() -> Result<()> {
2341 let expected_results = vec![
2342 ("u:object_r:system_file:s0", true),
2343 ("u:object_r:apk_data_file:s0", true),
2344 ("u:object_r:app_data_file:s0", false),
2345 ("u:object_r:app_data_file:s0:c512,c768", false),
2346 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2347 ("invalid", false),
2348 ("user:role:apk_data_file:severity:categories", true),
2349 ("user:role:apk_data_file:severity:categories:extraneous", false),
2350 ];
2351
2352 for (label, expected_valid) in expected_results {
2353 let context = SeContext::new(label)?;
2354 let result = check_label_is_allowed(&context);
2355 if expected_valid {
2356 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2357 } else if result.is_ok() {
2358 bail!("Expected label {} to be disallowed", label);
2359 }
2360 }
2361 Ok(())
2362 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002363
2364 #[test]
2365 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2366 let apk = tempfile::tempfile().unwrap();
2367 let idsig = tempfile::tempfile().unwrap();
2368
2369 let ret = create_or_update_idsig_file(
2370 &ParcelFileDescriptor::new(apk),
2371 &ParcelFileDescriptor::new(idsig),
2372 );
2373 assert!(ret.is_err(), "should fail");
2374 Ok(())
2375 }
2376
2377 #[test]
2378 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2379 let tmp_dir = tempfile::TempDir::new().unwrap();
2380 let apk = File::open(tmp_dir.path()).unwrap();
2381 let idsig = tempfile::tempfile().unwrap();
2382
2383 let ret = create_or_update_idsig_file(
2384 &ParcelFileDescriptor::new(apk),
2385 &ParcelFileDescriptor::new(idsig),
2386 );
2387 assert!(ret.is_err(), "should fail");
2388 Ok(())
2389 }
2390
2391 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2392 /// on ext4 filesystem is passed.
2393 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2394 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2395 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2396 #[test]
2397 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2398 // APEXes are backed by the ext4.
2399 let apk = File::open("/apex/com.android.virt/").unwrap();
2400 let idsig = tempfile::tempfile().unwrap();
2401
2402 let ret = create_or_update_idsig_file(
2403 &ParcelFileDescriptor::new(apk),
2404 &ParcelFileDescriptor::new(idsig),
2405 );
2406 assert!(ret.is_err(), "should fail");
2407 Ok(())
2408 }
Jiyong Park8d192952023-06-26 14:29:51 +09002409
2410 #[test]
2411 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2412 use std::io::Seek;
2413
2414 // Pick any APK
2415 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2416 let mut idsig = tempfile::tempfile().unwrap();
2417
2418 create_or_update_idsig_file(
2419 &ParcelFileDescriptor::new(apk.try_clone()?),
2420 &ParcelFileDescriptor::new(idsig.try_clone()?),
2421 )?;
2422 let modified_orig = idsig.metadata()?.modified()?;
2423 apk.rewind()?;
2424 idsig.rewind()?;
2425
2426 // Call the function again
2427 create_or_update_idsig_file(
2428 &ParcelFileDescriptor::new(apk.try_clone()?),
2429 &ParcelFileDescriptor::new(idsig.try_clone()?),
2430 )?;
2431 let modified_new = idsig.metadata()?.modified()?;
2432 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2433 Ok(())
2434 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002435
2436 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002437 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2438 use std::io::Read;
2439
2440 // Pick any APK
2441 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2442 let idsig_empty = tempfile::tempfile().unwrap();
2443 let mut idsig_invalid = tempfile::tempfile().unwrap();
2444 idsig_invalid.write_all(b"Oops")?;
2445
2446 // Create new idsig
2447 create_or_update_idsig_file(
2448 &ParcelFileDescriptor::new(apk.try_clone()?),
2449 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2450 )?;
2451 apk.rewind()?;
2452
2453 // Update idsig_invalid
2454 create_or_update_idsig_file(
2455 &ParcelFileDescriptor::new(apk.try_clone()?),
2456 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2457 )?;
2458
2459 // Ensure the 2 idsig files have same size!
2460 assert!(
2461 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2462 "idsig files differ in size"
2463 );
2464 // Ensure the 2 idsig files have same content!
2465 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2466 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2467 }
2468 Ok(())
2469 }
2470 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002471 fn test_append_kernel_param_first_param() {
2472 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2473 append_kernel_param("foo=1", &mut vm_config);
2474 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2475 }
2476
2477 #[test]
2478 fn test_append_kernel_param() {
2479 let mut vm_config =
2480 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2481 append_kernel_param("bar=42", &mut vm_config);
2482 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2483 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002484
Inseob Kim46257382024-01-03 15:41:22 +09002485 fn test_extract_os_name_from_config_path(
2486 path: &Path,
2487 expected_result: Option<&str>,
2488 ) -> Result<()> {
2489 let result = extract_os_name_from_config_path(path);
2490 if result.as_deref() != expected_result {
2491 bail!("Expected {:?} but was {:?}", expected_result, &result)
2492 }
2493 Ok(())
2494 }
2495
2496 #[test]
2497 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2498 test_extract_os_name_from_config_path(
2499 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2500 Some("microdroid"),
2501 )
2502 }
2503
2504 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002505 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2506 test_extract_os_name_from_config_path(
2507 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2508 Some("microdroid_16k"),
2509 )
2510 }
2511
2512 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002513 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2514 test_extract_os_name_from_config_path(
2515 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2516 Some("microdroid_gki-android14-6.1"),
2517 )
2518 }
2519
2520 #[test]
2521 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2522 test_extract_os_name_from_config_path(
2523 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2524 None,
2525 )
2526 }
2527
2528 #[test]
2529 fn test_extract_os_name_from_configs() -> Result<()> {
2530 let tmp_dir = tempfile::TempDir::new()?;
2531 let tmp_dir_path = tmp_dir.path().to_owned();
2532
2533 let mut os_names: HashSet<String> = HashSet::new();
2534 os_names.insert("microdroid".to_owned());
2535 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2536 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2537
2538 // config files
2539 for os_name in &os_names {
2540 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2541 }
2542
2543 // fake files not related to configs
2544 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2545 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2546
2547 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2548 Some(s) => s.to_owned(),
2549 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2550 };
2551
2552 let result = extract_os_names_from_configs(&glob_pattern)?;
2553 if result != os_names {
2554 bail!("Expected {:?} but was {:?}", os_names, result);
2555 }
2556 Ok(())
2557 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002558
2559 #[test]
2560 fn test_find_early_vms_from_xml() -> Result<()> {
2561 let tmp_dir = tempfile::TempDir::new()?;
2562 let tmp_dir_path = tmp_dir.path().to_owned();
2563 let xml_path = tmp_dir_path.join("early_vms.xml");
2564
2565 std::fs::write(
2566 &xml_path,
2567 br#"<?xml version="1.0" encoding="utf-8"?>
2568 <early_vms>
2569 <early_vm>
2570 <name>vm_demo_native_early</name>
2571 <cid>123</cid>
2572 <path>/system/bin/vm_demo_native_early</path>
2573 </early_vm>
2574 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002575 <name>vm_demo_native_early_2</name>
2576 <cid>456</cid>
2577 <path>/system/bin/vm_demo_native_early_2</path>
2578 </early_vm>
2579 </early_vms>
2580 "#,
2581 )?;
2582
2583 let cid_range = 100..1000;
2584
2585 let early_vms = get_early_vms_in_path(&xml_path)?;
2586 validate_cid_range(&early_vms, &cid_range)?;
2587
2588 let test_cases = [
2589 (
2590 "vm_demo_native_early",
2591 EarlyVm {
2592 name: "vm_demo_native_early".to_owned(),
2593 cid: 123,
2594 path: "/system/bin/vm_demo_native_early".to_owned(),
2595 },
2596 ),
2597 (
2598 "vm_demo_native_early_2",
2599 EarlyVm {
2600 name: "vm_demo_native_early_2".to_owned(),
2601 cid: 456,
2602 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2603 },
2604 ),
2605 ];
2606
2607 for (name, expected) in test_cases {
2608 let result = find_early_vm(&early_vms, name)?;
2609 assert_eq!(result, &expected);
2610 }
2611
2612 Ok(())
2613 }
2614
2615 #[test]
2616 fn test_invalid_cid_validation() -> Result<()> {
2617 let tmp_dir = tempfile::TempDir::new()?;
2618 let xml_path = tmp_dir.path().join("early_vms.xml");
2619
2620 let cid_range = 100..1000;
2621
2622 for cid in [-1, 999999] {
2623 std::fs::write(
2624 &xml_path,
2625 format!(
2626 r#"<?xml version="1.0" encoding="utf-8"?>
2627 <early_vms>
2628 <early_vm>
2629 <name>vm_demo_invalid_cid</name>
2630 <cid>{cid}</cid>
2631 <path>/system/bin/vm_demo_invalid_cid</path>
2632 </early_vm>
2633 </early_vms>
2634 "#
2635 ),
2636 )?;
2637
2638 let early_vms = get_early_vms_in_path(&xml_path)?;
2639 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2640 }
2641
2642 Ok(())
2643 }
2644
2645 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002646 fn test_symlink_to_system_ext_supported() -> Result<()> {
2647 let link_path = Path::new("/system/system_ext/file");
2648 let partition = find_partition(Some(link_path)).unwrap();
2649 assert_eq!("system_ext", partition);
2650 Ok(())
2651 }
2652
2653 #[test]
2654 fn test_symlink_to_product_supported() -> Result<()> {
2655 let link_path = Path::new("/system/product/file");
2656 let partition = find_partition(Some(link_path)).unwrap();
2657 assert_eq!("product", partition);
2658 Ok(())
2659 }
2660
2661 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002662 fn test_duplicated_early_vms() -> Result<()> {
2663 let tmp_dir = tempfile::TempDir::new()?;
2664 let tmp_dir_path = tmp_dir.path().to_owned();
2665 let xml_path = tmp_dir_path.join("early_vms.xml");
2666
2667 std::fs::write(
2668 &xml_path,
2669 br#"<?xml version="1.0" encoding="utf-8"?>
2670 <early_vms>
2671 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002672 <name>vm_demo_duplicated_name</name>
2673 <cid>456</cid>
2674 <path>/system/bin/vm_demo_duplicated_name_1</path>
2675 </early_vm>
2676 <early_vm>
2677 <name>vm_demo_duplicated_name</name>
2678 <cid>789</cid>
2679 <path>/system/bin/vm_demo_duplicated_name_2</path>
2680 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002681 </early_vms>
2682 "#,
2683 )?;
2684
2685 let cid_range = 100..1000;
2686
Inseob Kim7e1877b2024-11-07 17:28:56 +09002687 let early_vms = get_early_vms_in_path(&xml_path)?;
2688 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002689
Inseob Kim7e1877b2024-11-07 17:28:56 +09002690 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002691
2692 Ok(())
2693 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002694}