blob: 9d72506de766ed3598bdbbb7c4c66694c36eb845 [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};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, 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)?;
448 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
449
450 // Start VM service listening for connections from the new CID on port=CID.
451 let port = cid;
Devin Moore068e6742024-10-28 18:16:25 +0000452 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
Inseob Kimecde8c02024-09-03 13:11:08 +0900453 .context(format!("Could not start RpcServer on port {port}"))
454 .or_service_specific_exception(-1)?;
455 vm_server.start();
456 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
457 }
458
David Brazdil209074a2023-01-12 16:44:51 +0000459 fn create_vm_context(
460 &self,
461 requester_debug_pid: pid_t,
462 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000463 const NUM_ATTEMPTS: usize = 5;
464
465 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000466 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000467 let cid = vm_context.getCid()? as Cid;
468 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000469 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
470
471 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000472 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000473 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000474 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000475 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000476 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000477 }
478 Err(err) => {
479 warn!("Could not start RpcServer on port {}: {}", port, err);
480 }
481 }
482 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900483 Err(anyhow!("Too many attempts to create VM context failed"))
484 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000485 }
486
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000487 fn create_vm_internal(
488 &self,
489 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900490 console_out_fd: Option<&ParcelFileDescriptor>,
491 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000492 log_fd: Option<&ParcelFileDescriptor>,
493 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000494 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000495 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000496 let requester_uid = get_calling_uid();
497 let requester_debug_pid = get_calling_pid();
498
Nikita Ioffe631717e2023-09-05 13:38:07 +0100499 check_config_features(config)?;
500
Inseob Kimecde8c02024-09-03 13:11:08 +0900501 if cfg!(early) {
502 check_config_allowed_for_early_vms(config)?;
503 }
504
David Brazdil209074a2023-01-12 16:44:51 +0000505 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900506 let (vm_context, cid, temporary_directory) = if cfg!(early) {
507 self.create_early_vm_context(config)?
508 } else {
509 self.create_vm_context(requester_debug_pid)?
510 };
Inseob Kim1119d702022-05-02 18:01:58 +0900511
Alan Stokesfda70842023-12-20 17:50:14 +0000512 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100513 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900514 }
515
Nikita Ioffe5776f082023-02-10 21:38:26 +0000516 let gdb_port = extract_gdb_port(config);
517
518 // Additional permission checks if caller request gdb.
519 if gdb_port.is_some() {
520 check_gdb_allowed(config)?;
521 }
522
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000523 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900524
Jaewan Kimf3143242024-03-15 06:56:31 +0000525 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000526 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900527 Some(prepare_ramdump_file(&temporary_directory)?)
528 } else {
529 None
530 };
531
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000532 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900533 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100534 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900535 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100536 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000537 let dump_dt_fd = dump_dt_fd.map(clone_file).transpose()?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000538
539 // Counter to generate unique IDs for temporary image files.
540 let mut next_temporary_image_id = 0;
541 // Files which are referred to from composite images. These must be mapped to the crosvm
542 // child process, and not closed before it is started.
543 let mut indirect_files = vec![];
544
Alan Stokes7bc146c2022-10-20 17:10:32 +0100545 let (is_app_config, config) = match config {
546 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
547 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900548 let config = load_app_config(config, &debug_config, &temporary_directory)
549 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900550 *is_protected = config.protectedVm;
551 let message = format!("Failed to load app config: {:?}", e);
552 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900553 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900554 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100555 (true, BorrowedOrOwned::Owned(config))
556 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000557 };
558 let config = config.as_ref();
559 *is_protected = config.protectedVm;
560
561 // Check if partition images are labeled incorrectly. This is to prevent random images
562 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100563 // being loaded in a pVM. This applies to everything but the instance image in the raw
564 // config, and everything but the non-executable, generated partitions in the app
565 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000566 config
567 .disks
568 .iter()
569 .flat_map(|disk| disk.partitions.iter())
570 .filter(|partition| {
571 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100572 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000573 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000574 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000575 }
576 })
577 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900578 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000579
Inseob Kimff48a7c2024-02-26 22:07:21 +0900580 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
581 // have unstable interfaces.
582 // TODO(b/316431494): remove once Treble interfaces are stabilized.
583 check_partitions_for_files(config).or_service_specific_exception(-1)?;
584
Alan Stokes185fe112023-01-10 16:20:55 +0000585 let kernel = maybe_clone_file(&config.kernel)?;
586 let initrd = maybe_clone_file(&config.initrd)?;
587
Alan Stokes185fe112023-01-10 16:20:55 +0000588 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000589 // In a protected VM, we require custom kernels to come from a trusted source
590 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900591 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000592 // Fail fast with a meaningful error message in case device doesn't support pVMs.
593 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000594 }
595
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000596 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900597 write_zero_filler(&zero_filler_path)
598 .context("Failed to make composite image")
599 .with_log()
600 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000601
602 // Assemble disk images if needed.
603 let disks = config
604 .disks
605 .iter()
606 .map(|disk| {
607 assemble_disk_image(
608 disk,
609 &zero_filler_path,
610 &temporary_directory,
611 &mut next_temporary_image_id,
612 &mut indirect_files,
613 )
614 })
615 .collect::<Result<Vec<DiskFile>, _>>()?;
616
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700617 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
618
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000619 let (cpus, host_cpu_topology) = match config.cpuTopology {
620 CpuTopology::MATCH_HOST => (None, true),
621 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
622 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900623 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
624 .with_log()
625 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000626 }
627 };
628
David Brazdil2dfefd12023-11-17 14:07:36 +0000629 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900630 let mut set = HashSet::new();
631 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900632 let path = canonicalize(device)
633 .with_context(|| format!("can't canonicalize {device}"))
634 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900635 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900636 return Err(anyhow!("duplicated device {device}"))
637 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900638 }
639 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000640 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000641 let dtbo_file = File::from(
642 GLOBAL_SERVICE
643 .getDtboFile()?
644 .as_ref()
645 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900646 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000647 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
648 );
649 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900650 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000651 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900652 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900653 let display_config = if cfg!(paravirtualized_devices) {
654 config
655 .displayConfig
656 .as_ref()
657 .map(DisplayConfig::new)
658 .transpose()
659 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
660 } else {
661 None
662 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700663 let gpu_config = if cfg!(paravirtualized_devices) {
664 config
665 .gpuConfig
666 .as_ref()
667 .map(GpuConfig::new)
668 .transpose()
669 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
670 } else {
671 None
672 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900673
Jeongik Chac181be72024-03-27 00:18:30 +0900674 let input_device_options = if cfg!(paravirtualized_devices) {
675 config
676 .inputDevices
677 .iter()
678 .map(to_input_device_option_from)
679 .collect::<Result<Vec<InputDeviceOption>, _>>()
680 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
681 } else {
682 vec![]
683 };
684
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900685 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900686 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900687 if *is_protected {
688 return Err(anyhow!("Network feature is not supported for pVM yet"))
689 .with_log()
690 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
691 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900692 Some(File::from(
693 GLOBAL_SERVICE
694 .createTapInterface(&get_this_pid().to_string())?
695 .as_ref()
696 .try_clone()
697 .context("Failed to get TAP interface from ParcelFileDescriptor")
698 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
699 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900700 } else {
701 None
702 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800703
704 let audio_config = if cfg!(paravirtualized_devices) {
705 config.audioConfig.as_ref().map(AudioConfig::new)
706 } else {
707 None
708 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900709
Elie Kheirallah29d72912024-08-07 20:17:26 +0000710 let usb_config = config
711 .usbConfig
712 .as_ref()
713 .map(UsbConfig::new)
714 .unwrap_or(Ok(UsbConfig { controller: false }))
715 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
716
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000717 // Actually start the VM.
718 let crosvm_config = CrosvmConfig {
719 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000720 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000721 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000722 kernel,
723 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000724 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700725 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000726 params: config.params.to_owned(),
727 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900728 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700729 memory_mib: config
730 .memoryMib
731 .try_into()
732 .ok()
733 .and_then(NonZeroU32::new)
734 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000735 cpus,
736 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900737 console_out_fd,
738 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000739 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900740 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000741 indirect_files,
742 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900743 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000744 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900745 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000746 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000747 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900748 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900749 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000750 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900751 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800752 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000753 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700754 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800755 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900756 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000757 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000758 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000759 };
760 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100761 VmInstance::new(
762 crosvm_config,
763 temporary_directory,
764 requester_uid,
765 requester_debug_pid,
766 vm_context,
767 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900768 .with_context(|| format!("Failed to create VM with config {:?}", config))
769 .with_log()
770 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000771 );
772 state.add_vm(Arc::downgrade(&instance));
773 Ok(VirtualMachine::create(instance))
774 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900775}
776
Alan Stokesfda70842023-12-20 17:50:14 +0000777/// Returns whether a VM config represents a "custom" virtual machine, which requires the
778/// USE_CUSTOM_VIRTUAL_MACHINE.
779fn is_custom_config(config: &VirtualMachineConfig) -> bool {
780 match config {
781 // Any raw (non-Microdroid) VM is considered custom.
782 VirtualMachineConfig::RawConfig(_) => true,
783 VirtualMachineConfig::AppConfig(config) => {
784 // Some features are reserved for platform apps only, even when using
785 // VirtualMachineAppConfig. Almost all of these features are grouped in the
786 // CustomConfig struct:
787 // - controlling CPUs;
788 // - gdbPort is set, meaning that crosvm will start a gdb server;
789 // - using anything other than the default kernel;
790 // - specifying devices to be assigned.
791 if config.customConfig.is_some() {
792 true
793 } else {
794 // Additional custom features not included in CustomConfig:
795 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000796 // - specifying extra APKs;
797 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900798 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000799 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900800 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
801 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000802 }
803 }
804 }
805}
806
Seungjae Yoo14e60182024-02-21 13:28:31 +0900807fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
808 let VirtualMachineConfig::AppConfig(config) = config else {
809 return Ok(None);
810 };
811 let Some(custom_config) = &config.customConfig else {
812 return Ok(None);
813 };
814 let Some(file) = custom_config.vendorImage.as_ref() else {
815 return Ok(None);
816 };
817
818 let file = clone_file(file)?;
819 let size =
820 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
821 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
822 .context("Failed to get vbmeta from microdroid-vendor.img")?;
823
824 for descriptor in vbmeta.descriptors()?.iter() {
825 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
826 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
827 return Ok(Some(root_digest.as_bytes().to_vec()));
828 }
829 }
830 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
831}
832
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000833fn maybe_create_device_tree_overlay(
834 config: &VirtualMachineConfig,
835 temporary_directory: &Path,
836) -> binder::Result<Option<File>> {
837 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
838 // (e.g. instance-id)
839 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
840 let host_ref_dt = if host_ref_dt.exists()
841 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
842 {
843 Some(host_ref_dt)
844 } else {
845 warn!("VM reference DT doesn't exist in host DT");
846 None
847 };
848
849 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
850 .context("Failed to extract vendor hashtree digest")
851 .or_service_specific_exception(-1)?;
852
853 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
854 info!(
855 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
856 match the trusted digest in the pvmfw config, causing the VM to fail to start."
857 );
858 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
859 } else {
860 vec![]
861 };
862
863 let instance_id;
864 let mut untrusted_props = Vec::with_capacity(2);
865 if cfg!(llpvm_changes) {
866 instance_id = extract_instance_id(config);
867 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
868 let want_updatable = extract_want_updatable(config);
869 if want_updatable && is_secretkeeper_supported() {
870 // Let guest know that it can defer rollback protection to Secretkeeper by setting
871 // an empty property in untrusted node in DT. This enables Updatable VMs.
872 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
873 }
874 }
875
876 let device_tree_overlay = if host_ref_dt.is_some()
877 || !untrusted_props.is_empty()
878 || !trusted_props.is_empty()
879 {
880 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
881 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
882 let fdt =
883 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
884 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
885 .or_service_specific_exception(-1)?;
886 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
887 Some(File::open(dt_output).or_service_specific_exception(-1)?)
888 } else {
889 None
890 };
891 Ok(device_tree_overlay)
892}
893
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000894fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900895 let file = OpenOptions::new()
896 .create_new(true)
897 .read(true)
898 .write(true)
899 .open(zero_filler_path)
900 .with_context(|| "Failed to create zero.img")?;
901 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000902 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900903}
904
David Brazdilf50c7a62023-04-19 14:22:42 +0000905fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
906 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
907 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
908 part.flush()
909}
910
911fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
912 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
913 part.flush()
914}
915
916fn round_up(input: u64, granularity: u64) -> u64 {
917 if granularity == 0 {
918 return input;
919 }
920 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
921 let result = input.checked_add(granularity - 1).unwrap_or(input);
922 (result / granularity) * granularity
923}
924
Jeongik Chac181be72024-03-27 00:18:30 +0900925fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
926 Ok(match input_device {
927 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
928 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
929 height: u32::try_from(single_touch.height)?,
930 width: u32::try_from(single_touch.width)?,
931 name: if !single_touch.name.is_empty() {
932 Some(single_touch.name.clone())
933 } else {
934 None
935 },
936 },
937 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
938 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
939 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900940 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
941 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
942 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900943 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
944 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
945 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900946 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
947 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
948 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900949 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
950 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
951 height: u32::try_from(trackpad.height)?,
952 width: u32::try_from(trackpad.width)?,
953 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
954 },
Jeongik Cha10494912024-07-16 11:19:50 +0900955 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
956 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
957 height: u32::try_from(multi_touch.height)?,
958 width: u32::try_from(multi_touch.width)?,
959 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
960 },
Jeongik Chac181be72024-03-27 00:18:30 +0900961 })
962}
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700963
964fn assemble_shared_paths(
965 shared_paths: &[SharedPath],
966 temporary_directory: &Path,
967) -> Result<Vec<SharedPathConfig>, Status> {
968 if shared_paths.is_empty() {
969 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
970 }
971
972 shared_paths
973 .iter()
974 .map(|path| {
975 Ok(SharedPathConfig {
976 path: path.sharedPath.clone(),
977 host_uid: path.hostUid,
978 host_gid: path.hostGid,
979 guest_uid: path.guestUid,
980 guest_gid: path.guestGid,
981 mask: path.mask,
982 tag: path.tag.clone(),
983 socket_path: temporary_directory.join(&path.socket).to_string_lossy().to_string(),
984 })
985 })
986 .collect()
987}
988
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000989/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
990///
991/// This may involve assembling a composite disk from a set of partition images.
992fn assemble_disk_image(
993 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900994 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000995 temporary_directory: &Path,
996 next_temporary_image_id: &mut u64,
997 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000998) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000999 let image = if !disk.partitions.is_empty() {
1000 if disk.image.is_some() {
1001 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001002 return Err(anyhow!("DiskImage contains both image and partitions"))
1003 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001004 }
1005
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001006 let composite_image_filenames =
1007 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1008 let (image, partition_files) = make_composite_image(
1009 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001010 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001011 &composite_image_filenames.composite,
1012 &composite_image_filenames.header,
1013 &composite_image_filenames.footer,
1014 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001015 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1016 .with_log()
1017 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001018
1019 // Pass the file descriptors for the various partition files to crosvm when it
1020 // is run.
1021 indirect_files.extend(partition_files);
1022
1023 image
1024 } else if let Some(image) = &disk.image {
1025 clone_file(image)?
1026 } else {
1027 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001028 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1029 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001030 };
1031
1032 Ok(DiskFile { image, writable: disk.writable })
1033}
1034
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001035fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1036 if let Some(ref mut params) = vm_config.params {
1037 params.push(' ');
1038 params.push_str(param)
1039 } else {
1040 vm_config.params = Some(param.to_owned())
1041 }
1042}
1043
Inseob Kim46257382024-01-03 15:41:22 +09001044fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1045 if config.extension()?.to_str()? != "json" {
1046 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001047 }
Inseob Kim46257382024-01-03 15:41:22 +09001048
1049 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1050}
1051
1052fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1053 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1054 let os_names =
1055 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1056
1057 Ok(os_names)
1058}
1059
1060fn get_supported_os_names() -> Result<HashSet<String>> {
1061 if !cfg!(vendor_modules) {
1062 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1063 }
1064
1065 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1066}
1067
1068fn is_valid_os(os_name: &str) -> bool {
1069 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001070}
1071
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001072fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1073 if !cfg!(vendor_modules) {
1074 return false;
1075 }
1076 match config {
1077 VirtualMachineConfig::RawConfig(_) => false,
1078 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1079 }
1080}
1081
Jooyung Han21e9b922021-06-26 04:14:16 +09001082fn load_app_config(
1083 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001084 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001085 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001086) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001087 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1088 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001089 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001090
Shikha Panwar22e70452022-10-10 18:32:55 +00001091 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1092 Some(clone_file(file)?)
1093 } else {
1094 None
1095 };
1096
Alan Stokesfda70842023-12-20 17:50:14 +00001097 let vm_payload_config;
1098 let extra_apk_files: Vec<_>;
1099 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001100 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001101 vm_payload_config =
1102 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1103 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1104 extra_apk_files = vm_payload_config
1105 .extra_apks
1106 .iter()
1107 .enumerate()
1108 .map(|(i, apk)| {
1109 File::open(PathBuf::from(&apk.path))
1110 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1111 })
1112 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001113 }
Alan Stokesfda70842023-12-20 17:50:14 +00001114 Payload::PayloadConfig(payload_config) => {
1115 vm_payload_config = create_vm_payload_config(payload_config)?;
1116 extra_apk_files =
1117 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1118 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001119 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001120
Inseob Kim89b24592024-02-23 18:59:43 +09001121 let payload_config_os = vm_payload_config.os.name.as_str();
1122 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1123 bail!("'os' in payload config is deprecated");
1124 }
1125
Inseob Kim172f9eb2023-11-06 17:02:08 +09001126 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001127 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001128 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001129 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001130 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001131
1132 // It is safe to construct a filename based on the os_name because we've already checked that it
1133 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001134 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1135 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001136 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001137
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001138 if let Some(custom_config) = &config.customConfig {
1139 if let Some(file) = custom_config.customKernelImage.as_ref() {
1140 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1141 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001142 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001143
1144 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001145 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001146 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001147 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001148
Chris Wailes6177c662024-05-09 14:37:44 -07001149 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001150 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001151
1152 for param in custom_config.extraKernelCmdlineParams.iter() {
1153 append_kernel_param(param, &mut vm_config);
1154 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001155
1156 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001157 }
1158
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001159 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1160 // so we need to provide it in the kernel cmdline.
1161 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1162 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1163 append_kernel_param("page_shift=14", &mut vm_config);
1164 }
1165
Andrew Walbrancc045902021-07-27 16:06:17 +00001166 if config.memoryMib > 0 {
1167 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001168 }
1169
Chris Wailes6177c662024-05-09 14:37:44 -07001170 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001171 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001172 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001173 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001174 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001175
Shikha Panwar22e70452022-10-10 18:32:55 +00001176 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001177 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001178
1179 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1180 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001181 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001182 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001183 temporary_directory,
1184 apk_file,
1185 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001186 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001187 &vm_payload_config,
1188 &mut vm_config,
1189 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001190
Andrew Walbrancc0db522021-07-12 17:03:42 +00001191 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001192}
1193
Inseob Kimff48a7c2024-02-26 22:07:21 +09001194fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1195 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1196 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1197
1198 // microdroid vendor image is OK
1199 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1200 {
1201 return Ok(());
1202 }
1203
1204 if link.starts_with("/vendor") || link.starts_with("/odm") {
1205 bail!("vendor or odm file {} can't be used for VM", link.display());
1206 }
1207
1208 Ok(())
1209}
1210
1211fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1212 config
1213 .disks
1214 .iter()
1215 .flat_map(|disk| disk.partitions.iter())
1216 .filter_map(|partition| partition.image.as_ref())
1217 .try_for_each(check_partition_for_file)?;
1218
1219 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1220 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1221 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1222
1223 Ok(())
1224}
1225
Alan Stokes0d1ef782022-09-27 13:46:35 +01001226fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1227 let mut apk_zip = ZipArchive::new(apk_file)?;
1228 let config_file = apk_zip.by_name(config_path)?;
1229 Ok(serde_json::from_reader(config_file)?)
1230}
1231
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001232fn create_vm_payload_config(
1233 payload_config: &VirtualMachinePayloadConfig,
1234) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001235 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1236 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1237 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001238
1239 let payload_binary_name = &payload_config.payloadBinaryName;
1240 if payload_binary_name.contains('/') {
1241 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1242 }
1243
1244 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001245
1246 // The VM only cares about how many there are, these names are actually ignored.
1247 let extra_apk_count = payload_config.extraApks.len();
1248 let extra_apks =
1249 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1250
Inseob Kim89b24592024-02-23 18:59:43 +09001251 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001252}
1253
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001254/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001255fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001256 temporary_directory: &Path,
1257 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001258) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001259 let id = *next_temporary_image_id;
1260 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001261 CompositeImageFilenames {
1262 composite: temporary_directory.join(format!("composite-{}.img", id)),
1263 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1264 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1265 }
1266}
1267
1268/// Filenames for a composite disk image, including header and footer partitions.
1269#[derive(Clone, Debug, Eq, PartialEq)]
1270struct CompositeImageFilenames {
1271 /// The composite disk image itself.
1272 composite: PathBuf,
1273 /// The header partition image.
1274 header: PathBuf,
1275 /// The footer partition image.
1276 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001277}
1278
Jiyong Park753553b2021-07-12 21:21:09 +09001279/// Checks whether the caller has a specific permission
1280fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001281 if cfg!(early) {
1282 // Skip permission check for early VMs, in favor of SELinux
1283 return Ok(());
1284 }
David Brazdil1f530702022-10-03 12:18:10 +01001285 let calling_pid = get_calling_pid();
1286 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001287 // Root can do anything
1288 if calling_uid == 0 {
1289 return Ok(());
1290 }
1291 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001292 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001293 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001294 Ok(())
1295 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001296 Err(anyhow!("does not have the {} permission", perm))
1297 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001298 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001299}
1300
Jiyong Park753553b2021-07-12 21:21:09 +09001301/// Check whether the caller of the current Binder method is allowed to manage VMs
1302fn check_manage_access() -> binder::Result<()> {
1303 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1304}
1305
Inseob Kim1119d702022-05-02 18:01:58 +09001306/// Check whether the caller of the current Binder method is allowed to create custom VMs
1307fn check_use_custom_virtual_machine() -> binder::Result<()> {
1308 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1309}
1310
Alan Stokes185fe112023-01-10 16:20:55 +00001311/// Return whether a partition is exempt from selinux label checks, because we know that it does
1312/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001313fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001314 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001315 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001316 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001317 || label == "microdroid-apk-idsig"
1318 || label == "payload-metadata"
1319 || label.starts_with("extra-idsig-")
1320}
1321
Alice Wangc206b9b2023-08-28 14:13:51 +00001322/// Returns whether a partition with the given label is safe for a raw config VM.
1323fn is_safe_raw_partition(label: &str) -> bool {
1324 label == "vm-instance"
1325}
1326
Alan Stokes185fe112023-01-10 16:20:55 +00001327/// Check that a file SELinux label is acceptable.
1328///
1329/// 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 +09001330/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001331///
1332/// Note that sepolicy must also grant read access for these types to both virtualization
1333/// service and crosvm.
1334///
1335/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1336/// user devices (W^X).
1337fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1338 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001339 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001340 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001341 | "staging_data_file" // updated/staged APEX images
1342 | "system_file" // immutable dm-verity protected partition
1343 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001344 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001345 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001346 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001347 }
1348}
1349
Alan Stokes185fe112023-01-10 16:20:55 +00001350fn check_label_for_partition(partition: &Partition) -> Result<()> {
1351 let file = partition.image.as_ref().unwrap().as_ref();
1352 check_label_is_allowed(&getfilecon(file)?)
1353 .with_context(|| format!("Partition {} invalid", &partition.label))
1354}
1355
1356fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1357 if let Some(f) = kernel {
1358 check_label_for_file(f, "kernel")?;
1359 }
1360 if let Some(f) = initrd {
1361 check_label_for_file(f, "initrd")?;
1362 }
1363 Ok(())
1364}
1365fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1366 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1367}
1368
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001369/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1370#[derive(Debug)]
1371struct VirtualMachine {
1372 instance: Arc<VmInstance>,
1373}
1374
1375impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001376 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001377 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001378 }
1379}
1380
1381impl Interface for VirtualMachine {}
1382
Devin Moore407df8f2024-08-27 19:39:16 +00001383impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001384 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001385 // Don't check permission. The owner of the VM might have passed this binder object to
1386 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001387 Ok(self.instance.cid as i32)
1388 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001389
Andrew Walbran6b650662021-09-07 13:13:23 +00001390 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001391 // Don't check permission. The owner of the VM might have passed this binder object to
1392 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001393 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001394 }
1395
1396 fn registerCallback(
1397 &self,
1398 callback: &Strong<dyn IVirtualMachineCallback>,
1399 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001400 // Don't check permission. The owner of the VM might have passed this binder object to
1401 // others.
1402 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001403 // TODO: Should this give an error if the VM is already dead?
1404 self.instance.callbacks.add(callback.clone());
1405 Ok(())
1406 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001407
Andrew Walbranf8d94112021-09-07 11:45:36 +00001408 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001409 self.instance
1410 .start()
1411 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1412 .with_log()
1413 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001414 }
1415
Inseob Kima446f802022-07-11 19:46:37 +09001416 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001417 self.instance
1418 .kill()
1419 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1420 .with_log()
1421 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001422 }
1423
Keir Fraser48221ba2024-07-12 14:05:02 +00001424 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1425 let balloon = self
1426 .instance
1427 .get_memory_balloon()
1428 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1429 .with_log()
1430 .or_service_specific_exception(-1)?;
1431 Ok(balloon.try_into().unwrap())
1432 }
1433
1434 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001435 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001436 .set_memory_balloon(num_bytes.try_into().unwrap())
1437 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001438 .with_log()
1439 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001440 }
1441
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001442 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001443 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001444 return Err(Status::new_service_specific_error_str(
1445 IVirtualMachine::ERROR_UNEXPECTED,
1446 Some("Virtual Machine is not running"),
1447 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001448 }
Alan Stokes10c47672022-12-13 17:17:08 +00001449 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001450 if port < VSOCK_PRIV_PORT_MAX {
1451 return Err(Status::new_service_specific_error_str(
1452 IVirtualMachine::ERROR_UNEXPECTED,
1453 Some("Can't connect to privileged port {port}"),
1454 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001455 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001456 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1457 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001458 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001459 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001460 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001461
Devin Moore407df8f2024-08-27 19:39:16 +00001462 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1463 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1464 return Err(Status::new_service_specific_error_str(
1465 IVirtualMachine::ERROR_UNEXPECTED,
1466 Some("Virtual Machine is not running"),
1467 ));
1468 }
1469 let port = port as u32;
1470 if port < VSOCK_PRIV_PORT_MAX {
1471 return Err(Status::new_service_specific_error_str(
1472 IVirtualMachine::ERROR_UNEXPECTED,
1473 Some("Can't connect to privileged port {port}"),
1474 ));
1475 }
1476 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001477 let addr = sockaddr_vm {
1478 svm_family: AF_VSOCK as sa_family_t,
1479 svm_reserved1: 0,
1480 svm_port: port,
1481 svm_cid: cid,
1482 svm_zero: [0u8; 4],
1483 };
1484 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001485 let accessor = Accessor::new(name, get_connection_info);
1486 accessor
1487 .as_binder()
1488 .context("The newly created Accessor should always have a binder")
1489 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1490 }
1491
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001492 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1493 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1494 }
Jiyong Park23b67392024-07-04 13:51:42 +09001495
1496 fn suspend(&self) -> binder::Result<()> {
1497 self.instance
1498 .suspend()
1499 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1500 .with_log()
1501 .or_service_specific_exception(-1)
1502 }
1503
1504 fn resume(&self) -> binder::Result<()> {
1505 self.instance
1506 .resume()
1507 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1508 .with_log()
1509 .or_service_specific_exception(-1)
1510 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001511}
1512
1513impl Drop for VirtualMachine {
1514 fn drop(&mut self) {
1515 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001516 if let Err(e) = self.instance.kill() {
1517 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1518 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001519 }
1520}
1521
1522/// A set of Binders to be called back in response to various events on the VM, such as when it
1523/// dies.
1524#[derive(Debug, Default)]
1525pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1526
1527impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001528 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001529 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001530 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001531 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001532 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001533 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001534 }
1535 }
1536 }
1537
Inseob Kim14cb8692021-08-31 21:50:39 +09001538 /// Call all registered callbacks to notify that the payload is ready to serve.
1539 pub fn notify_payload_ready(&self, cid: Cid) {
1540 let callbacks = &*self.0.lock().unwrap();
1541 for callback in callbacks {
1542 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001543 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001544 }
1545 }
1546 }
1547
Inseob Kim2444af92021-08-31 01:22:50 +09001548 /// Call all registered callbacks to notify that the payload has finished.
1549 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1550 let callbacks = &*self.0.lock().unwrap();
1551 for callback in callbacks {
1552 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001553 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001554 }
1555 }
1556 }
1557
Jooyung Handd0a1732021-11-23 15:26:20 +09001558 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001559 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001560 let callbacks = &*self.0.lock().unwrap();
1561 for callback in callbacks {
1562 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001563 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001564 }
1565 }
1566 }
1567
Andrew Walbrandae07162021-03-12 17:05:20 +00001568 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001569 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001570 let callbacks = &*self.0.lock().unwrap();
1571 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001572 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001573 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001574 }
1575 }
1576 }
1577
1578 /// Add a new callback to the set.
1579 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1580 self.0.lock().unwrap().push(callback);
1581 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001582}
1583
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001584/// The mutable state of the VirtualizationService. There should only be one instance of this
1585/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001586#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001587struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001588 /// The VMs which have been started. When VMs are started a weak reference is added to this
1589 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1590 /// the Binder client are dropped the weak reference here will become invalid, and will be
1591 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001592 vms: Vec<Weak<VmInstance>>,
1593}
1594
1595impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001596 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001597 fn vms(&self) -> Vec<Arc<VmInstance>> {
1598 // Attempt to upgrade the weak pointers to strong pointers.
1599 self.vms.iter().filter_map(Weak::upgrade).collect()
1600 }
1601
1602 /// Add a new VM to the list.
1603 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1604 // Garbage collect any entries from the stored list which no longer exist.
1605 self.vms.retain(|vm| vm.strong_count() > 0);
1606
1607 // Actually add the new VM.
1608 self.vms.push(vm);
1609 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001610
Jiyong Park8611a6c2021-07-09 18:17:44 +09001611 /// Get a VM that corresponds to the given cid
1612 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1613 self.vms().into_iter().find(|vm| vm.cid == cid)
1614 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001615}
1616
Andrew Walbran6b650662021-09-07 13:13:23 +00001617/// Gets the `VirtualMachineState` of the given `VmInstance`.
1618fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001619 match &*instance.vm_state.lock().unwrap() {
1620 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1621 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001622 PayloadState::Starting => VirtualMachineState::STARTING,
1623 PayloadState::Started => VirtualMachineState::STARTED,
1624 PayloadState::Ready => VirtualMachineState::READY,
1625 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001626 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001627 },
1628 VmState::Dead => VirtualMachineState::DEAD,
1629 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001630 }
1631}
1632
David Brazdilf50c7a62023-04-19 14:22:42 +00001633/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001634pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1635 file.as_ref()
1636 .try_clone()
1637 .context("Failed to clone File from ParcelFileDescriptor")
1638 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001639 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001640}
1641
Andrew Walbrand3a84182021-09-07 14:48:52 +00001642/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001643fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001644 file.as_ref().map(clone_file).transpose()
1645}
1646
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001647/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001648fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1649 // SAFETY: ownership is transferred from stream to f
1650 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1651 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001652}
1653
Jiyong Parkdcf17412022-02-08 15:07:23 +09001654/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001655fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1656 VersionReq::parse(s)
1657 .with_context(|| format!("Invalid platform version requirement {}", s))
1658 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001659}
1660
Jiyong Parked180932023-02-24 19:55:41 +09001661/// Create the empty ramdump file
1662fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1663 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1664 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1665 // owner) for readout.
1666 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001667 let ramdump = File::create(ramdump_path)
1668 .context("Failed to prepare ramdump file")
1669 .with_log()
1670 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001671 Ok(ramdump)
1672}
1673
Nikita Ioffe5776f082023-02-10 21:38:26 +00001674fn is_protected(config: &VirtualMachineConfig) -> bool {
1675 match config {
1676 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1677 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1678 }
1679}
1680
1681fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1682 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001683 return Err(anyhow!("Can't use gdb with protected VMs"))
1684 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001685 }
1686
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001687 if get_debug_level(config) == Some(DebugLevel::NONE) {
1688 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1689 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001690 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001691
1692 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001693}
1694
Shikha Panwar61a74b52024-02-16 13:17:01 +00001695fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1696 match config {
1697 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1698 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1699 }
1700}
1701
Alan Stokesc96b35e2024-05-03 13:21:20 +01001702fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1703 match config {
1704 VirtualMachineConfig::RawConfig(_) => true,
1705 VirtualMachineConfig::AppConfig(config) => {
1706 let Some(custom) = &config.customConfig else { return true };
1707 custom.wantUpdatable
1708 }
1709 }
1710}
1711
Nikita Ioffe5776f082023-02-10 21:38:26 +00001712fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1713 match config {
1714 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001715 VirtualMachineConfig::AppConfig(config) => {
1716 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1717 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001718 }
1719}
1720
Nikita Ioffe631717e2023-09-05 13:38:07 +01001721fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1722 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1723 if let Some(custom_config) = &config.customConfig {
1724 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1725 return Err(anyhow!("vendor modules feature is disabled"))
1726 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1727 }
1728 }
1729 Ok(())
1730}
1731
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001732fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1733 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1734 if let Some(custom_config) = &config.customConfig {
1735 if !custom_config.devices.is_empty() {
1736 return Err(anyhow!("device assignment feature is disabled"))
1737 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1738 }
1739 }
1740 Ok(())
1741}
1742
Alan Stokesfda70842023-12-20 17:50:14 +00001743fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1744 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1745 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1746 if !payload_config.extraApks.is_empty() {
1747 return Err(anyhow!("multi-tenant feature is disabled"))
1748 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1749 }
1750 Ok(())
1751}
1752
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001753fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1754 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1755 if let Some(custom_config) = &config.customConfig {
1756 if !custom_config.extraKernelCmdlineParams.is_empty() {
1757 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1758 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1759 }
1760 }
1761 Ok(())
1762}
1763
Nikita Ioffe99548382024-10-21 15:54:46 +00001764fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1765 match config {
1766 VirtualMachineConfig::RawConfig(config) => {
1767 if !config.teeServices.is_empty() {
1768 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1769 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1770 }
1771 }
1772 VirtualMachineConfig::AppConfig(config) => {
1773 if let Some(custom_config) = &config.customConfig {
1774 if !custom_config.teeServices.is_empty() {
1775 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1776 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1777 }
1778 }
1779 }
1780 };
1781 Ok(())
1782}
1783
Nikita Ioffef934e812024-07-05 15:44:41 +00001784fn check_protected_vm_is_supported() -> binder::Result<()> {
1785 let is_pvm_supported =
1786 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1787 if is_pvm_supported {
1788 Ok(())
1789 } else {
1790 Err(anyhow!("pVM is not supported"))
1791 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1792 }
1793}
1794
Nikita Ioffe631717e2023-09-05 13:38:07 +01001795fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1796 if !cfg!(vendor_modules) {
1797 check_no_vendor_modules(config)?;
1798 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001799 if !cfg!(device_assignment) {
1800 check_no_devices(config)?;
1801 }
Alan Stokesfda70842023-12-20 17:50:14 +00001802 if !cfg!(multi_tenant) {
1803 check_no_extra_apks(config)?;
1804 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001805 if !cfg!(debuggable_vms_improvements) {
1806 check_no_extra_kernel_cmdline_params(config)?;
1807 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001808 if !cfg!(tee_services_allowlist) {
1809 check_no_tee_services(config)?;
1810 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001811 Ok(())
1812}
1813
Inseob Kimecde8c02024-09-03 13:11:08 +09001814fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1815 check_no_vendor_modules(config)?;
1816 check_no_devices(config)?;
1817
1818 Ok(())
1819}
1820
Inseob Kim0168b462022-12-27 14:54:35 +09001821fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001822 fd: Option<&ParcelFileDescriptor>,
1823 tag: String,
1824) -> Result<Option<File>, Status> {
1825 if let Some(fd) = fd {
1826 return Ok(Some(clone_file(fd)?));
1827 }
1828
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001829 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001830 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001831
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001832 let mut reader = BufReader::new(File::from(read_fd));
1833 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001834
1835 std::thread::spawn(move || loop {
1836 let mut buf = vec![];
1837 match reader.read_until(b'\n', &mut buf) {
1838 Ok(0) => {
1839 // EOF
1840 return;
1841 }
1842 Ok(size) => {
1843 if buf[size - 1] == b'\n' {
1844 buf.pop();
1845 }
1846 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1847 }
1848 Err(e) => {
1849 error!("Could not read console pipe: {:?}", e);
1850 return;
1851 }
1852 };
1853 });
1854
1855 Ok(Some(write_fd))
1856}
1857
Jooyung Han35edb8f2021-07-01 16:17:16 +09001858/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1859/// it doesn't require that T implements Clone.
1860enum BorrowedOrOwned<'a, T> {
1861 Borrowed(&'a T),
1862 Owned(T),
1863}
1864
1865impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1866 fn as_ref(&self) -> &T {
1867 match self {
1868 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001869 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001870 }
1871 }
1872}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001873
1874/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1875#[derive(Debug, Default)]
1876struct VirtualMachineService {
1877 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001878 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001879}
1880
1881impl Interface for VirtualMachineService {}
1882
1883impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001884 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1885 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001886 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001887 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001888 vm.update_payload_state(PayloadState::Started)
1889 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001890 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001891
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001892 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1893 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001894 Ok(())
1895 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001896 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001897 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001898 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001899 }
Inseob Kim2444af92021-08-31 01:22:50 +09001900
Inseob Kimc7d28c72021-10-25 14:28:10 +00001901 fn notifyPayloadReady(&self) -> binder::Result<()> {
1902 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001903 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001904 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001905 vm.update_payload_state(PayloadState::Ready)
1906 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001907 vm.callbacks.notify_payload_ready(cid);
1908 Ok(())
1909 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001910 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001911 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001912 }
1913 }
1914
Inseob Kimc7d28c72021-10-25 14:28:10 +00001915 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1916 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001917 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001918 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001919 vm.update_payload_state(PayloadState::Finished)
1920 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001921 vm.callbacks.notify_payload_finished(cid, exit_code);
1922 Ok(())
1923 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001924 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001925 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001926 }
1927 }
1928
Alan Stokes2bead0d2022-09-05 16:58:34 +01001929 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001930 let cid = self.cid;
1931 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001932 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001933 vm.update_payload_state(PayloadState::Finished)
1934 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001935 vm.callbacks.notify_error(cid, error_code, message);
1936 Ok(())
1937 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001938 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001939 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001940 }
1941 }
Alice Wangc2fec932023-02-23 16:24:02 +00001942
Shikha Panware45e9422024-02-28 21:18:10 +00001943 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1944 if !is_secretkeeper_supported() {
1945 return Err(StatusCode::NAME_NOT_FOUND)?;
1946 }
1947 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1948 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001949 }
1950
Alice Wange64dd182024-01-17 15:57:55 +00001951 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1952 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001953 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001954}
1955
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001956fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001957 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1958 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001959}
1960
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001961impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001962 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001963 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001964 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001965 BinderFeatures::default(),
1966 )
1967 }
1968}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001969
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001970struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1971
1972impl Interface for SecretkeeperProxy {}
1973
1974impl ISecretkeeper for SecretkeeperProxy {
1975 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1976 // Pass the request to the channel, and read the response.
1977 self.0.processSecretManagementRequest(req)
1978 }
1979
1980 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1981 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1982 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1983 }
1984
1985 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1986 self.0.deleteIds(ids)
1987 }
1988
1989 fn deleteAll(&self) -> binder::Result<()> {
1990 self.0.deleteAll()
1991 }
1992}
1993
1994struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1995
1996impl Interface for AuthGraphKeyExchangeProxy {}
1997
1998impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1999 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2000 self.0.create()
2001 }
2002
2003 fn init(
2004 &self,
2005 peer_pub_key: &PubKey,
2006 peer_id: &Identity,
2007 peer_nonce: &[u8],
2008 peer_version: i32,
2009 ) -> binder::Result<KeInitResult> {
2010 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2011 }
2012
2013 fn finish(
2014 &self,
2015 peer_pub_key: &PubKey,
2016 peer_id: &Identity,
2017 peer_signature: &SessionIdSignature,
2018 peer_nonce: &[u8],
2019 peer_version: i32,
2020 own_key: &Key,
2021 ) -> binder::Result<SessionInfo> {
2022 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2023 }
2024
2025 fn authenticationComplete(
2026 &self,
2027 peer_signature: &SessionIdSignature,
2028 shared_keys: &[AuthgraphArc; 2],
2029 ) -> binder::Result<[AuthgraphArc; 2]> {
2030 self.0.authenticationComplete(peer_signature, shared_keys)
2031 }
2032}
2033
Inseob Kimecde8c02024-09-03 13:11:08 +09002034// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002035#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002036struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002037 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002038 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002039 path: String,
2040}
2041
2042#[derive(Debug, Default, Deserialize)]
2043struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002044 early_vm: Vec<EarlyVm>,
2045}
2046
Inseob Kim7e1877b2024-11-07 17:28:56 +09002047static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2048 LazyLock::new(|| Mutex::new(HashMap::new()));
2049
Inseob Kimecde8c02024-09-03 13:11:08 +09002050fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2051 match partition {
2052 "system" => Ok(100..200),
2053 "system_ext" | "product" => Ok(200..300),
2054 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2055 }
2056}
2057
Inseob Kim7e1877b2024-11-07 17:28:56 +09002058fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002059 if !xml_path.exists() {
2060 bail!("{} doesn't exist", xml_path.display());
2061 }
2062
2063 let xml =
2064 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2065 let xml = String::from_utf8(xml)
2066 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2067 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2068 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2069
Inseob Kim7e1877b2024-11-07 17:28:56 +09002070 Ok(early_vms.early_vm)
2071}
Inseob Kimecde8c02024-09-03 13:11:08 +09002072
Inseob Kim7e1877b2024-11-07 17:28:56 +09002073fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2074 for early_vm in early_vms {
2075 let cid = early_vm
2076 .cid
2077 .try_into()
2078 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2079
2080 ensure!(
2081 cid_range.contains(&cid),
2082 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2083 early_vm.name
2084 );
2085 }
2086 Ok(())
2087}
2088
2089fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2090 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2091
2092 if let Some(result) = cache.get(partition) {
2093 return Ok(result.clone());
2094 }
2095
2096 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2097 let mut early_vms = Vec::new();
2098 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2099 match entry {
2100 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2101 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2102 }
2103 }
2104
2105 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2106 .with_context(|| format!("CID validation for {partition} failed"))?;
2107
2108 cache.insert(partition.to_owned(), early_vms.clone());
2109
2110 Ok(early_vms)
2111}
2112
2113fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2114 let mut found_vm: Option<&EarlyVm> = None;
2115
2116 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002117 if early_vm.name != name {
2118 continue;
2119 }
2120
Inseob Kimecde8c02024-09-03 13:11:08 +09002121 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002122 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002123 }
2124
2125 found_vm = Some(early_vm);
2126 }
2127
Inseob Kim7e1877b2024-11-07 17:28:56 +09002128 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002129}
2130
2131fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002132 let early_vms = get_early_vms_in_partition(partition)
2133 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2134
2135 Ok(find_early_vm(&early_vms, name)
2136 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2137 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002138}
2139
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002140#[cfg(test)]
2141mod tests {
2142 use super::*;
2143
2144 #[test]
2145 fn test_is_allowed_label_for_partition() -> Result<()> {
2146 let expected_results = vec![
2147 ("u:object_r:system_file:s0", true),
2148 ("u:object_r:apk_data_file:s0", true),
2149 ("u:object_r:app_data_file:s0", false),
2150 ("u:object_r:app_data_file:s0:c512,c768", false),
2151 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2152 ("invalid", false),
2153 ("user:role:apk_data_file:severity:categories", true),
2154 ("user:role:apk_data_file:severity:categories:extraneous", false),
2155 ];
2156
2157 for (label, expected_valid) in expected_results {
2158 let context = SeContext::new(label)?;
2159 let result = check_label_is_allowed(&context);
2160 if expected_valid {
2161 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2162 } else if result.is_ok() {
2163 bail!("Expected label {} to be disallowed", label);
2164 }
2165 }
2166 Ok(())
2167 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002168
2169 #[test]
2170 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2171 let apk = tempfile::tempfile().unwrap();
2172 let idsig = tempfile::tempfile().unwrap();
2173
2174 let ret = create_or_update_idsig_file(
2175 &ParcelFileDescriptor::new(apk),
2176 &ParcelFileDescriptor::new(idsig),
2177 );
2178 assert!(ret.is_err(), "should fail");
2179 Ok(())
2180 }
2181
2182 #[test]
2183 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2184 let tmp_dir = tempfile::TempDir::new().unwrap();
2185 let apk = File::open(tmp_dir.path()).unwrap();
2186 let idsig = tempfile::tempfile().unwrap();
2187
2188 let ret = create_or_update_idsig_file(
2189 &ParcelFileDescriptor::new(apk),
2190 &ParcelFileDescriptor::new(idsig),
2191 );
2192 assert!(ret.is_err(), "should fail");
2193 Ok(())
2194 }
2195
2196 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2197 /// on ext4 filesystem is passed.
2198 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2199 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2200 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2201 #[test]
2202 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2203 // APEXes are backed by the ext4.
2204 let apk = File::open("/apex/com.android.virt/").unwrap();
2205 let idsig = tempfile::tempfile().unwrap();
2206
2207 let ret = create_or_update_idsig_file(
2208 &ParcelFileDescriptor::new(apk),
2209 &ParcelFileDescriptor::new(idsig),
2210 );
2211 assert!(ret.is_err(), "should fail");
2212 Ok(())
2213 }
Jiyong Park8d192952023-06-26 14:29:51 +09002214
2215 #[test]
2216 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2217 use std::io::Seek;
2218
2219 // Pick any APK
2220 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2221 let mut idsig = tempfile::tempfile().unwrap();
2222
2223 create_or_update_idsig_file(
2224 &ParcelFileDescriptor::new(apk.try_clone()?),
2225 &ParcelFileDescriptor::new(idsig.try_clone()?),
2226 )?;
2227 let modified_orig = idsig.metadata()?.modified()?;
2228 apk.rewind()?;
2229 idsig.rewind()?;
2230
2231 // Call the function again
2232 create_or_update_idsig_file(
2233 &ParcelFileDescriptor::new(apk.try_clone()?),
2234 &ParcelFileDescriptor::new(idsig.try_clone()?),
2235 )?;
2236 let modified_new = idsig.metadata()?.modified()?;
2237 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2238 Ok(())
2239 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002240
2241 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002242 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2243 use std::io::Read;
2244
2245 // Pick any APK
2246 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2247 let idsig_empty = tempfile::tempfile().unwrap();
2248 let mut idsig_invalid = tempfile::tempfile().unwrap();
2249 idsig_invalid.write_all(b"Oops")?;
2250
2251 // Create new idsig
2252 create_or_update_idsig_file(
2253 &ParcelFileDescriptor::new(apk.try_clone()?),
2254 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2255 )?;
2256 apk.rewind()?;
2257
2258 // Update idsig_invalid
2259 create_or_update_idsig_file(
2260 &ParcelFileDescriptor::new(apk.try_clone()?),
2261 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2262 )?;
2263
2264 // Ensure the 2 idsig files have same size!
2265 assert!(
2266 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2267 "idsig files differ in size"
2268 );
2269 // Ensure the 2 idsig files have same content!
2270 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2271 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2272 }
2273 Ok(())
2274 }
2275 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002276 fn test_append_kernel_param_first_param() {
2277 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2278 append_kernel_param("foo=1", &mut vm_config);
2279 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2280 }
2281
2282 #[test]
2283 fn test_append_kernel_param() {
2284 let mut vm_config =
2285 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2286 append_kernel_param("bar=42", &mut vm_config);
2287 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2288 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002289
Inseob Kim46257382024-01-03 15:41:22 +09002290 fn test_extract_os_name_from_config_path(
2291 path: &Path,
2292 expected_result: Option<&str>,
2293 ) -> Result<()> {
2294 let result = extract_os_name_from_config_path(path);
2295 if result.as_deref() != expected_result {
2296 bail!("Expected {:?} but was {:?}", expected_result, &result)
2297 }
2298 Ok(())
2299 }
2300
2301 #[test]
2302 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2303 test_extract_os_name_from_config_path(
2304 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2305 Some("microdroid"),
2306 )
2307 }
2308
2309 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002310 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2311 test_extract_os_name_from_config_path(
2312 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2313 Some("microdroid_16k"),
2314 )
2315 }
2316
2317 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002318 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2319 test_extract_os_name_from_config_path(
2320 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2321 Some("microdroid_gki-android14-6.1"),
2322 )
2323 }
2324
2325 #[test]
2326 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2327 test_extract_os_name_from_config_path(
2328 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2329 None,
2330 )
2331 }
2332
2333 #[test]
2334 fn test_extract_os_name_from_configs() -> Result<()> {
2335 let tmp_dir = tempfile::TempDir::new()?;
2336 let tmp_dir_path = tmp_dir.path().to_owned();
2337
2338 let mut os_names: HashSet<String> = HashSet::new();
2339 os_names.insert("microdroid".to_owned());
2340 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2341 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2342
2343 // config files
2344 for os_name in &os_names {
2345 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2346 }
2347
2348 // fake files not related to configs
2349 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2350 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2351
2352 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2353 Some(s) => s.to_owned(),
2354 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2355 };
2356
2357 let result = extract_os_names_from_configs(&glob_pattern)?;
2358 if result != os_names {
2359 bail!("Expected {:?} but was {:?}", os_names, result);
2360 }
2361 Ok(())
2362 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002363
2364 #[test]
2365 fn test_find_early_vms_from_xml() -> Result<()> {
2366 let tmp_dir = tempfile::TempDir::new()?;
2367 let tmp_dir_path = tmp_dir.path().to_owned();
2368 let xml_path = tmp_dir_path.join("early_vms.xml");
2369
2370 std::fs::write(
2371 &xml_path,
2372 br#"<?xml version="1.0" encoding="utf-8"?>
2373 <early_vms>
2374 <early_vm>
2375 <name>vm_demo_native_early</name>
2376 <cid>123</cid>
2377 <path>/system/bin/vm_demo_native_early</path>
2378 </early_vm>
2379 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002380 <name>vm_demo_native_early_2</name>
2381 <cid>456</cid>
2382 <path>/system/bin/vm_demo_native_early_2</path>
2383 </early_vm>
2384 </early_vms>
2385 "#,
2386 )?;
2387
2388 let cid_range = 100..1000;
2389
2390 let early_vms = get_early_vms_in_path(&xml_path)?;
2391 validate_cid_range(&early_vms, &cid_range)?;
2392
2393 let test_cases = [
2394 (
2395 "vm_demo_native_early",
2396 EarlyVm {
2397 name: "vm_demo_native_early".to_owned(),
2398 cid: 123,
2399 path: "/system/bin/vm_demo_native_early".to_owned(),
2400 },
2401 ),
2402 (
2403 "vm_demo_native_early_2",
2404 EarlyVm {
2405 name: "vm_demo_native_early_2".to_owned(),
2406 cid: 456,
2407 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2408 },
2409 ),
2410 ];
2411
2412 for (name, expected) in test_cases {
2413 let result = find_early_vm(&early_vms, name)?;
2414 assert_eq!(result, &expected);
2415 }
2416
2417 Ok(())
2418 }
2419
2420 #[test]
2421 fn test_invalid_cid_validation() -> Result<()> {
2422 let tmp_dir = tempfile::TempDir::new()?;
2423 let xml_path = tmp_dir.path().join("early_vms.xml");
2424
2425 let cid_range = 100..1000;
2426
2427 for cid in [-1, 999999] {
2428 std::fs::write(
2429 &xml_path,
2430 format!(
2431 r#"<?xml version="1.0" encoding="utf-8"?>
2432 <early_vms>
2433 <early_vm>
2434 <name>vm_demo_invalid_cid</name>
2435 <cid>{cid}</cid>
2436 <path>/system/bin/vm_demo_invalid_cid</path>
2437 </early_vm>
2438 </early_vms>
2439 "#
2440 ),
2441 )?;
2442
2443 let early_vms = get_early_vms_in_path(&xml_path)?;
2444 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2445 }
2446
2447 Ok(())
2448 }
2449
2450 #[test]
2451 fn test_duplicated_early_vms() -> Result<()> {
2452 let tmp_dir = tempfile::TempDir::new()?;
2453 let tmp_dir_path = tmp_dir.path().to_owned();
2454 let xml_path = tmp_dir_path.join("early_vms.xml");
2455
2456 std::fs::write(
2457 &xml_path,
2458 br#"<?xml version="1.0" encoding="utf-8"?>
2459 <early_vms>
2460 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002461 <name>vm_demo_duplicated_name</name>
2462 <cid>456</cid>
2463 <path>/system/bin/vm_demo_duplicated_name_1</path>
2464 </early_vm>
2465 <early_vm>
2466 <name>vm_demo_duplicated_name</name>
2467 <cid>789</cid>
2468 <path>/system/bin/vm_demo_duplicated_name_2</path>
2469 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002470 </early_vms>
2471 "#,
2472 )?;
2473
2474 let cid_range = 100..1000;
2475
Inseob Kim7e1877b2024-11-07 17:28:56 +09002476 let early_vms = get_early_vms_in_path(&xml_path)?;
2477 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002478
Inseob Kim7e1877b2024-11-07 17:28:56 +09002479 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002480
2481 Ok(())
2482 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002483}