blob: 55de0af13642556628d04edfa22861057c31afc0 [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;
56use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
57 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
58 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
59 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
60 SessionInitiationInfo::SessionInitiationInfo,
61};
Inseob Kim7e1877b2024-11-07 17:28:56 +090062use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090063use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090064use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010065use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000066 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
67 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000068};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000069use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090073use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
David Brazdilf50c7a62023-04-19 14:22:42 +0000120const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
121
122/// crosvm requires all partitions to be a multiple of 4KiB.
123const PARTITION_GRANULARITY_BYTES: u64 = 4096;
124
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000125const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
126
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100127pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
128 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900129 if cfg!(early) {
130 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
131 } else {
132 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
133 .expect("Could not connect to VirtualizationServiceInternal")
134 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100135 });
136static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
137 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000138
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000139fn create_or_update_idsig_file(
140 input_fd: &ParcelFileDescriptor,
141 idsig_fd: &ParcelFileDescriptor,
142) -> Result<()> {
143 let mut input = clone_file(input_fd)?;
144 let metadata = input.metadata().context("failed to get input metadata")?;
145 if !metadata.is_file() {
146 bail!("input is not a regular file");
147 }
Alan Stokes25f69362023-03-06 16:51:54 +0000148 let mut sig =
149 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
150 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000151
152 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900153
154 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
155 // if the idsig file already has the same APK digest.
156 if output.metadata()?.len() > 0 {
157 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
158 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
159 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
160 return Ok(());
161 }
162 }
163 // if we fail to read v4signature from output, that's fine. User can pass a random file.
164 // We will anyway overwrite the file to the v4signature generated from input_fd.
165 }
166
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000167 output
168 .seek(SeekFrom::Start(0))
169 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000170 output.set_len(0).context("failed to set_len on the idsig output")?;
171 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000172 Ok(())
173}
174
Alan Stokes25f69362023-03-06 16:51:54 +0000175fn get_current_sdk() -> Result<u32> {
176 let current_sdk = system_properties::read("ro.build.version.sdk")?;
177 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
178 current_sdk.parse().context("Malformed SDK version")
179}
180
David Brazdil4b4c5102022-12-19 22:56:20 +0000181pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
182 for dir_entry in read_dir(path)? {
183 remove_file(dir_entry?.path())?;
184 }
185 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100186}
187
David Brazdil528e0472022-10-10 15:06:02 +0100188/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000189#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000190pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900191 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000192}
193
Shikha Panward8e35422021-10-11 13:51:27 +0000194impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000195 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000196 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
197 let state = &mut *self.state.lock().unwrap();
198 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000199 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000200 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000201 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
202 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000203 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000204 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000205 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000206 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
207 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000208 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000209 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000210 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000211 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000212 .or(Err(StatusCode::UNKNOWN_ERROR))?;
213 }
214 Ok(())
215 }
216}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000217impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000218 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
219 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000220 ///
221 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000222 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000223 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000224 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900225 console_out_fd: Option<&ParcelFileDescriptor>,
226 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000227 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000228 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000229 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000230 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900231 let ret = self.create_vm_internal(
232 config,
233 console_out_fd,
234 console_in_fd,
235 log_fd,
236 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000237 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900238 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000239 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000240 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000241 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000242
Shikha Panwar61a74b52024-02-16 13:17:01 +0000243 /// Allocate a new instance_id to the VM
244 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000245 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000246 GLOBAL_SERVICE.allocateInstanceId()
247 }
248
Andrew Walbrandff3b942021-06-09 15:20:36 +0000249 /// Initialise an empty partition image of the given size to be used as a writable partition.
250 fn initializeWritablePartition(
251 &self,
252 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000253 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900254 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000255 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900256 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900257 let size_bytes = size_bytes
258 .try_into()
259 .with_context(|| format!("Invalid size: {}", size_bytes))
260 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000261 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000262 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000263 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000264 image
265 .seek(SeekFrom::Start(0))
266 .context("failed to move cursor to start")
267 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900268 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700269 // Set the file length. In most filesystems, this will not allocate any physical disk
270 // space, it will only change the logical size.
271 image
272 .set_len(size_bytes)
273 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900274 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000275
276 match partition_type {
277 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700278 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
279 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000280 _ => Err(Error::new(
281 ErrorKind::Unsupported,
282 format!("Unsupported partition type {:?}", partition_type),
283 )),
284 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900285 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
286 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000287
288 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000289 }
290
Jiyong Park0a248432021-08-20 23:32:39 +0900291 /// Creates or update the idsig file by digesting the input APK file.
292 fn createOrUpdateIdsigFile(
293 &self,
294 input_fd: &ParcelFileDescriptor,
295 idsig_fd: &ParcelFileDescriptor,
296 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900297 check_manage_access()?;
298
Jiyong Park2227eaa2023-08-04 11:59:18 +0900299 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900300 Ok(())
301 }
302
Andrew Walbran320b5602021-03-04 16:11:12 +0000303 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
304 /// and as such is only permitted from the shell user.
305 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000306 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000307 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000308 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900309
310 /// Get a list of assignable device types.
311 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
312 // Delegate to the global service, including checking the permission.
313 GLOBAL_SERVICE.getAssignableDevices()
314 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100315
Inseob Kim46257382024-01-03 15:41:22 +0900316 /// Get a list of supported OSes.
317 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
318 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
319 }
320
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100321 /// Returns whether given feature is enabled
322 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
323 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000324 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100325 }
Alice Wange64dd182024-01-17 15:57:55 +0000326
327 fn enableTestAttestation(&self) -> binder::Result<()> {
328 GLOBAL_SERVICE.enableTestAttestation()
329 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000330
331 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
332 check_manage_access()?;
333 GLOBAL_SERVICE.isRemoteAttestationSupported()
334 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000335
336 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
337 // The response is specific to Microdroid. Updatable VMs are only possible if device
338 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
339 // this, however other guest OSes may do things differently.
340 check_manage_access()?;
341 Ok(is_secretkeeper_supported())
342 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000343
Shikha Panwar07d701c2024-03-28 14:43:52 +0000344 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
345 check_manage_access()?;
346 GLOBAL_SERVICE.removeVmInstance(instance_id)
347 }
348
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000349 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
350 check_manage_access()?;
351 GLOBAL_SERVICE.claimVmInstance(instance_id)
352 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000353}
354
Inseob Kimecde8c02024-09-03 13:11:08 +0900355/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
356#[derive(Debug, Default)]
357struct EarlyVmContext {
358 /// The unique CID assigned to the VM for vsock communication.
359 cid: Cid,
360 /// Temporary directory for this VM instance.
361 temp_dir: PathBuf,
362}
363
364impl EarlyVmContext {
365 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
366 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
367 // should trust clients, e.g. they won't run two VMs at the same time
368 let _ = remove_dir_all(&temp_dir);
369 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
370
371 Ok(Self { cid, temp_dir })
372 }
373}
374
375impl Interface for EarlyVmContext {}
376
377impl Drop for EarlyVmContext {
378 fn drop(&mut self) {
379 if let Err(e) = remove_dir_all(&self.temp_dir) {
380 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
381 }
382 }
383}
384
385impl IGlobalVmContext for EarlyVmContext {
386 fn getCid(&self) -> binder::Result<i32> {
387 Ok(self.cid as i32)
388 }
389
390 fn getTemporaryDirectory(&self) -> binder::Result<String> {
391 Ok(self.temp_dir.to_string_lossy().to_string())
392 }
393
394 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
395 Err(Status::new_exception_str(
396 ExceptionCode::UNSUPPORTED_OPERATION,
397 Some("Early VM doesn't support setting host console name"),
398 ))
399 }
400}
401
402fn find_partition(path: &Path) -> binder::Result<String> {
403 match path.components().nth(1) {
404 Some(std::path::Component::Normal(partition)) => {
405 Ok(partition.to_string_lossy().into_owned())
406 }
407 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
408 .or_service_specific_exception(-1),
409 }
410}
411
Jiyong Park8611a6c2021-07-09 18:17:44 +0900412impl VirtualizationService {
413 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000414 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900415 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000416
Inseob Kimecde8c02024-09-03 13:11:08 +0900417 fn create_early_vm_context(
418 &self,
419 config: &VirtualMachineConfig,
420 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
421 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
422 let link = fs::read_link(&calling_exe_path)
423 .context(format!("can't read_link '{calling_exe_path}'"))
424 .or_service_specific_exception(-1)?;
425 let partition = find_partition(&link)?;
426
427 let name = match config {
428 VirtualMachineConfig::RawConfig(config) => &config.name,
429 VirtualMachineConfig::AppConfig(config) => &config.name,
430 };
431 let early_vm =
432 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
433 if Path::new(&early_vm.path) != link {
434 return Err(anyhow!(
435 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
436 &early_vm.path,
437 link.display()
438 ))
439 .or_service_specific_exception(-1);
440 }
441
442 let cid = early_vm.cid as Cid;
443 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
444
445 let context = EarlyVmContext::new(cid, temp_dir.clone())
446 .context(format!("Can't create early vm contexts for {cid}"))
447 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900448
Jiyong Park690c1ca2024-11-28 18:06:50 +0900449 if requires_vm_service(config) {
450 // Start VM service listening for connections from the new CID on port=CID.
451 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
452 let port = cid;
453 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
454 .context(format!("Could not start RpcServer on port {port}"))
455 .or_service_specific_exception(-1)?;
456 vm_server.start();
457 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
458 } else {
459 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
460 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900461 }
462
David Brazdil209074a2023-01-12 16:44:51 +0000463 fn create_vm_context(
464 &self,
465 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900466 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000467 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000468 const NUM_ATTEMPTS: usize = 5;
469
470 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000471 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000472 let cid = vm_context.getCid()? as Cid;
473 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900474
475 // We don't need to start the VM service for custom VMs.
476 if !requires_vm_service(config) {
477 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
478 }
479
David Brazdil8cf8f482022-11-23 14:21:26 +0000480 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
481
482 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000483 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000484 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000485 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000486 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900487 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000488 }
489 Err(err) => {
490 warn!("Could not start RpcServer on port {}: {}", port, err);
491 }
492 }
493 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900494 Err(anyhow!("Too many attempts to create VM context failed"))
495 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000496 }
497
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000498 fn create_vm_internal(
499 &self,
500 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900501 console_out_fd: Option<&ParcelFileDescriptor>,
502 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000503 log_fd: Option<&ParcelFileDescriptor>,
504 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000505 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000506 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000507 let requester_uid = get_calling_uid();
508 let requester_debug_pid = get_calling_pid();
509
Nikita Ioffe631717e2023-09-05 13:38:07 +0100510 check_config_features(config)?;
511
Inseob Kimecde8c02024-09-03 13:11:08 +0900512 if cfg!(early) {
513 check_config_allowed_for_early_vms(config)?;
514 }
515
Nikita Ioffeb1416122024-10-22 12:18:49 +0000516 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
517 info!("callers secontext: {}", caller_secontext);
518
David Brazdil209074a2023-01-12 16:44:51 +0000519 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900520 let (vm_context, cid, temporary_directory) = if cfg!(early) {
521 self.create_early_vm_context(config)?
522 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900523 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900524 };
Inseob Kim1119d702022-05-02 18:01:58 +0900525
Alan Stokesfda70842023-12-20 17:50:14 +0000526 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100527 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900528 }
529
Nikita Ioffe5776f082023-02-10 21:38:26 +0000530 let gdb_port = extract_gdb_port(config);
531
532 // Additional permission checks if caller request gdb.
533 if gdb_port.is_some() {
534 check_gdb_allowed(config)?;
535 }
536
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000537 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900538
Jaewan Kimf3143242024-03-15 06:56:31 +0000539 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000540 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900541 Some(prepare_ramdump_file(&temporary_directory)?)
542 } else {
543 None
544 };
545
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000546 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900547 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100548 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900549 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100550 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100551 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
552 Some(clone_file(fd)?)
553 } else if debug_config.dump_device_tree {
554 Some(prepare_dump_dt_file(&temporary_directory)?)
555 } else {
556 None
557 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000558
559 // Counter to generate unique IDs for temporary image files.
560 let mut next_temporary_image_id = 0;
561 // Files which are referred to from composite images. These must be mapped to the crosvm
562 // child process, and not closed before it is started.
563 let mut indirect_files = vec![];
564
Alan Stokes7bc146c2022-10-20 17:10:32 +0100565 let (is_app_config, config) = match config {
566 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
567 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900568 let config = load_app_config(config, &debug_config, &temporary_directory)
569 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900570 *is_protected = config.protectedVm;
571 let message = format!("Failed to load app config: {:?}", e);
572 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900573 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900574 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100575 (true, BorrowedOrOwned::Owned(config))
576 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000577 };
578 let config = config.as_ref();
579 *is_protected = config.protectedVm;
580
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000581 if !config.teeServices.is_empty() {
582 check_tee_service_permission(&caller_secontext, &config.teeServices)
583 .with_log()
584 .or_binder_exception(ExceptionCode::SECURITY)?;
585 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000586
Jiyong Park3051ffe2024-11-26 14:41:58 +0900587 let kernel = maybe_clone_file(&config.kernel)?;
588 let initrd = maybe_clone_file(&config.initrd)?;
589
590 if config.protectedVm {
591 // Fail fast with a meaningful error message in case device doesn't support pVMs.
592 check_protected_vm_is_supported()?;
593
594 // In a protected VM, we require custom kernels to come from a trusted source
595 // (b/237054515).
596 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
597
598 // Check if partition images are labeled incorrectly. This is to prevent random images
599 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
600 // from being loaded in a pVM. This applies to everything but the instance image in the
601 // raw config, and everything but the non-executable, generated partitions in the app
602 // config.
603 config
604 .disks
605 .iter()
606 .flat_map(|disk| disk.partitions.iter())
607 .filter(|partition| {
608 if is_app_config {
609 !is_safe_app_partition(&partition.label)
610 } else {
611 !is_safe_raw_partition(&partition.label)
612 }
613 })
614 .try_for_each(check_label_for_partition)
615 .or_service_specific_exception(-1)?;
616 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000617
Inseob Kimff48a7c2024-02-26 22:07:21 +0900618 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
619 // have unstable interfaces.
620 // TODO(b/316431494): remove once Treble interfaces are stabilized.
621 check_partitions_for_files(config).or_service_specific_exception(-1)?;
622
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000623 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900624 write_zero_filler(&zero_filler_path)
625 .context("Failed to make composite image")
626 .with_log()
627 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000628
629 // Assemble disk images if needed.
630 let disks = config
631 .disks
632 .iter()
633 .map(|disk| {
634 assemble_disk_image(
635 disk,
636 &zero_filler_path,
637 &temporary_directory,
638 &mut next_temporary_image_id,
639 &mut indirect_files,
640 )
641 })
642 .collect::<Result<Vec<DiskFile>, _>>()?;
643
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700644 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
645
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000646 let (cpus, host_cpu_topology) = match config.cpuTopology {
647 CpuTopology::MATCH_HOST => (None, true),
648 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
649 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900650 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
651 .with_log()
652 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000653 }
654 };
655
David Brazdil2dfefd12023-11-17 14:07:36 +0000656 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900657 let mut set = HashSet::new();
658 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900659 let path = canonicalize(device)
660 .with_context(|| format!("can't canonicalize {device}"))
661 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900662 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900663 return Err(anyhow!("duplicated device {device}"))
664 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900665 }
666 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000667 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000668 let dtbo_file = File::from(
669 GLOBAL_SERVICE
670 .getDtboFile()?
671 .as_ref()
672 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900673 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000674 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
675 );
676 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900677 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000678 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900679 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900680 let display_config = if cfg!(paravirtualized_devices) {
681 config
682 .displayConfig
683 .as_ref()
684 .map(DisplayConfig::new)
685 .transpose()
686 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
687 } else {
688 None
689 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700690 let gpu_config = if cfg!(paravirtualized_devices) {
691 config
692 .gpuConfig
693 .as_ref()
694 .map(GpuConfig::new)
695 .transpose()
696 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
697 } else {
698 None
699 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900700
Jeongik Chac181be72024-03-27 00:18:30 +0900701 let input_device_options = if cfg!(paravirtualized_devices) {
702 config
703 .inputDevices
704 .iter()
705 .map(to_input_device_option_from)
706 .collect::<Result<Vec<InputDeviceOption>, _>>()
707 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
708 } else {
709 vec![]
710 };
711
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900712 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900713 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900714 if *is_protected {
715 return Err(anyhow!("Network feature is not supported for pVM yet"))
716 .with_log()
717 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
718 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900719 Some(File::from(
720 GLOBAL_SERVICE
721 .createTapInterface(&get_this_pid().to_string())?
722 .as_ref()
723 .try_clone()
724 .context("Failed to get TAP interface from ParcelFileDescriptor")
725 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
726 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900727 } else {
728 None
729 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800730
731 let audio_config = if cfg!(paravirtualized_devices) {
732 config.audioConfig.as_ref().map(AudioConfig::new)
733 } else {
734 None
735 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900736
Elie Kheirallah29d72912024-08-07 20:17:26 +0000737 let usb_config = config
738 .usbConfig
739 .as_ref()
740 .map(UsbConfig::new)
741 .unwrap_or(Ok(UsbConfig { controller: false }))
742 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
743
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000744 // Actually start the VM.
745 let crosvm_config = CrosvmConfig {
746 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000747 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000748 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000749 kernel,
750 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000751 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700752 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000753 params: config.params.to_owned(),
754 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900755 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700756 memory_mib: config
757 .memoryMib
758 .try_into()
759 .ok()
760 .and_then(NonZeroU32::new)
761 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000762 cpus,
763 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900764 console_out_fd,
765 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000766 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900767 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000768 indirect_files,
769 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900770 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000771 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900772 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000773 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000774 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900775 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900776 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000777 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900778 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800779 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000780 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700781 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800782 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900783 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000784 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000785 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000786 };
787 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100788 VmInstance::new(
789 crosvm_config,
790 temporary_directory,
791 requester_uid,
792 requester_debug_pid,
793 vm_context,
794 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900795 .with_context(|| format!("Failed to create VM with config {:?}", config))
796 .with_log()
797 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000798 );
799 state.add_vm(Arc::downgrade(&instance));
800 Ok(VirtualMachine::create(instance))
801 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900802}
803
Alan Stokesfda70842023-12-20 17:50:14 +0000804/// Returns whether a VM config represents a "custom" virtual machine, which requires the
805/// USE_CUSTOM_VIRTUAL_MACHINE.
806fn is_custom_config(config: &VirtualMachineConfig) -> bool {
807 match config {
808 // Any raw (non-Microdroid) VM is considered custom.
809 VirtualMachineConfig::RawConfig(_) => true,
810 VirtualMachineConfig::AppConfig(config) => {
811 // Some features are reserved for platform apps only, even when using
812 // VirtualMachineAppConfig. Almost all of these features are grouped in the
813 // CustomConfig struct:
814 // - controlling CPUs;
815 // - gdbPort is set, meaning that crosvm will start a gdb server;
816 // - using anything other than the default kernel;
817 // - specifying devices to be assigned.
818 if config.customConfig.is_some() {
819 true
820 } else {
821 // Additional custom features not included in CustomConfig:
822 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000823 // - specifying extra APKs;
824 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900825 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000826 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900827 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
828 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000829 }
830 }
831 }
832}
833
Jiyong Park690c1ca2024-11-28 18:06:50 +0900834/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
835/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
836/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
837/// "microdroid" we run VirtualMachineService
838fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
839 match config {
840 VirtualMachineConfig::AppConfig(_) => true,
841 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
842 }
843}
844
Seungjae Yoo14e60182024-02-21 13:28:31 +0900845fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
846 let VirtualMachineConfig::AppConfig(config) = config else {
847 return Ok(None);
848 };
849 let Some(custom_config) = &config.customConfig else {
850 return Ok(None);
851 };
852 let Some(file) = custom_config.vendorImage.as_ref() else {
853 return Ok(None);
854 };
855
856 let file = clone_file(file)?;
857 let size =
858 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
859 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
860 .context("Failed to get vbmeta from microdroid-vendor.img")?;
861
862 for descriptor in vbmeta.descriptors()?.iter() {
863 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
864 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
865 return Ok(Some(root_digest.as_bytes().to_vec()));
866 }
867 }
868 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
869}
870
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000871fn maybe_create_device_tree_overlay(
872 config: &VirtualMachineConfig,
873 temporary_directory: &Path,
874) -> binder::Result<Option<File>> {
875 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
876 // (e.g. instance-id)
877 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
878 let host_ref_dt = if host_ref_dt.exists()
879 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
880 {
881 Some(host_ref_dt)
882 } else {
883 warn!("VM reference DT doesn't exist in host DT");
884 None
885 };
886
887 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
888 .context("Failed to extract vendor hashtree digest")
889 .or_service_specific_exception(-1)?;
890
891 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
892 info!(
893 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
894 match the trusted digest in the pvmfw config, causing the VM to fail to start."
895 );
896 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
897 } else {
898 vec![]
899 };
900
901 let instance_id;
902 let mut untrusted_props = Vec::with_capacity(2);
903 if cfg!(llpvm_changes) {
904 instance_id = extract_instance_id(config);
905 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
906 let want_updatable = extract_want_updatable(config);
907 if want_updatable && is_secretkeeper_supported() {
908 // Let guest know that it can defer rollback protection to Secretkeeper by setting
909 // an empty property in untrusted node in DT. This enables Updatable VMs.
910 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
911 }
912 }
913
914 let device_tree_overlay = if host_ref_dt.is_some()
915 || !untrusted_props.is_empty()
916 || !trusted_props.is_empty()
917 {
918 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
919 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
920 let fdt =
921 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
922 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
923 .or_service_specific_exception(-1)?;
924 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
925 Some(File::open(dt_output).or_service_specific_exception(-1)?)
926 } else {
927 None
928 };
929 Ok(device_tree_overlay)
930}
931
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000932fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900933 let file = OpenOptions::new()
934 .create_new(true)
935 .read(true)
936 .write(true)
937 .open(zero_filler_path)
938 .with_context(|| "Failed to create zero.img")?;
939 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000940 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900941}
942
David Brazdilf50c7a62023-04-19 14:22:42 +0000943fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
944 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
945 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
946 part.flush()
947}
948
949fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
950 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
951 part.flush()
952}
953
954fn round_up(input: u64, granularity: u64) -> u64 {
955 if granularity == 0 {
956 return input;
957 }
958 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
959 let result = input.checked_add(granularity - 1).unwrap_or(input);
960 (result / granularity) * granularity
961}
962
Jeongik Chac181be72024-03-27 00:18:30 +0900963fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
964 Ok(match input_device {
965 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
966 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
967 height: u32::try_from(single_touch.height)?,
968 width: u32::try_from(single_touch.width)?,
969 name: if !single_touch.name.is_empty() {
970 Some(single_touch.name.clone())
971 } else {
972 None
973 },
974 },
975 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
976 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
977 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900978 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
979 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
980 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900981 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
982 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
983 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900984 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
985 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
986 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900987 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
988 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
989 height: u32::try_from(trackpad.height)?,
990 width: u32::try_from(trackpad.width)?,
991 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
992 },
Jeongik Cha10494912024-07-16 11:19:50 +0900993 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
994 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
995 height: u32::try_from(multi_touch.height)?,
996 width: u32::try_from(multi_touch.width)?,
997 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
998 },
Jeongik Chac181be72024-03-27 00:18:30 +0900999 })
1000}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001001
1002fn assemble_shared_paths(
1003 shared_paths: &[SharedPath],
1004 temporary_directory: &Path,
1005) -> Result<Vec<SharedPathConfig>, Status> {
1006 if shared_paths.is_empty() {
1007 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1008 }
1009
1010 shared_paths
1011 .iter()
1012 .map(|path| {
1013 Ok(SharedPathConfig {
1014 path: path.sharedPath.clone(),
1015 host_uid: path.hostUid,
1016 host_gid: path.hostGid,
1017 guest_uid: path.guestUid,
1018 guest_gid: path.guestGid,
1019 mask: path.mask,
1020 tag: path.tag.clone(),
1021 socket_path: temporary_directory.join(&path.socket).to_string_lossy().to_string(),
1022 })
1023 })
1024 .collect()
1025}
1026
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001027/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1028///
1029/// This may involve assembling a composite disk from a set of partition images.
1030fn assemble_disk_image(
1031 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001032 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001033 temporary_directory: &Path,
1034 next_temporary_image_id: &mut u64,
1035 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001036) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001037 let image = if !disk.partitions.is_empty() {
1038 if disk.image.is_some() {
1039 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001040 return Err(anyhow!("DiskImage contains both image and partitions"))
1041 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001042 }
1043
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001044 let composite_image_filenames =
1045 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1046 let (image, partition_files) = make_composite_image(
1047 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001048 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001049 &composite_image_filenames.composite,
1050 &composite_image_filenames.header,
1051 &composite_image_filenames.footer,
1052 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001053 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1054 .with_log()
1055 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001056
1057 // Pass the file descriptors for the various partition files to crosvm when it
1058 // is run.
1059 indirect_files.extend(partition_files);
1060
1061 image
1062 } else if let Some(image) = &disk.image {
1063 clone_file(image)?
1064 } else {
1065 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001066 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1067 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001068 };
1069
1070 Ok(DiskFile { image, writable: disk.writable })
1071}
1072
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001073fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1074 if let Some(ref mut params) = vm_config.params {
1075 params.push(' ');
1076 params.push_str(param)
1077 } else {
1078 vm_config.params = Some(param.to_owned())
1079 }
1080}
1081
Inseob Kim46257382024-01-03 15:41:22 +09001082fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1083 if config.extension()?.to_str()? != "json" {
1084 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001085 }
Inseob Kim46257382024-01-03 15:41:22 +09001086
1087 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1088}
1089
1090fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1091 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1092 let os_names =
1093 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1094
1095 Ok(os_names)
1096}
1097
1098fn get_supported_os_names() -> Result<HashSet<String>> {
1099 if !cfg!(vendor_modules) {
1100 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1101 }
1102
1103 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1104}
1105
1106fn is_valid_os(os_name: &str) -> bool {
1107 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001108}
1109
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001110fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1111 if !cfg!(vendor_modules) {
1112 return false;
1113 }
1114 match config {
1115 VirtualMachineConfig::RawConfig(_) => false,
1116 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1117 }
1118}
1119
Jooyung Han21e9b922021-06-26 04:14:16 +09001120fn load_app_config(
1121 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001122 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001123 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001124) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001125 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1126 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001127 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001128
Shikha Panwar22e70452022-10-10 18:32:55 +00001129 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1130 Some(clone_file(file)?)
1131 } else {
1132 None
1133 };
1134
Alan Stokesfda70842023-12-20 17:50:14 +00001135 let vm_payload_config;
1136 let extra_apk_files: Vec<_>;
1137 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001138 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001139 vm_payload_config =
1140 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1141 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1142 extra_apk_files = vm_payload_config
1143 .extra_apks
1144 .iter()
1145 .enumerate()
1146 .map(|(i, apk)| {
1147 File::open(PathBuf::from(&apk.path))
1148 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1149 })
1150 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001151 }
Alan Stokesfda70842023-12-20 17:50:14 +00001152 Payload::PayloadConfig(payload_config) => {
1153 vm_payload_config = create_vm_payload_config(payload_config)?;
1154 extra_apk_files =
1155 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1156 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001157 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001158
Inseob Kim89b24592024-02-23 18:59:43 +09001159 let payload_config_os = vm_payload_config.os.name.as_str();
1160 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1161 bail!("'os' in payload config is deprecated");
1162 }
1163
Inseob Kim172f9eb2023-11-06 17:02:08 +09001164 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001165 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001166 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001167 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001168 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001169
1170 // It is safe to construct a filename based on the os_name because we've already checked that it
1171 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001172 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1173 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001174 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001175
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001176 if let Some(custom_config) = &config.customConfig {
1177 if let Some(file) = custom_config.customKernelImage.as_ref() {
1178 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1179 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001180 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001181
1182 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001183 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001184 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001185 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001186
Chris Wailes6177c662024-05-09 14:37:44 -07001187 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001188 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001189
1190 for param in custom_config.extraKernelCmdlineParams.iter() {
1191 append_kernel_param(param, &mut vm_config);
1192 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001193
1194 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001195 }
1196
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001197 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1198 // so we need to provide it in the kernel cmdline.
1199 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1200 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1201 append_kernel_param("page_shift=14", &mut vm_config);
1202 }
1203
Andrew Walbrancc045902021-07-27 16:06:17 +00001204 if config.memoryMib > 0 {
1205 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001206 }
1207
Chris Wailes6177c662024-05-09 14:37:44 -07001208 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001209 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001210 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001211 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001212 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001213
Shikha Panwar22e70452022-10-10 18:32:55 +00001214 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001215 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001216
1217 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1218 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001219 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001220 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001221 temporary_directory,
1222 apk_file,
1223 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001224 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001225 &vm_payload_config,
1226 &mut vm_config,
1227 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001228
Andrew Walbrancc0db522021-07-12 17:03:42 +00001229 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001230}
1231
Inseob Kimff48a7c2024-02-26 22:07:21 +09001232fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1233 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1234 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1235
1236 // microdroid vendor image is OK
1237 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1238 {
1239 return Ok(());
1240 }
1241
1242 if link.starts_with("/vendor") || link.starts_with("/odm") {
1243 bail!("vendor or odm file {} can't be used for VM", link.display());
1244 }
1245
1246 Ok(())
1247}
1248
1249fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1250 config
1251 .disks
1252 .iter()
1253 .flat_map(|disk| disk.partitions.iter())
1254 .filter_map(|partition| partition.image.as_ref())
1255 .try_for_each(check_partition_for_file)?;
1256
1257 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1258 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1259 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1260
1261 Ok(())
1262}
1263
Alan Stokes0d1ef782022-09-27 13:46:35 +01001264fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1265 let mut apk_zip = ZipArchive::new(apk_file)?;
1266 let config_file = apk_zip.by_name(config_path)?;
1267 Ok(serde_json::from_reader(config_file)?)
1268}
1269
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001270fn create_vm_payload_config(
1271 payload_config: &VirtualMachinePayloadConfig,
1272) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001273 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1274 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1275 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001276
1277 let payload_binary_name = &payload_config.payloadBinaryName;
1278 if payload_binary_name.contains('/') {
1279 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1280 }
1281
1282 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001283
1284 // The VM only cares about how many there are, these names are actually ignored.
1285 let extra_apk_count = payload_config.extraApks.len();
1286 let extra_apks =
1287 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1288
Inseob Kim89b24592024-02-23 18:59:43 +09001289 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001290}
1291
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001292/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001293fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001294 temporary_directory: &Path,
1295 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001296) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001297 let id = *next_temporary_image_id;
1298 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001299 CompositeImageFilenames {
1300 composite: temporary_directory.join(format!("composite-{}.img", id)),
1301 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1302 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1303 }
1304}
1305
1306/// Filenames for a composite disk image, including header and footer partitions.
1307#[derive(Clone, Debug, Eq, PartialEq)]
1308struct CompositeImageFilenames {
1309 /// The composite disk image itself.
1310 composite: PathBuf,
1311 /// The header partition image.
1312 header: PathBuf,
1313 /// The footer partition image.
1314 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001315}
1316
Jiyong Park753553b2021-07-12 21:21:09 +09001317/// Checks whether the caller has a specific permission
1318fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001319 if cfg!(early) {
1320 // Skip permission check for early VMs, in favor of SELinux
1321 return Ok(());
1322 }
David Brazdil1f530702022-10-03 12:18:10 +01001323 let calling_pid = get_calling_pid();
1324 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001325 // Root can do anything
1326 if calling_uid == 0 {
1327 return Ok(());
1328 }
1329 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001330 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001331 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001332 Ok(())
1333 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001334 Err(anyhow!("does not have the {} permission", perm))
1335 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001336 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001337}
1338
Jiyong Park753553b2021-07-12 21:21:09 +09001339/// Check whether the caller of the current Binder method is allowed to manage VMs
1340fn check_manage_access() -> binder::Result<()> {
1341 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1342}
1343
Inseob Kim1119d702022-05-02 18:01:58 +09001344/// Check whether the caller of the current Binder method is allowed to create custom VMs
1345fn check_use_custom_virtual_machine() -> binder::Result<()> {
1346 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1347}
1348
Alan Stokes185fe112023-01-10 16:20:55 +00001349/// Return whether a partition is exempt from selinux label checks, because we know that it does
1350/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001351fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001352 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001353 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001354 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001355 || label == "microdroid-apk-idsig"
1356 || label == "payload-metadata"
1357 || label.starts_with("extra-idsig-")
1358}
1359
Alice Wangc206b9b2023-08-28 14:13:51 +00001360/// Returns whether a partition with the given label is safe for a raw config VM.
1361fn is_safe_raw_partition(label: &str) -> bool {
1362 label == "vm-instance"
1363}
1364
Alan Stokes185fe112023-01-10 16:20:55 +00001365/// Check that a file SELinux label is acceptable.
1366///
1367/// 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 +09001368/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001369///
1370/// Note that sepolicy must also grant read access for these types to both virtualization
1371/// service and crosvm.
1372///
1373/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1374/// user devices (W^X).
1375fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1376 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001377 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001378 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001379 | "staging_data_file" // updated/staged APEX images
1380 | "system_file" // immutable dm-verity protected partition
1381 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001382 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001383 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001384 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001385 }
1386}
1387
Alan Stokes185fe112023-01-10 16:20:55 +00001388fn check_label_for_partition(partition: &Partition) -> Result<()> {
1389 let file = partition.image.as_ref().unwrap().as_ref();
1390 check_label_is_allowed(&getfilecon(file)?)
1391 .with_context(|| format!("Partition {} invalid", &partition.label))
1392}
1393
1394fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1395 if let Some(f) = kernel {
1396 check_label_for_file(f, "kernel")?;
1397 }
1398 if let Some(f) = initrd {
1399 check_label_for_file(f, "initrd")?;
1400 }
1401 Ok(())
1402}
1403fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1404 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1405}
1406
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001407/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1408#[derive(Debug)]
1409struct VirtualMachine {
1410 instance: Arc<VmInstance>,
1411}
1412
1413impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001414 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001415 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001416 }
1417}
1418
1419impl Interface for VirtualMachine {}
1420
Devin Moore407df8f2024-08-27 19:39:16 +00001421impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001422 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001423 // Don't check permission. The owner of the VM might have passed this binder object to
1424 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001425 Ok(self.instance.cid as i32)
1426 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001427
Andrew Walbran6b650662021-09-07 13:13:23 +00001428 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001429 // Don't check permission. The owner of the VM might have passed this binder object to
1430 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001431 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001432 }
1433
1434 fn registerCallback(
1435 &self,
1436 callback: &Strong<dyn IVirtualMachineCallback>,
1437 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001438 // Don't check permission. The owner of the VM might have passed this binder object to
1439 // others.
1440 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001441 // TODO: Should this give an error if the VM is already dead?
1442 self.instance.callbacks.add(callback.clone());
1443 Ok(())
1444 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001445
Andrew Walbranf8d94112021-09-07 11:45:36 +00001446 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001447 self.instance
1448 .start()
1449 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1450 .with_log()
1451 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001452 }
1453
Inseob Kima446f802022-07-11 19:46:37 +09001454 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001455 self.instance
1456 .kill()
1457 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1458 .with_log()
1459 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001460 }
1461
Keir Fraser48221ba2024-07-12 14:05:02 +00001462 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1463 let balloon = self
1464 .instance
1465 .get_memory_balloon()
1466 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1467 .with_log()
1468 .or_service_specific_exception(-1)?;
1469 Ok(balloon.try_into().unwrap())
1470 }
1471
1472 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001473 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001474 .set_memory_balloon(num_bytes.try_into().unwrap())
1475 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001476 .with_log()
1477 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001478 }
1479
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001480 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001481 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001482 return Err(Status::new_service_specific_error_str(
1483 IVirtualMachine::ERROR_UNEXPECTED,
1484 Some("Virtual Machine is not running"),
1485 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001486 }
Alan Stokes10c47672022-12-13 17:17:08 +00001487 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001488 if port < VSOCK_PRIV_PORT_MAX {
1489 return Err(Status::new_service_specific_error_str(
1490 IVirtualMachine::ERROR_UNEXPECTED,
1491 Some("Can't connect to privileged port {port}"),
1492 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001493 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001494 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1495 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001496 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001497 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001498 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001499
Devin Moore407df8f2024-08-27 19:39:16 +00001500 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1501 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1502 return Err(Status::new_service_specific_error_str(
1503 IVirtualMachine::ERROR_UNEXPECTED,
1504 Some("Virtual Machine is not running"),
1505 ));
1506 }
1507 let port = port as u32;
1508 if port < VSOCK_PRIV_PORT_MAX {
1509 return Err(Status::new_service_specific_error_str(
1510 IVirtualMachine::ERROR_UNEXPECTED,
1511 Some("Can't connect to privileged port {port}"),
1512 ));
1513 }
1514 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001515 let addr = sockaddr_vm {
1516 svm_family: AF_VSOCK as sa_family_t,
1517 svm_reserved1: 0,
1518 svm_port: port,
1519 svm_cid: cid,
1520 svm_zero: [0u8; 4],
1521 };
1522 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001523 let accessor = Accessor::new(name, get_connection_info);
1524 accessor
1525 .as_binder()
1526 .context("The newly created Accessor should always have a binder")
1527 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1528 }
1529
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001530 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1531 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1532 }
Jiyong Park23b67392024-07-04 13:51:42 +09001533
1534 fn suspend(&self) -> binder::Result<()> {
1535 self.instance
1536 .suspend()
1537 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1538 .with_log()
1539 .or_service_specific_exception(-1)
1540 }
1541
1542 fn resume(&self) -> binder::Result<()> {
1543 self.instance
1544 .resume()
1545 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1546 .with_log()
1547 .or_service_specific_exception(-1)
1548 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001549}
1550
1551impl Drop for VirtualMachine {
1552 fn drop(&mut self) {
1553 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001554 if let Err(e) = self.instance.kill() {
1555 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1556 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001557 }
1558}
1559
1560/// A set of Binders to be called back in response to various events on the VM, such as when it
1561/// dies.
1562#[derive(Debug, Default)]
1563pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1564
1565impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001566 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001567 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001568 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001569 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001570 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001571 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001572 }
1573 }
1574 }
1575
Inseob Kim14cb8692021-08-31 21:50:39 +09001576 /// Call all registered callbacks to notify that the payload is ready to serve.
1577 pub fn notify_payload_ready(&self, cid: Cid) {
1578 let callbacks = &*self.0.lock().unwrap();
1579 for callback in callbacks {
1580 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001581 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001582 }
1583 }
1584 }
1585
Inseob Kim2444af92021-08-31 01:22:50 +09001586 /// Call all registered callbacks to notify that the payload has finished.
1587 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1588 let callbacks = &*self.0.lock().unwrap();
1589 for callback in callbacks {
1590 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001591 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001592 }
1593 }
1594 }
1595
Jooyung Handd0a1732021-11-23 15:26:20 +09001596 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001597 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001598 let callbacks = &*self.0.lock().unwrap();
1599 for callback in callbacks {
1600 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001601 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001602 }
1603 }
1604 }
1605
Andrew Walbrandae07162021-03-12 17:05:20 +00001606 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001607 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001608 let callbacks = &*self.0.lock().unwrap();
1609 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001610 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001611 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001612 }
1613 }
1614 }
1615
1616 /// Add a new callback to the set.
1617 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1618 self.0.lock().unwrap().push(callback);
1619 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001620}
1621
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001622/// The mutable state of the VirtualizationService. There should only be one instance of this
1623/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001624#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001625struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001626 /// The VMs which have been started. When VMs are started a weak reference is added to this
1627 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1628 /// the Binder client are dropped the weak reference here will become invalid, and will be
1629 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001630 vms: Vec<Weak<VmInstance>>,
1631}
1632
1633impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001634 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001635 fn vms(&self) -> Vec<Arc<VmInstance>> {
1636 // Attempt to upgrade the weak pointers to strong pointers.
1637 self.vms.iter().filter_map(Weak::upgrade).collect()
1638 }
1639
1640 /// Add a new VM to the list.
1641 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1642 // Garbage collect any entries from the stored list which no longer exist.
1643 self.vms.retain(|vm| vm.strong_count() > 0);
1644
1645 // Actually add the new VM.
1646 self.vms.push(vm);
1647 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001648
Jiyong Park8611a6c2021-07-09 18:17:44 +09001649 /// Get a VM that corresponds to the given cid
1650 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1651 self.vms().into_iter().find(|vm| vm.cid == cid)
1652 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001653}
1654
Andrew Walbran6b650662021-09-07 13:13:23 +00001655/// Gets the `VirtualMachineState` of the given `VmInstance`.
1656fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001657 match &*instance.vm_state.lock().unwrap() {
1658 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1659 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001660 PayloadState::Starting => VirtualMachineState::STARTING,
1661 PayloadState::Started => VirtualMachineState::STARTED,
1662 PayloadState::Ready => VirtualMachineState::READY,
1663 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001664 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001665 },
1666 VmState::Dead => VirtualMachineState::DEAD,
1667 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001668 }
1669}
1670
David Brazdilf50c7a62023-04-19 14:22:42 +00001671/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001672pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1673 file.as_ref()
1674 .try_clone()
1675 .context("Failed to clone File from ParcelFileDescriptor")
1676 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001677 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001678}
1679
Andrew Walbrand3a84182021-09-07 14:48:52 +00001680/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001681fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001682 file.as_ref().map(clone_file).transpose()
1683}
1684
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001685/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001686fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1687 // SAFETY: ownership is transferred from stream to f
1688 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1689 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001690}
1691
Jiyong Parkdcf17412022-02-08 15:07:23 +09001692/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001693fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1694 VersionReq::parse(s)
1695 .with_context(|| format!("Invalid platform version requirement {}", s))
1696 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001697}
1698
Jiyong Parked180932023-02-24 19:55:41 +09001699/// Create the empty ramdump file
1700fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1701 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1702 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1703 // owner) for readout.
1704 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001705 let ramdump = File::create(ramdump_path)
1706 .context("Failed to prepare ramdump file")
1707 .with_log()
1708 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001709 Ok(ramdump)
1710}
1711
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001712/// Create the empty device tree dump file
1713fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1714 let path = temporary_directory.join("device_tree.dtb");
1715 let file = File::create(path)
1716 .context("Failed to prepare device tree dump file")
1717 .with_log()
1718 .or_service_specific_exception(-1)?;
1719 Ok(file)
1720}
1721
Nikita Ioffe5776f082023-02-10 21:38:26 +00001722fn is_protected(config: &VirtualMachineConfig) -> bool {
1723 match config {
1724 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1725 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1726 }
1727}
1728
1729fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1730 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001731 return Err(anyhow!("Can't use gdb with protected VMs"))
1732 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001733 }
1734
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001735 if get_debug_level(config) == Some(DebugLevel::NONE) {
1736 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1737 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001738 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001739
1740 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001741}
1742
Shikha Panwar61a74b52024-02-16 13:17:01 +00001743fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1744 match config {
1745 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1746 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1747 }
1748}
1749
Alan Stokesc96b35e2024-05-03 13:21:20 +01001750fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1751 match config {
1752 VirtualMachineConfig::RawConfig(_) => true,
1753 VirtualMachineConfig::AppConfig(config) => {
1754 let Some(custom) = &config.customConfig else { return true };
1755 custom.wantUpdatable
1756 }
1757 }
1758}
1759
Nikita Ioffe5776f082023-02-10 21:38:26 +00001760fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1761 match config {
1762 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001763 VirtualMachineConfig::AppConfig(config) => {
1764 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1765 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001766 }
1767}
1768
Nikita Ioffe631717e2023-09-05 13:38:07 +01001769fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1770 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1771 if let Some(custom_config) = &config.customConfig {
1772 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1773 return Err(anyhow!("vendor modules feature is disabled"))
1774 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1775 }
1776 }
1777 Ok(())
1778}
1779
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001780fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1781 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1782 if let Some(custom_config) = &config.customConfig {
1783 if !custom_config.devices.is_empty() {
1784 return Err(anyhow!("device assignment feature is disabled"))
1785 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1786 }
1787 }
1788 Ok(())
1789}
1790
Alan Stokesfda70842023-12-20 17:50:14 +00001791fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1792 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1793 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1794 if !payload_config.extraApks.is_empty() {
1795 return Err(anyhow!("multi-tenant feature is disabled"))
1796 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1797 }
1798 Ok(())
1799}
1800
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001801fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1802 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1803 if let Some(custom_config) = &config.customConfig {
1804 if !custom_config.extraKernelCmdlineParams.is_empty() {
1805 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1806 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1807 }
1808 }
1809 Ok(())
1810}
1811
Nikita Ioffe99548382024-10-21 15:54:46 +00001812fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1813 match config {
1814 VirtualMachineConfig::RawConfig(config) => {
1815 if !config.teeServices.is_empty() {
1816 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1817 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1818 }
1819 }
1820 VirtualMachineConfig::AppConfig(config) => {
1821 if let Some(custom_config) = &config.customConfig {
1822 if !custom_config.teeServices.is_empty() {
1823 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1824 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1825 }
1826 }
1827 }
1828 };
1829 Ok(())
1830}
1831
Nikita Ioffef934e812024-07-05 15:44:41 +00001832fn check_protected_vm_is_supported() -> binder::Result<()> {
1833 let is_pvm_supported =
1834 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1835 if is_pvm_supported {
1836 Ok(())
1837 } else {
1838 Err(anyhow!("pVM is not supported"))
1839 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1840 }
1841}
1842
Nikita Ioffe631717e2023-09-05 13:38:07 +01001843fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1844 if !cfg!(vendor_modules) {
1845 check_no_vendor_modules(config)?;
1846 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001847 if !cfg!(device_assignment) {
1848 check_no_devices(config)?;
1849 }
Alan Stokesfda70842023-12-20 17:50:14 +00001850 if !cfg!(multi_tenant) {
1851 check_no_extra_apks(config)?;
1852 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001853 if !cfg!(debuggable_vms_improvements) {
1854 check_no_extra_kernel_cmdline_params(config)?;
1855 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001856 if !cfg!(tee_services_allowlist) {
1857 check_no_tee_services(config)?;
1858 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001859 Ok(())
1860}
1861
Inseob Kimecde8c02024-09-03 13:11:08 +09001862fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1863 check_no_vendor_modules(config)?;
1864 check_no_devices(config)?;
1865
1866 Ok(())
1867}
1868
Inseob Kim0168b462022-12-27 14:54:35 +09001869fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001870 fd: Option<&ParcelFileDescriptor>,
1871 tag: String,
1872) -> Result<Option<File>, Status> {
1873 if let Some(fd) = fd {
1874 return Ok(Some(clone_file(fd)?));
1875 }
1876
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001877 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001878 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001879
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001880 let mut reader = BufReader::new(File::from(read_fd));
1881 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001882
1883 std::thread::spawn(move || loop {
1884 let mut buf = vec![];
1885 match reader.read_until(b'\n', &mut buf) {
1886 Ok(0) => {
1887 // EOF
1888 return;
1889 }
1890 Ok(size) => {
1891 if buf[size - 1] == b'\n' {
1892 buf.pop();
1893 }
1894 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1895 }
1896 Err(e) => {
1897 error!("Could not read console pipe: {:?}", e);
1898 return;
1899 }
1900 };
1901 });
1902
1903 Ok(Some(write_fd))
1904}
1905
Jooyung Han35edb8f2021-07-01 16:17:16 +09001906/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1907/// it doesn't require that T implements Clone.
1908enum BorrowedOrOwned<'a, T> {
1909 Borrowed(&'a T),
1910 Owned(T),
1911}
1912
1913impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1914 fn as_ref(&self) -> &T {
1915 match self {
1916 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001917 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001918 }
1919 }
1920}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001921
1922/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1923#[derive(Debug, Default)]
1924struct VirtualMachineService {
1925 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001926 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001927}
1928
1929impl Interface for VirtualMachineService {}
1930
1931impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001932 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1933 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001934 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001935 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001936 vm.update_payload_state(PayloadState::Started)
1937 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001938 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001939
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001940 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1941 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001942 Ok(())
1943 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001944 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001945 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001946 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001947 }
Inseob Kim2444af92021-08-31 01:22:50 +09001948
Inseob Kimc7d28c72021-10-25 14:28:10 +00001949 fn notifyPayloadReady(&self) -> binder::Result<()> {
1950 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001951 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001952 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001953 vm.update_payload_state(PayloadState::Ready)
1954 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001955 vm.callbacks.notify_payload_ready(cid);
1956 Ok(())
1957 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001958 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001959 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001960 }
1961 }
1962
Inseob Kimc7d28c72021-10-25 14:28:10 +00001963 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1964 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001965 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001966 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001967 vm.update_payload_state(PayloadState::Finished)
1968 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001969 vm.callbacks.notify_payload_finished(cid, exit_code);
1970 Ok(())
1971 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001972 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001973 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001974 }
1975 }
1976
Alan Stokes2bead0d2022-09-05 16:58:34 +01001977 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001978 let cid = self.cid;
1979 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001980 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001981 vm.update_payload_state(PayloadState::Finished)
1982 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001983 vm.callbacks.notify_error(cid, error_code, message);
1984 Ok(())
1985 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001986 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001987 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001988 }
1989 }
Alice Wangc2fec932023-02-23 16:24:02 +00001990
Shikha Panware45e9422024-02-28 21:18:10 +00001991 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1992 if !is_secretkeeper_supported() {
1993 return Err(StatusCode::NAME_NOT_FOUND)?;
1994 }
1995 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1996 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001997 }
1998
Alice Wange64dd182024-01-17 15:57:55 +00001999 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2000 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002001 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002002}
2003
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002004fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002005 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2006 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002007}
2008
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002009impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002010 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002011 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002012 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002013 BinderFeatures::default(),
2014 )
2015 }
2016}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002017
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002018struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2019
2020impl Interface for SecretkeeperProxy {}
2021
2022impl ISecretkeeper for SecretkeeperProxy {
2023 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2024 // Pass the request to the channel, and read the response.
2025 self.0.processSecretManagementRequest(req)
2026 }
2027
2028 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2029 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2030 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2031 }
2032
2033 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2034 self.0.deleteIds(ids)
2035 }
2036
2037 fn deleteAll(&self) -> binder::Result<()> {
2038 self.0.deleteAll()
2039 }
2040}
2041
2042struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2043
2044impl Interface for AuthGraphKeyExchangeProxy {}
2045
2046impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2047 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2048 self.0.create()
2049 }
2050
2051 fn init(
2052 &self,
2053 peer_pub_key: &PubKey,
2054 peer_id: &Identity,
2055 peer_nonce: &[u8],
2056 peer_version: i32,
2057 ) -> binder::Result<KeInitResult> {
2058 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2059 }
2060
2061 fn finish(
2062 &self,
2063 peer_pub_key: &PubKey,
2064 peer_id: &Identity,
2065 peer_signature: &SessionIdSignature,
2066 peer_nonce: &[u8],
2067 peer_version: i32,
2068 own_key: &Key,
2069 ) -> binder::Result<SessionInfo> {
2070 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2071 }
2072
2073 fn authenticationComplete(
2074 &self,
2075 peer_signature: &SessionIdSignature,
2076 shared_keys: &[AuthgraphArc; 2],
2077 ) -> binder::Result<[AuthgraphArc; 2]> {
2078 self.0.authenticationComplete(peer_signature, shared_keys)
2079 }
2080}
2081
Inseob Kimecde8c02024-09-03 13:11:08 +09002082// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002083#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002084struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002085 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002086 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002087 path: String,
2088}
2089
2090#[derive(Debug, Default, Deserialize)]
2091struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002092 early_vm: Vec<EarlyVm>,
2093}
2094
Inseob Kim7e1877b2024-11-07 17:28:56 +09002095static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2096 LazyLock::new(|| Mutex::new(HashMap::new()));
2097
Inseob Kimecde8c02024-09-03 13:11:08 +09002098fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2099 match partition {
2100 "system" => Ok(100..200),
2101 "system_ext" | "product" => Ok(200..300),
2102 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2103 }
2104}
2105
Inseob Kim7e1877b2024-11-07 17:28:56 +09002106fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002107 if !xml_path.exists() {
2108 bail!("{} doesn't exist", xml_path.display());
2109 }
2110
2111 let xml =
2112 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2113 let xml = String::from_utf8(xml)
2114 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2115 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2116 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2117
Inseob Kim7e1877b2024-11-07 17:28:56 +09002118 Ok(early_vms.early_vm)
2119}
Inseob Kimecde8c02024-09-03 13:11:08 +09002120
Inseob Kim7e1877b2024-11-07 17:28:56 +09002121fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2122 for early_vm in early_vms {
2123 let cid = early_vm
2124 .cid
2125 .try_into()
2126 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2127
2128 ensure!(
2129 cid_range.contains(&cid),
2130 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2131 early_vm.name
2132 );
2133 }
2134 Ok(())
2135}
2136
2137fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2138 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2139
2140 if let Some(result) = cache.get(partition) {
2141 return Ok(result.clone());
2142 }
2143
2144 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2145 let mut early_vms = Vec::new();
2146 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2147 match entry {
2148 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2149 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2150 }
2151 }
2152
2153 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2154 .with_context(|| format!("CID validation for {partition} failed"))?;
2155
2156 cache.insert(partition.to_owned(), early_vms.clone());
2157
2158 Ok(early_vms)
2159}
2160
2161fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2162 let mut found_vm: Option<&EarlyVm> = None;
2163
2164 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002165 if early_vm.name != name {
2166 continue;
2167 }
2168
Inseob Kimecde8c02024-09-03 13:11:08 +09002169 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002170 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002171 }
2172
2173 found_vm = Some(early_vm);
2174 }
2175
Inseob Kim7e1877b2024-11-07 17:28:56 +09002176 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002177}
2178
2179fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002180 let early_vms = get_early_vms_in_partition(partition)
2181 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2182
2183 Ok(find_early_vm(&early_vms, name)
2184 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2185 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002186}
2187
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002188#[cfg(test)]
2189mod tests {
2190 use super::*;
2191
2192 #[test]
2193 fn test_is_allowed_label_for_partition() -> Result<()> {
2194 let expected_results = vec![
2195 ("u:object_r:system_file:s0", true),
2196 ("u:object_r:apk_data_file:s0", true),
2197 ("u:object_r:app_data_file:s0", false),
2198 ("u:object_r:app_data_file:s0:c512,c768", false),
2199 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2200 ("invalid", false),
2201 ("user:role:apk_data_file:severity:categories", true),
2202 ("user:role:apk_data_file:severity:categories:extraneous", false),
2203 ];
2204
2205 for (label, expected_valid) in expected_results {
2206 let context = SeContext::new(label)?;
2207 let result = check_label_is_allowed(&context);
2208 if expected_valid {
2209 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2210 } else if result.is_ok() {
2211 bail!("Expected label {} to be disallowed", label);
2212 }
2213 }
2214 Ok(())
2215 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002216
2217 #[test]
2218 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2219 let apk = tempfile::tempfile().unwrap();
2220 let idsig = tempfile::tempfile().unwrap();
2221
2222 let ret = create_or_update_idsig_file(
2223 &ParcelFileDescriptor::new(apk),
2224 &ParcelFileDescriptor::new(idsig),
2225 );
2226 assert!(ret.is_err(), "should fail");
2227 Ok(())
2228 }
2229
2230 #[test]
2231 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2232 let tmp_dir = tempfile::TempDir::new().unwrap();
2233 let apk = File::open(tmp_dir.path()).unwrap();
2234 let idsig = tempfile::tempfile().unwrap();
2235
2236 let ret = create_or_update_idsig_file(
2237 &ParcelFileDescriptor::new(apk),
2238 &ParcelFileDescriptor::new(idsig),
2239 );
2240 assert!(ret.is_err(), "should fail");
2241 Ok(())
2242 }
2243
2244 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2245 /// on ext4 filesystem is passed.
2246 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2247 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2248 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2249 #[test]
2250 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2251 // APEXes are backed by the ext4.
2252 let apk = File::open("/apex/com.android.virt/").unwrap();
2253 let idsig = tempfile::tempfile().unwrap();
2254
2255 let ret = create_or_update_idsig_file(
2256 &ParcelFileDescriptor::new(apk),
2257 &ParcelFileDescriptor::new(idsig),
2258 );
2259 assert!(ret.is_err(), "should fail");
2260 Ok(())
2261 }
Jiyong Park8d192952023-06-26 14:29:51 +09002262
2263 #[test]
2264 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2265 use std::io::Seek;
2266
2267 // Pick any APK
2268 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2269 let mut idsig = tempfile::tempfile().unwrap();
2270
2271 create_or_update_idsig_file(
2272 &ParcelFileDescriptor::new(apk.try_clone()?),
2273 &ParcelFileDescriptor::new(idsig.try_clone()?),
2274 )?;
2275 let modified_orig = idsig.metadata()?.modified()?;
2276 apk.rewind()?;
2277 idsig.rewind()?;
2278
2279 // Call the function again
2280 create_or_update_idsig_file(
2281 &ParcelFileDescriptor::new(apk.try_clone()?),
2282 &ParcelFileDescriptor::new(idsig.try_clone()?),
2283 )?;
2284 let modified_new = idsig.metadata()?.modified()?;
2285 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2286 Ok(())
2287 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002288
2289 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002290 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2291 use std::io::Read;
2292
2293 // Pick any APK
2294 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2295 let idsig_empty = tempfile::tempfile().unwrap();
2296 let mut idsig_invalid = tempfile::tempfile().unwrap();
2297 idsig_invalid.write_all(b"Oops")?;
2298
2299 // Create new idsig
2300 create_or_update_idsig_file(
2301 &ParcelFileDescriptor::new(apk.try_clone()?),
2302 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2303 )?;
2304 apk.rewind()?;
2305
2306 // Update idsig_invalid
2307 create_or_update_idsig_file(
2308 &ParcelFileDescriptor::new(apk.try_clone()?),
2309 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2310 )?;
2311
2312 // Ensure the 2 idsig files have same size!
2313 assert!(
2314 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2315 "idsig files differ in size"
2316 );
2317 // Ensure the 2 idsig files have same content!
2318 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2319 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2320 }
2321 Ok(())
2322 }
2323 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002324 fn test_append_kernel_param_first_param() {
2325 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2326 append_kernel_param("foo=1", &mut vm_config);
2327 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2328 }
2329
2330 #[test]
2331 fn test_append_kernel_param() {
2332 let mut vm_config =
2333 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2334 append_kernel_param("bar=42", &mut vm_config);
2335 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2336 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002337
Inseob Kim46257382024-01-03 15:41:22 +09002338 fn test_extract_os_name_from_config_path(
2339 path: &Path,
2340 expected_result: Option<&str>,
2341 ) -> Result<()> {
2342 let result = extract_os_name_from_config_path(path);
2343 if result.as_deref() != expected_result {
2344 bail!("Expected {:?} but was {:?}", expected_result, &result)
2345 }
2346 Ok(())
2347 }
2348
2349 #[test]
2350 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2351 test_extract_os_name_from_config_path(
2352 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2353 Some("microdroid"),
2354 )
2355 }
2356
2357 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002358 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2359 test_extract_os_name_from_config_path(
2360 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2361 Some("microdroid_16k"),
2362 )
2363 }
2364
2365 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002366 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2367 test_extract_os_name_from_config_path(
2368 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2369 Some("microdroid_gki-android14-6.1"),
2370 )
2371 }
2372
2373 #[test]
2374 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2375 test_extract_os_name_from_config_path(
2376 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2377 None,
2378 )
2379 }
2380
2381 #[test]
2382 fn test_extract_os_name_from_configs() -> Result<()> {
2383 let tmp_dir = tempfile::TempDir::new()?;
2384 let tmp_dir_path = tmp_dir.path().to_owned();
2385
2386 let mut os_names: HashSet<String> = HashSet::new();
2387 os_names.insert("microdroid".to_owned());
2388 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2389 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2390
2391 // config files
2392 for os_name in &os_names {
2393 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2394 }
2395
2396 // fake files not related to configs
2397 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2398 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2399
2400 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2401 Some(s) => s.to_owned(),
2402 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2403 };
2404
2405 let result = extract_os_names_from_configs(&glob_pattern)?;
2406 if result != os_names {
2407 bail!("Expected {:?} but was {:?}", os_names, result);
2408 }
2409 Ok(())
2410 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002411
2412 #[test]
2413 fn test_find_early_vms_from_xml() -> Result<()> {
2414 let tmp_dir = tempfile::TempDir::new()?;
2415 let tmp_dir_path = tmp_dir.path().to_owned();
2416 let xml_path = tmp_dir_path.join("early_vms.xml");
2417
2418 std::fs::write(
2419 &xml_path,
2420 br#"<?xml version="1.0" encoding="utf-8"?>
2421 <early_vms>
2422 <early_vm>
2423 <name>vm_demo_native_early</name>
2424 <cid>123</cid>
2425 <path>/system/bin/vm_demo_native_early</path>
2426 </early_vm>
2427 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002428 <name>vm_demo_native_early_2</name>
2429 <cid>456</cid>
2430 <path>/system/bin/vm_demo_native_early_2</path>
2431 </early_vm>
2432 </early_vms>
2433 "#,
2434 )?;
2435
2436 let cid_range = 100..1000;
2437
2438 let early_vms = get_early_vms_in_path(&xml_path)?;
2439 validate_cid_range(&early_vms, &cid_range)?;
2440
2441 let test_cases = [
2442 (
2443 "vm_demo_native_early",
2444 EarlyVm {
2445 name: "vm_demo_native_early".to_owned(),
2446 cid: 123,
2447 path: "/system/bin/vm_demo_native_early".to_owned(),
2448 },
2449 ),
2450 (
2451 "vm_demo_native_early_2",
2452 EarlyVm {
2453 name: "vm_demo_native_early_2".to_owned(),
2454 cid: 456,
2455 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2456 },
2457 ),
2458 ];
2459
2460 for (name, expected) in test_cases {
2461 let result = find_early_vm(&early_vms, name)?;
2462 assert_eq!(result, &expected);
2463 }
2464
2465 Ok(())
2466 }
2467
2468 #[test]
2469 fn test_invalid_cid_validation() -> Result<()> {
2470 let tmp_dir = tempfile::TempDir::new()?;
2471 let xml_path = tmp_dir.path().join("early_vms.xml");
2472
2473 let cid_range = 100..1000;
2474
2475 for cid in [-1, 999999] {
2476 std::fs::write(
2477 &xml_path,
2478 format!(
2479 r#"<?xml version="1.0" encoding="utf-8"?>
2480 <early_vms>
2481 <early_vm>
2482 <name>vm_demo_invalid_cid</name>
2483 <cid>{cid}</cid>
2484 <path>/system/bin/vm_demo_invalid_cid</path>
2485 </early_vm>
2486 </early_vms>
2487 "#
2488 ),
2489 )?;
2490
2491 let early_vms = get_early_vms_in_path(&xml_path)?;
2492 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2493 }
2494
2495 Ok(())
2496 }
2497
2498 #[test]
2499 fn test_duplicated_early_vms() -> Result<()> {
2500 let tmp_dir = tempfile::TempDir::new()?;
2501 let tmp_dir_path = tmp_dir.path().to_owned();
2502 let xml_path = tmp_dir_path.join("early_vms.xml");
2503
2504 std::fs::write(
2505 &xml_path,
2506 br#"<?xml version="1.0" encoding="utf-8"?>
2507 <early_vms>
2508 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002509 <name>vm_demo_duplicated_name</name>
2510 <cid>456</cid>
2511 <path>/system/bin/vm_demo_duplicated_name_1</path>
2512 </early_vm>
2513 <early_vm>
2514 <name>vm_demo_duplicated_name</name>
2515 <cid>789</cid>
2516 <path>/system/bin/vm_demo_duplicated_name_2</path>
2517 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002518 </early_vms>
2519 "#,
2520 )?;
2521
2522 let cid_range = 100..1000;
2523
Inseob Kim7e1877b2024-11-07 17:28:56 +09002524 let early_vms = get_early_vms_in_path(&xml_path)?;
2525 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002526
Inseob Kim7e1877b2024-11-07 17:28:56 +09002527 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002528
2529 Ok(())
2530 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002531}