blob: 0f81f3d33f1203a84a332e9d06bd5131214de3e8 [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 Kim61f86142023-03-28 15:12:52 +090021use crate::debug_config::DebugConfig;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{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::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
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};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000070use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090071use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000072use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000073use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090074use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090075use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000076use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000077use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090078use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090079use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090080use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000081use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000082use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090083use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090084use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090086use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000087use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090088use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090089use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000090use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010092use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090093use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010094use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000095use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090096use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097
David Brazdil41d1a872022-10-05 14:44:19 +010098/// The unique ID of a VM used (together with a port number) for vsock communication.
99pub type Cid = u32;
100
David Brazdil4b4c5102022-12-19 22:56:20 +0000101pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
102
Devin Moore407df8f2024-08-27 19:39:16 +0000103/// Vsock privileged ports are below this number.
104const VSOCK_PRIV_PORT_MAX: u32 = 1024;
105
Jooyung Han95884632021-07-06 22:27:54 +0900106/// The size of zero.img.
107/// Gaps in composite disk images are filled with a shared zero.img.
108const ZERO_FILLER_SIZE: u64 = 4096;
109
David Brazdilf50c7a62023-04-19 14:22:42 +0000110/// Magic string for the instance image
111const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
112
113/// Version of the instance image format
114const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
115
Alan Stokes0d1ef782022-09-27 13:46:35 +0100116const MICRODROID_OS_NAME: &str = "microdroid";
117
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000118const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000119 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000120
David Brazdilf50c7a62023-04-19 14:22:42 +0000121const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
122
123/// crosvm requires all partitions to be a multiple of 4KiB.
124const PARTITION_GRANULARITY_BYTES: u64 = 4096;
125
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000126const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
127
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100128pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
129 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900130 if cfg!(early) {
131 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
132 } else {
133 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
134 .expect("Could not connect to VirtualizationServiceInternal")
135 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100136 });
137static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
138 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000139
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000140fn create_or_update_idsig_file(
141 input_fd: &ParcelFileDescriptor,
142 idsig_fd: &ParcelFileDescriptor,
143) -> Result<()> {
144 let mut input = clone_file(input_fd)?;
145 let metadata = input.metadata().context("failed to get input metadata")?;
146 if !metadata.is_file() {
147 bail!("input is not a regular file");
148 }
Alan Stokes25f69362023-03-06 16:51:54 +0000149 let mut sig =
150 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
151 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000152
153 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900154
155 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
156 // if the idsig file already has the same APK digest.
157 if output.metadata()?.len() > 0 {
158 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
159 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
160 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
161 return Ok(());
162 }
163 }
164 // if we fail to read v4signature from output, that's fine. User can pass a random file.
165 // We will anyway overwrite the file to the v4signature generated from input_fd.
166 }
167
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000168 output
169 .seek(SeekFrom::Start(0))
170 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000171 output.set_len(0).context("failed to set_len on the idsig output")?;
172 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000173 Ok(())
174}
175
Alan Stokes25f69362023-03-06 16:51:54 +0000176fn get_current_sdk() -> Result<u32> {
177 let current_sdk = system_properties::read("ro.build.version.sdk")?;
178 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
179 current_sdk.parse().context("Malformed SDK version")
180}
181
David Brazdil4b4c5102022-12-19 22:56:20 +0000182pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
183 for dir_entry in read_dir(path)? {
184 remove_file(dir_entry?.path())?;
185 }
186 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100187}
188
David Brazdil528e0472022-10-10 15:06:02 +0100189/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000190#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000191pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900192 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000193}
194
Shikha Panward8e35422021-10-11 13:51:27 +0000195impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000197 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
198 let state = &mut *self.state.lock().unwrap();
199 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000201 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
203 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
208 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000209 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000211 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000212 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000213 .or(Err(StatusCode::UNKNOWN_ERROR))?;
214 }
215 Ok(())
216 }
217}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000218impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
220 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221 ///
222 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000224 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000225 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900226 console_out_fd: Option<&ParcelFileDescriptor>,
227 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000228 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000229 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000230 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000231 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900232 let ret = self.create_vm_internal(
233 config,
234 console_out_fd,
235 console_in_fd,
236 log_fd,
237 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000238 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900239 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000240 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000241 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000242 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000243
Shikha Panwar61a74b52024-02-16 13:17:01 +0000244 /// Allocate a new instance_id to the VM
245 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000246 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000247 GLOBAL_SERVICE.allocateInstanceId()
248 }
249
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 /// Initialise an empty partition image of the given size to be used as a writable partition.
251 fn initializeWritablePartition(
252 &self,
253 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000254 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900255 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000256 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900257 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900258 let size_bytes = size_bytes
259 .try_into()
260 .with_context(|| format!("Invalid size: {}", size_bytes))
261 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000262 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000263 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000264 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000265 image
266 .seek(SeekFrom::Start(0))
267 .context("failed to move cursor to start")
268 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900269 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700270 // Set the file length. In most filesystems, this will not allocate any physical disk
271 // space, it will only change the logical size.
272 image
273 .set_len(size_bytes)
274 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900275 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276
277 match partition_type {
278 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700279 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
280 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000281 _ => Err(Error::new(
282 ErrorKind::Unsupported,
283 format!("Unsupported partition type {:?}", partition_type),
284 )),
285 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900286 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
287 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000288
289 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000290 }
291
Jiyong Park0a248432021-08-20 23:32:39 +0900292 /// Creates or update the idsig file by digesting the input APK file.
293 fn createOrUpdateIdsigFile(
294 &self,
295 input_fd: &ParcelFileDescriptor,
296 idsig_fd: &ParcelFileDescriptor,
297 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900298 check_manage_access()?;
299
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900301 Ok(())
302 }
303
Andrew Walbran320b5602021-03-04 16:11:12 +0000304 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
305 /// and as such is only permitted from the shell user.
306 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000307 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000308 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000309 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900310
311 /// Get a list of assignable device types.
312 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
313 // Delegate to the global service, including checking the permission.
314 GLOBAL_SERVICE.getAssignableDevices()
315 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100316
Inseob Kim46257382024-01-03 15:41:22 +0900317 /// Get a list of supported OSes.
318 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
319 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
320 }
321
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100322 /// Returns whether given feature is enabled
323 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
324 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000325 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100326 }
Alice Wange64dd182024-01-17 15:57:55 +0000327
328 fn enableTestAttestation(&self) -> binder::Result<()> {
329 GLOBAL_SERVICE.enableTestAttestation()
330 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000331
332 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
333 check_manage_access()?;
334 GLOBAL_SERVICE.isRemoteAttestationSupported()
335 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000336
337 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
338 // The response is specific to Microdroid. Updatable VMs are only possible if device
339 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
340 // this, however other guest OSes may do things differently.
341 check_manage_access()?;
342 Ok(is_secretkeeper_supported())
343 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000344
Shikha Panwar07d701c2024-03-28 14:43:52 +0000345 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
346 check_manage_access()?;
347 GLOBAL_SERVICE.removeVmInstance(instance_id)
348 }
349
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000350 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
351 check_manage_access()?;
352 GLOBAL_SERVICE.claimVmInstance(instance_id)
353 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000354}
355
Inseob Kimecde8c02024-09-03 13:11:08 +0900356/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
357#[derive(Debug, Default)]
358struct EarlyVmContext {
359 /// The unique CID assigned to the VM for vsock communication.
360 cid: Cid,
361 /// Temporary directory for this VM instance.
362 temp_dir: PathBuf,
363}
364
365impl EarlyVmContext {
366 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
367 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
368 // should trust clients, e.g. they won't run two VMs at the same time
369 let _ = remove_dir_all(&temp_dir);
370 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
371
372 Ok(Self { cid, temp_dir })
373 }
374}
375
376impl Interface for EarlyVmContext {}
377
378impl Drop for EarlyVmContext {
379 fn drop(&mut self) {
380 if let Err(e) = remove_dir_all(&self.temp_dir) {
381 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
382 }
383 }
384}
385
386impl IGlobalVmContext for EarlyVmContext {
387 fn getCid(&self) -> binder::Result<i32> {
388 Ok(self.cid as i32)
389 }
390
391 fn getTemporaryDirectory(&self) -> binder::Result<String> {
392 Ok(self.temp_dir.to_string_lossy().to_string())
393 }
394
395 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
396 Err(Status::new_exception_str(
397 ExceptionCode::UNSUPPORTED_OPERATION,
398 Some("Early VM doesn't support setting host console name"),
399 ))
400 }
401}
402
403fn find_partition(path: &Path) -> binder::Result<String> {
404 match path.components().nth(1) {
405 Some(std::path::Component::Normal(partition)) => {
406 Ok(partition.to_string_lossy().into_owned())
407 }
408 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
409 .or_service_specific_exception(-1),
410 }
411}
412
Jiyong Park8611a6c2021-07-09 18:17:44 +0900413impl VirtualizationService {
414 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000415 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900416 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000417
Inseob Kimecde8c02024-09-03 13:11:08 +0900418 fn create_early_vm_context(
419 &self,
420 config: &VirtualMachineConfig,
421 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
422 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
423 let link = fs::read_link(&calling_exe_path)
424 .context(format!("can't read_link '{calling_exe_path}'"))
425 .or_service_specific_exception(-1)?;
426 let partition = find_partition(&link)?;
427
428 let name = match config {
429 VirtualMachineConfig::RawConfig(config) => &config.name,
430 VirtualMachineConfig::AppConfig(config) => &config.name,
431 };
432 let early_vm =
433 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
434 if Path::new(&early_vm.path) != link {
435 return Err(anyhow!(
436 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
437 &early_vm.path,
438 link.display()
439 ))
440 .or_service_specific_exception(-1);
441 }
442
443 let cid = early_vm.cid as Cid;
444 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
445
446 let context = EarlyVmContext::new(cid, temp_dir.clone())
447 .context(format!("Can't create early vm contexts for {cid}"))
448 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900449
Jiyong Park690c1ca2024-11-28 18:06:50 +0900450 if requires_vm_service(config) {
451 // Start VM service listening for connections from the new CID on port=CID.
452 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
453 let port = cid;
454 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
455 .context(format!("Could not start RpcServer on port {port}"))
456 .or_service_specific_exception(-1)?;
457 vm_server.start();
458 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
459 } else {
460 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
461 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900462 }
463
David Brazdil209074a2023-01-12 16:44:51 +0000464 fn create_vm_context(
465 &self,
466 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900467 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000468 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000469 const NUM_ATTEMPTS: usize = 5;
470
471 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000472 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000473 let cid = vm_context.getCid()? as Cid;
474 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900475
476 // We don't need to start the VM service for custom VMs.
477 if !requires_vm_service(config) {
478 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
479 }
480
David Brazdil8cf8f482022-11-23 14:21:26 +0000481 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
482
483 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000484 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000485 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000486 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000487 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900488 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000489 }
490 Err(err) => {
491 warn!("Could not start RpcServer on port {}: {}", port, err);
492 }
493 }
494 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900495 Err(anyhow!("Too many attempts to create VM context failed"))
496 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000497 }
498
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000499 fn create_vm_internal(
500 &self,
501 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900502 console_out_fd: Option<&ParcelFileDescriptor>,
503 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000504 log_fd: Option<&ParcelFileDescriptor>,
505 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000506 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000507 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000508 let requester_uid = get_calling_uid();
509 let requester_debug_pid = get_calling_pid();
510
Nikita Ioffe631717e2023-09-05 13:38:07 +0100511 check_config_features(config)?;
512
Inseob Kimecde8c02024-09-03 13:11:08 +0900513 if cfg!(early) {
514 check_config_allowed_for_early_vms(config)?;
515 }
516
Nikita Ioffeb1416122024-10-22 12:18:49 +0000517 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
518 info!("callers secontext: {}", caller_secontext);
519
David Brazdil209074a2023-01-12 16:44:51 +0000520 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900521 let (vm_context, cid, temporary_directory) = if cfg!(early) {
522 self.create_early_vm_context(config)?
523 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900524 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900525 };
Inseob Kim1119d702022-05-02 18:01:58 +0900526
Alan Stokesfda70842023-12-20 17:50:14 +0000527 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100528 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900529 }
530
Nikita Ioffe5776f082023-02-10 21:38:26 +0000531 let gdb_port = extract_gdb_port(config);
532
533 // Additional permission checks if caller request gdb.
534 if gdb_port.is_some() {
535 check_gdb_allowed(config)?;
536 }
537
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000538 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900539
Jaewan Kimf3143242024-03-15 06:56:31 +0000540 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000541 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900542 Some(prepare_ramdump_file(&temporary_directory)?)
543 } else {
544 None
545 };
546
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000547 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900548 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100549 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900550 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100551 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100552 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
553 Some(clone_file(fd)?)
554 } else if debug_config.dump_device_tree {
555 Some(prepare_dump_dt_file(&temporary_directory)?)
556 } else {
557 None
558 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000559
560 // Counter to generate unique IDs for temporary image files.
561 let mut next_temporary_image_id = 0;
562 // Files which are referred to from composite images. These must be mapped to the crosvm
563 // child process, and not closed before it is started.
564 let mut indirect_files = vec![];
565
Alan Stokes7bc146c2022-10-20 17:10:32 +0100566 let (is_app_config, config) = match config {
567 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
568 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900569 let config = load_app_config(config, &debug_config, &temporary_directory)
570 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900571 *is_protected = config.protectedVm;
572 let message = format!("Failed to load app config: {:?}", e);
573 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900574 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900575 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100576 (true, BorrowedOrOwned::Owned(config))
577 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000578 };
579 let config = config.as_ref();
580 *is_protected = config.protectedVm;
581
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000582 if !config.teeServices.is_empty() {
583 check_tee_service_permission(&caller_secontext, &config.teeServices)
584 .with_log()
585 .or_binder_exception(ExceptionCode::SECURITY)?;
586 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000587
Jiyong Park3051ffe2024-11-26 14:41:58 +0900588 let kernel = maybe_clone_file(&config.kernel)?;
589 let initrd = maybe_clone_file(&config.initrd)?;
590
591 if config.protectedVm {
592 // Fail fast with a meaningful error message in case device doesn't support pVMs.
593 check_protected_vm_is_supported()?;
594
595 // In a protected VM, we require custom kernels to come from a trusted source
596 // (b/237054515).
597 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
598
599 // Check if partition images are labeled incorrectly. This is to prevent random images
600 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
601 // from being loaded in a pVM. This applies to everything but the instance image in the
602 // raw config, and everything but the non-executable, generated partitions in the app
603 // config.
604 config
605 .disks
606 .iter()
607 .flat_map(|disk| disk.partitions.iter())
608 .filter(|partition| {
609 if is_app_config {
610 !is_safe_app_partition(&partition.label)
611 } else {
612 !is_safe_raw_partition(&partition.label)
613 }
614 })
615 .try_for_each(check_label_for_partition)
616 .or_service_specific_exception(-1)?;
617 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000618
Inseob Kimff48a7c2024-02-26 22:07:21 +0900619 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
620 // have unstable interfaces.
621 // TODO(b/316431494): remove once Treble interfaces are stabilized.
622 check_partitions_for_files(config).or_service_specific_exception(-1)?;
623
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000624 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900625 write_zero_filler(&zero_filler_path)
626 .context("Failed to make composite image")
627 .with_log()
628 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000629
630 // Assemble disk images if needed.
631 let disks = config
632 .disks
633 .iter()
634 .map(|disk| {
635 assemble_disk_image(
636 disk,
637 &zero_filler_path,
638 &temporary_directory,
639 &mut next_temporary_image_id,
640 &mut indirect_files,
641 )
642 })
643 .collect::<Result<Vec<DiskFile>, _>>()?;
644
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700645 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
646
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000647 let (cpus, host_cpu_topology) = match config.cpuTopology {
648 CpuTopology::MATCH_HOST => (None, true),
649 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
650 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900651 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
652 .with_log()
653 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000654 }
655 };
656
David Brazdil2dfefd12023-11-17 14:07:36 +0000657 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900658 let mut set = HashSet::new();
659 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900660 let path = canonicalize(device)
661 .with_context(|| format!("can't canonicalize {device}"))
662 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900663 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900664 return Err(anyhow!("duplicated device {device}"))
665 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900666 }
667 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000668 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000669 let dtbo_file = File::from(
670 GLOBAL_SERVICE
671 .getDtboFile()?
672 .as_ref()
673 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900674 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000675 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
676 );
677 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900678 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000679 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900680 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900681 let display_config = if cfg!(paravirtualized_devices) {
682 config
683 .displayConfig
684 .as_ref()
685 .map(DisplayConfig::new)
686 .transpose()
687 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
688 } else {
689 None
690 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700691 let gpu_config = if cfg!(paravirtualized_devices) {
692 config
693 .gpuConfig
694 .as_ref()
695 .map(GpuConfig::new)
696 .transpose()
697 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
698 } else {
699 None
700 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900701
Jeongik Chac181be72024-03-27 00:18:30 +0900702 let input_device_options = if cfg!(paravirtualized_devices) {
703 config
704 .inputDevices
705 .iter()
706 .map(to_input_device_option_from)
707 .collect::<Result<Vec<InputDeviceOption>, _>>()
708 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
709 } else {
710 vec![]
711 };
712
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900713 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900714 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900715 if *is_protected {
716 return Err(anyhow!("Network feature is not supported for pVM yet"))
717 .with_log()
718 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
719 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900720 Some(File::from(
721 GLOBAL_SERVICE
722 .createTapInterface(&get_this_pid().to_string())?
723 .as_ref()
724 .try_clone()
725 .context("Failed to get TAP interface from ParcelFileDescriptor")
726 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
727 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900728 } else {
729 None
730 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800731
732 let audio_config = if cfg!(paravirtualized_devices) {
733 config.audioConfig.as_ref().map(AudioConfig::new)
734 } else {
735 None
736 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900737
Elie Kheirallah29d72912024-08-07 20:17:26 +0000738 let usb_config = config
739 .usbConfig
740 .as_ref()
741 .map(UsbConfig::new)
742 .unwrap_or(Ok(UsbConfig { controller: false }))
743 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
744
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000745 // Actually start the VM.
746 let crosvm_config = CrosvmConfig {
747 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000748 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000749 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000750 kernel,
751 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000752 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700753 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000754 params: config.params.to_owned(),
755 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900756 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700757 memory_mib: config
758 .memoryMib
759 .try_into()
760 .ok()
761 .and_then(NonZeroU32::new)
762 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000763 cpus,
764 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900765 console_out_fd,
766 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000767 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900768 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000769 indirect_files,
770 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900771 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000772 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900773 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000774 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000775 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900776 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900777 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000778 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900779 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800780 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000781 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700782 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800783 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900784 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000785 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000786 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000787 };
788 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100789 VmInstance::new(
790 crosvm_config,
791 temporary_directory,
792 requester_uid,
793 requester_debug_pid,
794 vm_context,
795 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900796 .with_context(|| format!("Failed to create VM with config {:?}", config))
797 .with_log()
798 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000799 );
800 state.add_vm(Arc::downgrade(&instance));
801 Ok(VirtualMachine::create(instance))
802 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900803}
804
Alan Stokesfda70842023-12-20 17:50:14 +0000805/// Returns whether a VM config represents a "custom" virtual machine, which requires the
806/// USE_CUSTOM_VIRTUAL_MACHINE.
807fn is_custom_config(config: &VirtualMachineConfig) -> bool {
808 match config {
809 // Any raw (non-Microdroid) VM is considered custom.
810 VirtualMachineConfig::RawConfig(_) => true,
811 VirtualMachineConfig::AppConfig(config) => {
812 // Some features are reserved for platform apps only, even when using
813 // VirtualMachineAppConfig. Almost all of these features are grouped in the
814 // CustomConfig struct:
815 // - controlling CPUs;
816 // - gdbPort is set, meaning that crosvm will start a gdb server;
817 // - using anything other than the default kernel;
818 // - specifying devices to be assigned.
819 if config.customConfig.is_some() {
820 true
821 } else {
822 // Additional custom features not included in CustomConfig:
823 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000824 // - specifying extra APKs;
825 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900826 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000827 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900828 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
829 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000830 }
831 }
832 }
833}
834
Jiyong Park690c1ca2024-11-28 18:06:50 +0900835/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
836/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
837/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
838/// "microdroid" we run VirtualMachineService
839fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
840 match config {
841 VirtualMachineConfig::AppConfig(_) => true,
842 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
843 }
844}
845
Seungjae Yoo14e60182024-02-21 13:28:31 +0900846fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
847 let VirtualMachineConfig::AppConfig(config) = config else {
848 return Ok(None);
849 };
850 let Some(custom_config) = &config.customConfig else {
851 return Ok(None);
852 };
853 let Some(file) = custom_config.vendorImage.as_ref() else {
854 return Ok(None);
855 };
856
857 let file = clone_file(file)?;
858 let size =
859 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
860 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
861 .context("Failed to get vbmeta from microdroid-vendor.img")?;
862
863 for descriptor in vbmeta.descriptors()?.iter() {
864 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
865 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
866 return Ok(Some(root_digest.as_bytes().to_vec()));
867 }
868 }
869 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
870}
871
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000872fn maybe_create_device_tree_overlay(
873 config: &VirtualMachineConfig,
874 temporary_directory: &Path,
875) -> binder::Result<Option<File>> {
876 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
877 // (e.g. instance-id)
878 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
879 let host_ref_dt = if host_ref_dt.exists()
880 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
881 {
882 Some(host_ref_dt)
883 } else {
884 warn!("VM reference DT doesn't exist in host DT");
885 None
886 };
887
888 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
889 .context("Failed to extract vendor hashtree digest")
890 .or_service_specific_exception(-1)?;
891
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000892 let vendor_hashtree_digest = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000893 info!(
894 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
895 match the trusted digest in the pvmfw config, causing the VM to fail to start."
896 );
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000897 Some((cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice()))
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000898 } else {
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000899 None
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000900 };
901
Matt Gilbrideb57abcc2024-10-12 15:26:45 +0000902 let key_material;
903 let secretkeeper_public_key = if is_secretkeeper_supported() {
904 let sk: Strong<dyn ISecretkeeper> = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
905 if sk.getInterfaceVersion()? >= 2 {
906 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
907 key_material = keyMaterial;
908 Some((cstr!("secretkeeper_public_key"), key_material.as_slice()))
909 } else {
910 None
911 }
912 } else {
913 None
914 };
915
916 let trusted_props: Vec<(&CStr, &[u8])> =
917 vec![vendor_hashtree_digest, secretkeeper_public_key].into_iter().flatten().collect();
918
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000919 let instance_id;
920 let mut untrusted_props = Vec::with_capacity(2);
921 if cfg!(llpvm_changes) {
922 instance_id = extract_instance_id(config);
923 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
924 let want_updatable = extract_want_updatable(config);
925 if want_updatable && is_secretkeeper_supported() {
926 // Let guest know that it can defer rollback protection to Secretkeeper by setting
927 // an empty property in untrusted node in DT. This enables Updatable VMs.
928 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
929 }
930 }
931
932 let device_tree_overlay = if host_ref_dt.is_some()
933 || !untrusted_props.is_empty()
934 || !trusted_props.is_empty()
935 {
936 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
937 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
938 let fdt =
939 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
940 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
941 .or_service_specific_exception(-1)?;
942 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
943 Some(File::open(dt_output).or_service_specific_exception(-1)?)
944 } else {
945 None
946 };
947 Ok(device_tree_overlay)
948}
949
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000950fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900951 let file = OpenOptions::new()
952 .create_new(true)
953 .read(true)
954 .write(true)
955 .open(zero_filler_path)
956 .with_context(|| "Failed to create zero.img")?;
957 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000958 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900959}
960
David Brazdilf50c7a62023-04-19 14:22:42 +0000961fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
962 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
963 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
964 part.flush()
965}
966
967fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
968 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
969 part.flush()
970}
971
972fn round_up(input: u64, granularity: u64) -> u64 {
973 if granularity == 0 {
974 return input;
975 }
976 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
977 let result = input.checked_add(granularity - 1).unwrap_or(input);
978 (result / granularity) * granularity
979}
980
Jeongik Chac181be72024-03-27 00:18:30 +0900981fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
982 Ok(match input_device {
983 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
984 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
985 height: u32::try_from(single_touch.height)?,
986 width: u32::try_from(single_touch.width)?,
987 name: if !single_touch.name.is_empty() {
988 Some(single_touch.name.clone())
989 } else {
990 None
991 },
992 },
993 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
994 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
995 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900996 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
997 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
998 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900999 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1000 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1001 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001002 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1003 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1004 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001005 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1006 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1007 height: u32::try_from(trackpad.height)?,
1008 width: u32::try_from(trackpad.width)?,
1009 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1010 },
Jeongik Cha10494912024-07-16 11:19:50 +09001011 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1012 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1013 height: u32::try_from(multi_touch.height)?,
1014 width: u32::try_from(multi_touch.width)?,
1015 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1016 },
Jeongik Chac181be72024-03-27 00:18:30 +09001017 })
1018}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001019
1020fn assemble_shared_paths(
1021 shared_paths: &[SharedPath],
1022 temporary_directory: &Path,
1023) -> Result<Vec<SharedPathConfig>, Status> {
1024 if shared_paths.is_empty() {
1025 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1026 }
1027
1028 shared_paths
1029 .iter()
1030 .map(|path| {
1031 Ok(SharedPathConfig {
1032 path: path.sharedPath.clone(),
1033 host_uid: path.hostUid,
1034 host_gid: path.hostGid,
1035 guest_uid: path.guestUid,
1036 guest_gid: path.guestGid,
1037 mask: path.mask,
1038 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001039 socket_path: temporary_directory
1040 .join(&path.socketPath)
1041 .to_string_lossy()
1042 .to_string(),
1043 socket_fd: maybe_clone_file(&path.socketFd)?,
1044 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001045 })
1046 })
1047 .collect()
1048}
1049
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001050/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1051///
1052/// This may involve assembling a composite disk from a set of partition images.
1053fn assemble_disk_image(
1054 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001055 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001056 temporary_directory: &Path,
1057 next_temporary_image_id: &mut u64,
1058 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001059) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001060 let image = if !disk.partitions.is_empty() {
1061 if disk.image.is_some() {
1062 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001063 return Err(anyhow!("DiskImage contains both image and partitions"))
1064 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001065 }
1066
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001067 let composite_image_filenames =
1068 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1069 let (image, partition_files) = make_composite_image(
1070 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001071 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001072 &composite_image_filenames.composite,
1073 &composite_image_filenames.header,
1074 &composite_image_filenames.footer,
1075 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001076 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1077 .with_log()
1078 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001079
1080 // Pass the file descriptors for the various partition files to crosvm when it
1081 // is run.
1082 indirect_files.extend(partition_files);
1083
1084 image
1085 } else if let Some(image) = &disk.image {
1086 clone_file(image)?
1087 } else {
1088 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001089 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1090 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001091 };
1092
1093 Ok(DiskFile { image, writable: disk.writable })
1094}
1095
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001096fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1097 if let Some(ref mut params) = vm_config.params {
1098 params.push(' ');
1099 params.push_str(param)
1100 } else {
1101 vm_config.params = Some(param.to_owned())
1102 }
1103}
1104
Inseob Kim46257382024-01-03 15:41:22 +09001105fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1106 if config.extension()?.to_str()? != "json" {
1107 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001108 }
Inseob Kim46257382024-01-03 15:41:22 +09001109
1110 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1111}
1112
1113fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1114 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1115 let os_names =
1116 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1117
1118 Ok(os_names)
1119}
1120
1121fn get_supported_os_names() -> Result<HashSet<String>> {
1122 if !cfg!(vendor_modules) {
1123 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1124 }
1125
1126 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1127}
1128
1129fn is_valid_os(os_name: &str) -> bool {
1130 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001131}
1132
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001133fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1134 if !cfg!(vendor_modules) {
1135 return false;
1136 }
1137 match config {
1138 VirtualMachineConfig::RawConfig(_) => false,
1139 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1140 }
1141}
1142
Jooyung Han21e9b922021-06-26 04:14:16 +09001143fn load_app_config(
1144 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001145 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001146 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001147) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001148 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1149 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001150 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001151
Shikha Panwar22e70452022-10-10 18:32:55 +00001152 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1153 Some(clone_file(file)?)
1154 } else {
1155 None
1156 };
1157
Alan Stokesfda70842023-12-20 17:50:14 +00001158 let vm_payload_config;
1159 let extra_apk_files: Vec<_>;
1160 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001161 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001162 vm_payload_config =
1163 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1164 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1165 extra_apk_files = vm_payload_config
1166 .extra_apks
1167 .iter()
1168 .enumerate()
1169 .map(|(i, apk)| {
1170 File::open(PathBuf::from(&apk.path))
1171 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1172 })
1173 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001174 }
Alan Stokesfda70842023-12-20 17:50:14 +00001175 Payload::PayloadConfig(payload_config) => {
1176 vm_payload_config = create_vm_payload_config(payload_config)?;
1177 extra_apk_files =
1178 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1179 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001180 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001181
Inseob Kim89b24592024-02-23 18:59:43 +09001182 let payload_config_os = vm_payload_config.os.name.as_str();
1183 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1184 bail!("'os' in payload config is deprecated");
1185 }
1186
Inseob Kim172f9eb2023-11-06 17:02:08 +09001187 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001188 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001189 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001190 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001191 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001192
1193 // It is safe to construct a filename based on the os_name because we've already checked that it
1194 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001195 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1196 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001197 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001198
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001199 if let Some(custom_config) = &config.customConfig {
1200 if let Some(file) = custom_config.customKernelImage.as_ref() {
1201 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1202 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001203 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001204
1205 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001206 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001207 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001208 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001209
Chris Wailes6177c662024-05-09 14:37:44 -07001210 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001211 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001212
1213 for param in custom_config.extraKernelCmdlineParams.iter() {
1214 append_kernel_param(param, &mut vm_config);
1215 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001216
1217 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001218 }
1219
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001220 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1221 // so we need to provide it in the kernel cmdline.
1222 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1223 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1224 append_kernel_param("page_shift=14", &mut vm_config);
1225 }
1226
Andrew Walbrancc045902021-07-27 16:06:17 +00001227 if config.memoryMib > 0 {
1228 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001229 }
1230
Chris Wailes6177c662024-05-09 14:37:44 -07001231 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001232 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001233 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001234 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001235 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001236
Shikha Panwar22e70452022-10-10 18:32:55 +00001237 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001238 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001239
1240 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1241 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001242 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001243 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001244 temporary_directory,
1245 apk_file,
1246 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001247 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001248 &vm_payload_config,
1249 &mut vm_config,
1250 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001251
Andrew Walbrancc0db522021-07-12 17:03:42 +00001252 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001253}
1254
Inseob Kimff48a7c2024-02-26 22:07:21 +09001255fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1256 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1257 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1258
1259 // microdroid vendor image is OK
1260 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1261 {
1262 return Ok(());
1263 }
1264
1265 if link.starts_with("/vendor") || link.starts_with("/odm") {
1266 bail!("vendor or odm file {} can't be used for VM", link.display());
1267 }
1268
1269 Ok(())
1270}
1271
1272fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1273 config
1274 .disks
1275 .iter()
1276 .flat_map(|disk| disk.partitions.iter())
1277 .filter_map(|partition| partition.image.as_ref())
1278 .try_for_each(check_partition_for_file)?;
1279
1280 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1281 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1282 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1283
1284 Ok(())
1285}
1286
Alan Stokes0d1ef782022-09-27 13:46:35 +01001287fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1288 let mut apk_zip = ZipArchive::new(apk_file)?;
1289 let config_file = apk_zip.by_name(config_path)?;
1290 Ok(serde_json::from_reader(config_file)?)
1291}
1292
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001293fn create_vm_payload_config(
1294 payload_config: &VirtualMachinePayloadConfig,
1295) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001296 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1297 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1298 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001299
1300 let payload_binary_name = &payload_config.payloadBinaryName;
1301 if payload_binary_name.contains('/') {
1302 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1303 }
1304
1305 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001306
1307 // The VM only cares about how many there are, these names are actually ignored.
1308 let extra_apk_count = payload_config.extraApks.len();
1309 let extra_apks =
1310 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1311
Inseob Kim89b24592024-02-23 18:59:43 +09001312 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001313}
1314
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001315/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001316fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001317 temporary_directory: &Path,
1318 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001319) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001320 let id = *next_temporary_image_id;
1321 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001322 CompositeImageFilenames {
1323 composite: temporary_directory.join(format!("composite-{}.img", id)),
1324 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1325 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1326 }
1327}
1328
1329/// Filenames for a composite disk image, including header and footer partitions.
1330#[derive(Clone, Debug, Eq, PartialEq)]
1331struct CompositeImageFilenames {
1332 /// The composite disk image itself.
1333 composite: PathBuf,
1334 /// The header partition image.
1335 header: PathBuf,
1336 /// The footer partition image.
1337 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001338}
1339
Jiyong Park753553b2021-07-12 21:21:09 +09001340/// Checks whether the caller has a specific permission
1341fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001342 if cfg!(early) {
1343 // Skip permission check for early VMs, in favor of SELinux
1344 return Ok(());
1345 }
David Brazdil1f530702022-10-03 12:18:10 +01001346 let calling_pid = get_calling_pid();
1347 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001348 // Root can do anything
1349 if calling_uid == 0 {
1350 return Ok(());
1351 }
1352 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001353 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001354 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001355 Ok(())
1356 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001357 Err(anyhow!("does not have the {} permission", perm))
1358 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001359 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001360}
1361
Jiyong Park753553b2021-07-12 21:21:09 +09001362/// Check whether the caller of the current Binder method is allowed to manage VMs
1363fn check_manage_access() -> binder::Result<()> {
1364 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1365}
1366
Inseob Kim1119d702022-05-02 18:01:58 +09001367/// Check whether the caller of the current Binder method is allowed to create custom VMs
1368fn check_use_custom_virtual_machine() -> binder::Result<()> {
1369 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1370}
1371
Alan Stokes185fe112023-01-10 16:20:55 +00001372/// Return whether a partition is exempt from selinux label checks, because we know that it does
1373/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001374fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001375 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001376 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001377 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001378 || label == "microdroid-apk-idsig"
1379 || label == "payload-metadata"
1380 || label.starts_with("extra-idsig-")
1381}
1382
Alice Wangc206b9b2023-08-28 14:13:51 +00001383/// Returns whether a partition with the given label is safe for a raw config VM.
1384fn is_safe_raw_partition(label: &str) -> bool {
1385 label == "vm-instance"
1386}
1387
Alan Stokes185fe112023-01-10 16:20:55 +00001388/// Check that a file SELinux label is acceptable.
1389///
1390/// 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 +09001391/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001392///
1393/// Note that sepolicy must also grant read access for these types to both virtualization
1394/// service and crosvm.
1395///
1396/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1397/// user devices (W^X).
1398fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1399 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001400 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001401 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001402 | "staging_data_file" // updated/staged APEX images
1403 | "system_file" // immutable dm-verity protected partition
1404 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001405 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001406 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001407 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001408 }
1409}
1410
Alan Stokes185fe112023-01-10 16:20:55 +00001411fn check_label_for_partition(partition: &Partition) -> Result<()> {
1412 let file = partition.image.as_ref().unwrap().as_ref();
1413 check_label_is_allowed(&getfilecon(file)?)
1414 .with_context(|| format!("Partition {} invalid", &partition.label))
1415}
1416
1417fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1418 if let Some(f) = kernel {
1419 check_label_for_file(f, "kernel")?;
1420 }
1421 if let Some(f) = initrd {
1422 check_label_for_file(f, "initrd")?;
1423 }
1424 Ok(())
1425}
1426fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1427 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1428}
1429
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001430/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1431#[derive(Debug)]
1432struct VirtualMachine {
1433 instance: Arc<VmInstance>,
1434}
1435
1436impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001437 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001438 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001439 }
1440}
1441
1442impl Interface for VirtualMachine {}
1443
Devin Moore407df8f2024-08-27 19:39:16 +00001444impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001445 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001446 // Don't check permission. The owner of the VM might have passed this binder object to
1447 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001448 Ok(self.instance.cid as i32)
1449 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001450
Andrew Walbran6b650662021-09-07 13:13:23 +00001451 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001452 // Don't check permission. The owner of the VM might have passed this binder object to
1453 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001454 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001455 }
1456
1457 fn registerCallback(
1458 &self,
1459 callback: &Strong<dyn IVirtualMachineCallback>,
1460 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001461 // Don't check permission. The owner of the VM might have passed this binder object to
1462 // others.
1463 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001464 // TODO: Should this give an error if the VM is already dead?
1465 self.instance.callbacks.add(callback.clone());
1466 Ok(())
1467 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001468
Andrew Walbranf8d94112021-09-07 11:45:36 +00001469 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001470 self.instance
1471 .start()
1472 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1473 .with_log()
1474 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001475 }
1476
Inseob Kima446f802022-07-11 19:46:37 +09001477 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001478 self.instance
1479 .kill()
1480 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1481 .with_log()
1482 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001483 }
1484
Keir Fraser48221ba2024-07-12 14:05:02 +00001485 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1486 let balloon = self
1487 .instance
1488 .get_memory_balloon()
1489 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1490 .with_log()
1491 .or_service_specific_exception(-1)?;
1492 Ok(balloon.try_into().unwrap())
1493 }
1494
1495 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001496 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001497 .set_memory_balloon(num_bytes.try_into().unwrap())
1498 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001499 .with_log()
1500 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001501 }
1502
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001503 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001504 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001505 return Err(Status::new_service_specific_error_str(
1506 IVirtualMachine::ERROR_UNEXPECTED,
1507 Some("Virtual Machine is not running"),
1508 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001509 }
Alan Stokes10c47672022-12-13 17:17:08 +00001510 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001511 if port < VSOCK_PRIV_PORT_MAX {
1512 return Err(Status::new_service_specific_error_str(
1513 IVirtualMachine::ERROR_UNEXPECTED,
1514 Some("Can't connect to privileged port {port}"),
1515 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001516 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001517 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1518 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001519 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001520 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001521 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001522
Devin Moore407df8f2024-08-27 19:39:16 +00001523 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1524 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1525 return Err(Status::new_service_specific_error_str(
1526 IVirtualMachine::ERROR_UNEXPECTED,
1527 Some("Virtual Machine is not running"),
1528 ));
1529 }
1530 let port = port as u32;
1531 if port < VSOCK_PRIV_PORT_MAX {
1532 return Err(Status::new_service_specific_error_str(
1533 IVirtualMachine::ERROR_UNEXPECTED,
1534 Some("Can't connect to privileged port {port}"),
1535 ));
1536 }
1537 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001538 let addr = sockaddr_vm {
1539 svm_family: AF_VSOCK as sa_family_t,
1540 svm_reserved1: 0,
1541 svm_port: port,
1542 svm_cid: cid,
1543 svm_zero: [0u8; 4],
1544 };
1545 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001546 let accessor = Accessor::new(name, get_connection_info);
1547 accessor
1548 .as_binder()
1549 .context("The newly created Accessor should always have a binder")
1550 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1551 }
1552
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001553 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1554 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1555 }
Jiyong Park23b67392024-07-04 13:51:42 +09001556
1557 fn suspend(&self) -> binder::Result<()> {
1558 self.instance
1559 .suspend()
1560 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1561 .with_log()
1562 .or_service_specific_exception(-1)
1563 }
1564
1565 fn resume(&self) -> binder::Result<()> {
1566 self.instance
1567 .resume()
1568 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1569 .with_log()
1570 .or_service_specific_exception(-1)
1571 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001572}
1573
1574impl Drop for VirtualMachine {
1575 fn drop(&mut self) {
1576 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001577 if let Err(e) = self.instance.kill() {
1578 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1579 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001580 }
1581}
1582
1583/// A set of Binders to be called back in response to various events on the VM, such as when it
1584/// dies.
1585#[derive(Debug, Default)]
1586pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1587
1588impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001589 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001590 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001591 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001592 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001593 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001594 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001595 }
1596 }
1597 }
1598
Inseob Kim14cb8692021-08-31 21:50:39 +09001599 /// Call all registered callbacks to notify that the payload is ready to serve.
1600 pub fn notify_payload_ready(&self, cid: Cid) {
1601 let callbacks = &*self.0.lock().unwrap();
1602 for callback in callbacks {
1603 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001604 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001605 }
1606 }
1607 }
1608
Inseob Kim2444af92021-08-31 01:22:50 +09001609 /// Call all registered callbacks to notify that the payload has finished.
1610 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1611 let callbacks = &*self.0.lock().unwrap();
1612 for callback in callbacks {
1613 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001614 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001615 }
1616 }
1617 }
1618
Jooyung Handd0a1732021-11-23 15:26:20 +09001619 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001620 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001621 let callbacks = &*self.0.lock().unwrap();
1622 for callback in callbacks {
1623 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001624 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001625 }
1626 }
1627 }
1628
Andrew Walbrandae07162021-03-12 17:05:20 +00001629 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001630 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001631 let callbacks = &*self.0.lock().unwrap();
1632 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001633 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001634 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001635 }
1636 }
1637 }
1638
1639 /// Add a new callback to the set.
1640 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1641 self.0.lock().unwrap().push(callback);
1642 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001643}
1644
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001645/// The mutable state of the VirtualizationService. There should only be one instance of this
1646/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001647#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001648struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001649 /// The VMs which have been started. When VMs are started a weak reference is added to this
1650 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1651 /// the Binder client are dropped the weak reference here will become invalid, and will be
1652 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001653 vms: Vec<Weak<VmInstance>>,
1654}
1655
1656impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001657 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001658 fn vms(&self) -> Vec<Arc<VmInstance>> {
1659 // Attempt to upgrade the weak pointers to strong pointers.
1660 self.vms.iter().filter_map(Weak::upgrade).collect()
1661 }
1662
1663 /// Add a new VM to the list.
1664 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1665 // Garbage collect any entries from the stored list which no longer exist.
1666 self.vms.retain(|vm| vm.strong_count() > 0);
1667
1668 // Actually add the new VM.
1669 self.vms.push(vm);
1670 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001671
Jiyong Park8611a6c2021-07-09 18:17:44 +09001672 /// Get a VM that corresponds to the given cid
1673 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1674 self.vms().into_iter().find(|vm| vm.cid == cid)
1675 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001676}
1677
Andrew Walbran6b650662021-09-07 13:13:23 +00001678/// Gets the `VirtualMachineState` of the given `VmInstance`.
1679fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001680 match &*instance.vm_state.lock().unwrap() {
1681 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1682 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001683 PayloadState::Starting => VirtualMachineState::STARTING,
1684 PayloadState::Started => VirtualMachineState::STARTED,
1685 PayloadState::Ready => VirtualMachineState::READY,
1686 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001687 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001688 },
1689 VmState::Dead => VirtualMachineState::DEAD,
1690 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001691 }
1692}
1693
David Brazdilf50c7a62023-04-19 14:22:42 +00001694/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001695pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1696 file.as_ref()
1697 .try_clone()
1698 .context("Failed to clone File from ParcelFileDescriptor")
1699 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001700 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001701}
1702
Andrew Walbrand3a84182021-09-07 14:48:52 +00001703/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001704fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001705 file.as_ref().map(clone_file).transpose()
1706}
1707
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001708/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001709fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1710 // SAFETY: ownership is transferred from stream to f
1711 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1712 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001713}
1714
Jiyong Parkdcf17412022-02-08 15:07:23 +09001715/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001716fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1717 VersionReq::parse(s)
1718 .with_context(|| format!("Invalid platform version requirement {}", s))
1719 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001720}
1721
Jiyong Parked180932023-02-24 19:55:41 +09001722/// Create the empty ramdump file
1723fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1724 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1725 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1726 // owner) for readout.
1727 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001728 let ramdump = File::create(ramdump_path)
1729 .context("Failed to prepare ramdump file")
1730 .with_log()
1731 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001732 Ok(ramdump)
1733}
1734
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001735/// Create the empty device tree dump file
1736fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1737 let path = temporary_directory.join("device_tree.dtb");
1738 let file = File::create(path)
1739 .context("Failed to prepare device tree dump file")
1740 .with_log()
1741 .or_service_specific_exception(-1)?;
1742 Ok(file)
1743}
1744
Nikita Ioffe5776f082023-02-10 21:38:26 +00001745fn is_protected(config: &VirtualMachineConfig) -> bool {
1746 match config {
1747 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1748 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1749 }
1750}
1751
1752fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1753 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001754 return Err(anyhow!("Can't use gdb with protected VMs"))
1755 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001756 }
1757
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001758 if get_debug_level(config) == Some(DebugLevel::NONE) {
1759 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1760 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001761 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001762
1763 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001764}
1765
Shikha Panwar61a74b52024-02-16 13:17:01 +00001766fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1767 match config {
1768 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1769 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1770 }
1771}
1772
Alan Stokesc96b35e2024-05-03 13:21:20 +01001773fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1774 match config {
1775 VirtualMachineConfig::RawConfig(_) => true,
1776 VirtualMachineConfig::AppConfig(config) => {
1777 let Some(custom) = &config.customConfig else { return true };
1778 custom.wantUpdatable
1779 }
1780 }
1781}
1782
Nikita Ioffe5776f082023-02-10 21:38:26 +00001783fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1784 match config {
1785 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001786 VirtualMachineConfig::AppConfig(config) => {
1787 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1788 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001789 }
1790}
1791
Nikita Ioffe631717e2023-09-05 13:38:07 +01001792fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1793 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1794 if let Some(custom_config) = &config.customConfig {
1795 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1796 return Err(anyhow!("vendor modules feature is disabled"))
1797 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1798 }
1799 }
1800 Ok(())
1801}
1802
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001803fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1804 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1805 if let Some(custom_config) = &config.customConfig {
1806 if !custom_config.devices.is_empty() {
1807 return Err(anyhow!("device assignment feature is disabled"))
1808 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1809 }
1810 }
1811 Ok(())
1812}
1813
Alan Stokesfda70842023-12-20 17:50:14 +00001814fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1815 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1816 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1817 if !payload_config.extraApks.is_empty() {
1818 return Err(anyhow!("multi-tenant feature is disabled"))
1819 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1820 }
1821 Ok(())
1822}
1823
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001824fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1825 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1826 if let Some(custom_config) = &config.customConfig {
1827 if !custom_config.extraKernelCmdlineParams.is_empty() {
1828 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1829 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1830 }
1831 }
1832 Ok(())
1833}
1834
Nikita Ioffe99548382024-10-21 15:54:46 +00001835fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1836 match config {
1837 VirtualMachineConfig::RawConfig(config) => {
1838 if !config.teeServices.is_empty() {
1839 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1840 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1841 }
1842 }
1843 VirtualMachineConfig::AppConfig(config) => {
1844 if let Some(custom_config) = &config.customConfig {
1845 if !custom_config.teeServices.is_empty() {
1846 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1847 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1848 }
1849 }
1850 }
1851 };
1852 Ok(())
1853}
1854
Nikita Ioffef934e812024-07-05 15:44:41 +00001855fn check_protected_vm_is_supported() -> binder::Result<()> {
1856 let is_pvm_supported =
1857 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1858 if is_pvm_supported {
1859 Ok(())
1860 } else {
1861 Err(anyhow!("pVM is not supported"))
1862 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1863 }
1864}
1865
Nikita Ioffe631717e2023-09-05 13:38:07 +01001866fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1867 if !cfg!(vendor_modules) {
1868 check_no_vendor_modules(config)?;
1869 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001870 if !cfg!(device_assignment) {
1871 check_no_devices(config)?;
1872 }
Alan Stokesfda70842023-12-20 17:50:14 +00001873 if !cfg!(multi_tenant) {
1874 check_no_extra_apks(config)?;
1875 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001876 if !cfg!(debuggable_vms_improvements) {
1877 check_no_extra_kernel_cmdline_params(config)?;
1878 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001879 if !cfg!(tee_services_allowlist) {
1880 check_no_tee_services(config)?;
1881 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001882 Ok(())
1883}
1884
Inseob Kimecde8c02024-09-03 13:11:08 +09001885fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1886 check_no_vendor_modules(config)?;
1887 check_no_devices(config)?;
1888
1889 Ok(())
1890}
1891
Inseob Kim0168b462022-12-27 14:54:35 +09001892fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001893 fd: Option<&ParcelFileDescriptor>,
1894 tag: String,
1895) -> Result<Option<File>, Status> {
1896 if let Some(fd) = fd {
1897 return Ok(Some(clone_file(fd)?));
1898 }
1899
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001900 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001901 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001902
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001903 let mut reader = BufReader::new(File::from(read_fd));
1904 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001905
1906 std::thread::spawn(move || loop {
1907 let mut buf = vec![];
1908 match reader.read_until(b'\n', &mut buf) {
1909 Ok(0) => {
1910 // EOF
1911 return;
1912 }
1913 Ok(size) => {
1914 if buf[size - 1] == b'\n' {
1915 buf.pop();
1916 }
1917 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1918 }
1919 Err(e) => {
1920 error!("Could not read console pipe: {:?}", e);
1921 return;
1922 }
1923 };
1924 });
1925
1926 Ok(Some(write_fd))
1927}
1928
Jooyung Han35edb8f2021-07-01 16:17:16 +09001929/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1930/// it doesn't require that T implements Clone.
1931enum BorrowedOrOwned<'a, T> {
1932 Borrowed(&'a T),
1933 Owned(T),
1934}
1935
1936impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1937 fn as_ref(&self) -> &T {
1938 match self {
1939 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001940 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001941 }
1942 }
1943}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001944
1945/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1946#[derive(Debug, Default)]
1947struct VirtualMachineService {
1948 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001949 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001950}
1951
1952impl Interface for VirtualMachineService {}
1953
1954impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001955 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1956 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001957 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001958 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001959 vm.update_payload_state(PayloadState::Started)
1960 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001961 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001962
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001963 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1964 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001965 Ok(())
1966 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001967 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001968 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001969 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001970 }
Inseob Kim2444af92021-08-31 01:22:50 +09001971
Inseob Kimc7d28c72021-10-25 14:28:10 +00001972 fn notifyPayloadReady(&self) -> binder::Result<()> {
1973 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001974 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001975 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001976 vm.update_payload_state(PayloadState::Ready)
1977 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001978 vm.callbacks.notify_payload_ready(cid);
1979 Ok(())
1980 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001981 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001982 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001983 }
1984 }
1985
Inseob Kimc7d28c72021-10-25 14:28:10 +00001986 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1987 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001988 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001989 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001990 vm.update_payload_state(PayloadState::Finished)
1991 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001992 vm.callbacks.notify_payload_finished(cid, exit_code);
1993 Ok(())
1994 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001995 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001996 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001997 }
1998 }
1999
Alan Stokes2bead0d2022-09-05 16:58:34 +01002000 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002001 let cid = self.cid;
2002 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002003 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002004 vm.update_payload_state(PayloadState::Finished)
2005 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002006 vm.callbacks.notify_error(cid, error_code, message);
2007 Ok(())
2008 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002009 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002010 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002011 }
2012 }
Alice Wangc2fec932023-02-23 16:24:02 +00002013
Shikha Panware45e9422024-02-28 21:18:10 +00002014 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2015 if !is_secretkeeper_supported() {
2016 return Err(StatusCode::NAME_NOT_FOUND)?;
2017 }
2018 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2019 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002020 }
2021
Alice Wange64dd182024-01-17 15:57:55 +00002022 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2023 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002024 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002025}
2026
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002027fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002028 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2029 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002030}
2031
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002032impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002033 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002034 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002035 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002036 BinderFeatures::default(),
2037 )
2038 }
2039}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002040
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002041struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2042
2043impl Interface for SecretkeeperProxy {}
2044
2045impl ISecretkeeper for SecretkeeperProxy {
2046 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2047 // Pass the request to the channel, and read the response.
2048 self.0.processSecretManagementRequest(req)
2049 }
2050
2051 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2052 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2053 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2054 }
2055
2056 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2057 self.0.deleteIds(ids)
2058 }
2059
2060 fn deleteAll(&self) -> binder::Result<()> {
2061 self.0.deleteAll()
2062 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002063
2064 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2065 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2066 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2067 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2068 // use this API from the proxy.
2069 Err(ExceptionCode::SECURITY.into())
2070 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002071}
2072
2073struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2074
2075impl Interface for AuthGraphKeyExchangeProxy {}
2076
2077impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2078 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2079 self.0.create()
2080 }
2081
2082 fn init(
2083 &self,
2084 peer_pub_key: &PubKey,
2085 peer_id: &Identity,
2086 peer_nonce: &[u8],
2087 peer_version: i32,
2088 ) -> binder::Result<KeInitResult> {
2089 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2090 }
2091
2092 fn finish(
2093 &self,
2094 peer_pub_key: &PubKey,
2095 peer_id: &Identity,
2096 peer_signature: &SessionIdSignature,
2097 peer_nonce: &[u8],
2098 peer_version: i32,
2099 own_key: &Key,
2100 ) -> binder::Result<SessionInfo> {
2101 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2102 }
2103
2104 fn authenticationComplete(
2105 &self,
2106 peer_signature: &SessionIdSignature,
2107 shared_keys: &[AuthgraphArc; 2],
2108 ) -> binder::Result<[AuthgraphArc; 2]> {
2109 self.0.authenticationComplete(peer_signature, shared_keys)
2110 }
2111}
2112
Inseob Kimecde8c02024-09-03 13:11:08 +09002113// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002114#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002115struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002116 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002117 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002118 path: String,
2119}
2120
2121#[derive(Debug, Default, Deserialize)]
2122struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002123 early_vm: Vec<EarlyVm>,
2124}
2125
Inseob Kim7e1877b2024-11-07 17:28:56 +09002126static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2127 LazyLock::new(|| Mutex::new(HashMap::new()));
2128
Inseob Kimecde8c02024-09-03 13:11:08 +09002129fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2130 match partition {
2131 "system" => Ok(100..200),
2132 "system_ext" | "product" => Ok(200..300),
2133 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2134 }
2135}
2136
Inseob Kim7e1877b2024-11-07 17:28:56 +09002137fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002138 if !xml_path.exists() {
2139 bail!("{} doesn't exist", xml_path.display());
2140 }
2141
2142 let xml =
2143 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2144 let xml = String::from_utf8(xml)
2145 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2146 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2147 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2148
Inseob Kim7e1877b2024-11-07 17:28:56 +09002149 Ok(early_vms.early_vm)
2150}
Inseob Kimecde8c02024-09-03 13:11:08 +09002151
Inseob Kim7e1877b2024-11-07 17:28:56 +09002152fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2153 for early_vm in early_vms {
2154 let cid = early_vm
2155 .cid
2156 .try_into()
2157 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2158
2159 ensure!(
2160 cid_range.contains(&cid),
2161 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2162 early_vm.name
2163 );
2164 }
2165 Ok(())
2166}
2167
2168fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2169 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2170
2171 if let Some(result) = cache.get(partition) {
2172 return Ok(result.clone());
2173 }
2174
2175 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2176 let mut early_vms = Vec::new();
2177 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2178 match entry {
2179 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2180 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2181 }
2182 }
2183
2184 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2185 .with_context(|| format!("CID validation for {partition} failed"))?;
2186
2187 cache.insert(partition.to_owned(), early_vms.clone());
2188
2189 Ok(early_vms)
2190}
2191
2192fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2193 let mut found_vm: Option<&EarlyVm> = None;
2194
2195 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002196 if early_vm.name != name {
2197 continue;
2198 }
2199
Inseob Kimecde8c02024-09-03 13:11:08 +09002200 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002201 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002202 }
2203
2204 found_vm = Some(early_vm);
2205 }
2206
Inseob Kim7e1877b2024-11-07 17:28:56 +09002207 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002208}
2209
2210fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002211 let early_vms = get_early_vms_in_partition(partition)
2212 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2213
2214 Ok(find_early_vm(&early_vms, name)
2215 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2216 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002217}
2218
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002219#[cfg(test)]
2220mod tests {
2221 use super::*;
2222
2223 #[test]
2224 fn test_is_allowed_label_for_partition() -> Result<()> {
2225 let expected_results = vec![
2226 ("u:object_r:system_file:s0", true),
2227 ("u:object_r:apk_data_file:s0", true),
2228 ("u:object_r:app_data_file:s0", false),
2229 ("u:object_r:app_data_file:s0:c512,c768", false),
2230 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2231 ("invalid", false),
2232 ("user:role:apk_data_file:severity:categories", true),
2233 ("user:role:apk_data_file:severity:categories:extraneous", false),
2234 ];
2235
2236 for (label, expected_valid) in expected_results {
2237 let context = SeContext::new(label)?;
2238 let result = check_label_is_allowed(&context);
2239 if expected_valid {
2240 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2241 } else if result.is_ok() {
2242 bail!("Expected label {} to be disallowed", label);
2243 }
2244 }
2245 Ok(())
2246 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002247
2248 #[test]
2249 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2250 let apk = tempfile::tempfile().unwrap();
2251 let idsig = tempfile::tempfile().unwrap();
2252
2253 let ret = create_or_update_idsig_file(
2254 &ParcelFileDescriptor::new(apk),
2255 &ParcelFileDescriptor::new(idsig),
2256 );
2257 assert!(ret.is_err(), "should fail");
2258 Ok(())
2259 }
2260
2261 #[test]
2262 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2263 let tmp_dir = tempfile::TempDir::new().unwrap();
2264 let apk = File::open(tmp_dir.path()).unwrap();
2265 let idsig = tempfile::tempfile().unwrap();
2266
2267 let ret = create_or_update_idsig_file(
2268 &ParcelFileDescriptor::new(apk),
2269 &ParcelFileDescriptor::new(idsig),
2270 );
2271 assert!(ret.is_err(), "should fail");
2272 Ok(())
2273 }
2274
2275 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2276 /// on ext4 filesystem is passed.
2277 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2278 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2279 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2280 #[test]
2281 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2282 // APEXes are backed by the ext4.
2283 let apk = File::open("/apex/com.android.virt/").unwrap();
2284 let idsig = tempfile::tempfile().unwrap();
2285
2286 let ret = create_or_update_idsig_file(
2287 &ParcelFileDescriptor::new(apk),
2288 &ParcelFileDescriptor::new(idsig),
2289 );
2290 assert!(ret.is_err(), "should fail");
2291 Ok(())
2292 }
Jiyong Park8d192952023-06-26 14:29:51 +09002293
2294 #[test]
2295 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2296 use std::io::Seek;
2297
2298 // Pick any APK
2299 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2300 let mut idsig = tempfile::tempfile().unwrap();
2301
2302 create_or_update_idsig_file(
2303 &ParcelFileDescriptor::new(apk.try_clone()?),
2304 &ParcelFileDescriptor::new(idsig.try_clone()?),
2305 )?;
2306 let modified_orig = idsig.metadata()?.modified()?;
2307 apk.rewind()?;
2308 idsig.rewind()?;
2309
2310 // Call the function again
2311 create_or_update_idsig_file(
2312 &ParcelFileDescriptor::new(apk.try_clone()?),
2313 &ParcelFileDescriptor::new(idsig.try_clone()?),
2314 )?;
2315 let modified_new = idsig.metadata()?.modified()?;
2316 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2317 Ok(())
2318 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002319
2320 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002321 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2322 use std::io::Read;
2323
2324 // Pick any APK
2325 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2326 let idsig_empty = tempfile::tempfile().unwrap();
2327 let mut idsig_invalid = tempfile::tempfile().unwrap();
2328 idsig_invalid.write_all(b"Oops")?;
2329
2330 // Create new idsig
2331 create_or_update_idsig_file(
2332 &ParcelFileDescriptor::new(apk.try_clone()?),
2333 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2334 )?;
2335 apk.rewind()?;
2336
2337 // Update idsig_invalid
2338 create_or_update_idsig_file(
2339 &ParcelFileDescriptor::new(apk.try_clone()?),
2340 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2341 )?;
2342
2343 // Ensure the 2 idsig files have same size!
2344 assert!(
2345 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2346 "idsig files differ in size"
2347 );
2348 // Ensure the 2 idsig files have same content!
2349 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2350 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2351 }
2352 Ok(())
2353 }
2354 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002355 fn test_append_kernel_param_first_param() {
2356 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2357 append_kernel_param("foo=1", &mut vm_config);
2358 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2359 }
2360
2361 #[test]
2362 fn test_append_kernel_param() {
2363 let mut vm_config =
2364 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2365 append_kernel_param("bar=42", &mut vm_config);
2366 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2367 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002368
Inseob Kim46257382024-01-03 15:41:22 +09002369 fn test_extract_os_name_from_config_path(
2370 path: &Path,
2371 expected_result: Option<&str>,
2372 ) -> Result<()> {
2373 let result = extract_os_name_from_config_path(path);
2374 if result.as_deref() != expected_result {
2375 bail!("Expected {:?} but was {:?}", expected_result, &result)
2376 }
2377 Ok(())
2378 }
2379
2380 #[test]
2381 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2382 test_extract_os_name_from_config_path(
2383 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2384 Some("microdroid"),
2385 )
2386 }
2387
2388 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002389 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2390 test_extract_os_name_from_config_path(
2391 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2392 Some("microdroid_16k"),
2393 )
2394 }
2395
2396 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002397 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2398 test_extract_os_name_from_config_path(
2399 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2400 Some("microdroid_gki-android14-6.1"),
2401 )
2402 }
2403
2404 #[test]
2405 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2406 test_extract_os_name_from_config_path(
2407 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2408 None,
2409 )
2410 }
2411
2412 #[test]
2413 fn test_extract_os_name_from_configs() -> Result<()> {
2414 let tmp_dir = tempfile::TempDir::new()?;
2415 let tmp_dir_path = tmp_dir.path().to_owned();
2416
2417 let mut os_names: HashSet<String> = HashSet::new();
2418 os_names.insert("microdroid".to_owned());
2419 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2420 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2421
2422 // config files
2423 for os_name in &os_names {
2424 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2425 }
2426
2427 // fake files not related to configs
2428 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2429 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2430
2431 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2432 Some(s) => s.to_owned(),
2433 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2434 };
2435
2436 let result = extract_os_names_from_configs(&glob_pattern)?;
2437 if result != os_names {
2438 bail!("Expected {:?} but was {:?}", os_names, result);
2439 }
2440 Ok(())
2441 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002442
2443 #[test]
2444 fn test_find_early_vms_from_xml() -> Result<()> {
2445 let tmp_dir = tempfile::TempDir::new()?;
2446 let tmp_dir_path = tmp_dir.path().to_owned();
2447 let xml_path = tmp_dir_path.join("early_vms.xml");
2448
2449 std::fs::write(
2450 &xml_path,
2451 br#"<?xml version="1.0" encoding="utf-8"?>
2452 <early_vms>
2453 <early_vm>
2454 <name>vm_demo_native_early</name>
2455 <cid>123</cid>
2456 <path>/system/bin/vm_demo_native_early</path>
2457 </early_vm>
2458 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002459 <name>vm_demo_native_early_2</name>
2460 <cid>456</cid>
2461 <path>/system/bin/vm_demo_native_early_2</path>
2462 </early_vm>
2463 </early_vms>
2464 "#,
2465 )?;
2466
2467 let cid_range = 100..1000;
2468
2469 let early_vms = get_early_vms_in_path(&xml_path)?;
2470 validate_cid_range(&early_vms, &cid_range)?;
2471
2472 let test_cases = [
2473 (
2474 "vm_demo_native_early",
2475 EarlyVm {
2476 name: "vm_demo_native_early".to_owned(),
2477 cid: 123,
2478 path: "/system/bin/vm_demo_native_early".to_owned(),
2479 },
2480 ),
2481 (
2482 "vm_demo_native_early_2",
2483 EarlyVm {
2484 name: "vm_demo_native_early_2".to_owned(),
2485 cid: 456,
2486 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2487 },
2488 ),
2489 ];
2490
2491 for (name, expected) in test_cases {
2492 let result = find_early_vm(&early_vms, name)?;
2493 assert_eq!(result, &expected);
2494 }
2495
2496 Ok(())
2497 }
2498
2499 #[test]
2500 fn test_invalid_cid_validation() -> Result<()> {
2501 let tmp_dir = tempfile::TempDir::new()?;
2502 let xml_path = tmp_dir.path().join("early_vms.xml");
2503
2504 let cid_range = 100..1000;
2505
2506 for cid in [-1, 999999] {
2507 std::fs::write(
2508 &xml_path,
2509 format!(
2510 r#"<?xml version="1.0" encoding="utf-8"?>
2511 <early_vms>
2512 <early_vm>
2513 <name>vm_demo_invalid_cid</name>
2514 <cid>{cid}</cid>
2515 <path>/system/bin/vm_demo_invalid_cid</path>
2516 </early_vm>
2517 </early_vms>
2518 "#
2519 ),
2520 )?;
2521
2522 let early_vms = get_early_vms_in_path(&xml_path)?;
2523 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2524 }
2525
2526 Ok(())
2527 }
2528
2529 #[test]
2530 fn test_duplicated_early_vms() -> Result<()> {
2531 let tmp_dir = tempfile::TempDir::new()?;
2532 let tmp_dir_path = tmp_dir.path().to_owned();
2533 let xml_path = tmp_dir_path.join("early_vms.xml");
2534
2535 std::fs::write(
2536 &xml_path,
2537 br#"<?xml version="1.0" encoding="utf-8"?>
2538 <early_vms>
2539 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002540 <name>vm_demo_duplicated_name</name>
2541 <cid>456</cid>
2542 <path>/system/bin/vm_demo_duplicated_name_1</path>
2543 </early_vm>
2544 <early_vm>
2545 <name>vm_demo_duplicated_name</name>
2546 <cid>789</cid>
2547 <path>/system/bin/vm_demo_duplicated_name_2</path>
2548 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002549 </early_vms>
2550 "#,
2551 )?;
2552
2553 let cid_range = 100..1000;
2554
Inseob Kim7e1877b2024-11-07 17:28:56 +09002555 let early_vms = get_early_vms_in_path(&xml_path)?;
2556 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002557
Inseob Kim7e1877b2024-11-07 17:28:56 +09002558 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002559
2560 Ok(())
2561 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002562}