blob: 2524ce75e48d2f8b44b2eddd53f8b2aced0ab7d5 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000070use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090071use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000072use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000073use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090074use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090075use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000076use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000077use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090078use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090079use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090080use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000081use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000082use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090083use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090084use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090086use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000087use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090088use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090089use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000090use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010092use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090093use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010094use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000095use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090096use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097
David Brazdil41d1a872022-10-05 14:44:19 +010098/// The unique ID of a VM used (together with a port number) for vsock communication.
99pub type Cid = u32;
100
David Brazdil4b4c5102022-12-19 22:56:20 +0000101pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
102
Devin Moore407df8f2024-08-27 19:39:16 +0000103/// Vsock privileged ports are below this number.
104const VSOCK_PRIV_PORT_MAX: u32 = 1024;
105
Jooyung Han95884632021-07-06 22:27:54 +0900106/// The size of zero.img.
107/// Gaps in composite disk images are filled with a shared zero.img.
108const ZERO_FILLER_SIZE: u64 = 4096;
109
David Brazdilf50c7a62023-04-19 14:22:42 +0000110/// Magic string for the instance image
111const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
112
113/// Version of the instance image format
114const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
115
Alan Stokes0d1ef782022-09-27 13:46:35 +0100116const MICRODROID_OS_NAME: &str = "microdroid";
117
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000118const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000119 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000120
David Brazdilf50c7a62023-04-19 14:22:42 +0000121const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
122
123/// crosvm requires all partitions to be a multiple of 4KiB.
124const PARTITION_GRANULARITY_BYTES: u64 = 4096;
125
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000126const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
127
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100128pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
129 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900130 if cfg!(early) {
131 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
132 } else {
133 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
134 .expect("Could not connect to VirtualizationServiceInternal")
135 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100136 });
137static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
138 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000139
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000140fn create_or_update_idsig_file(
141 input_fd: &ParcelFileDescriptor,
142 idsig_fd: &ParcelFileDescriptor,
143) -> Result<()> {
144 let mut input = clone_file(input_fd)?;
145 let metadata = input.metadata().context("failed to get input metadata")?;
146 if !metadata.is_file() {
147 bail!("input is not a regular file");
148 }
Alan Stokes25f69362023-03-06 16:51:54 +0000149 let mut sig =
150 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
151 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000152
153 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900154
155 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
156 // if the idsig file already has the same APK digest.
157 if output.metadata()?.len() > 0 {
158 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
159 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
160 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
161 return Ok(());
162 }
163 }
164 // if we fail to read v4signature from output, that's fine. User can pass a random file.
165 // We will anyway overwrite the file to the v4signature generated from input_fd.
166 }
167
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000168 output
169 .seek(SeekFrom::Start(0))
170 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000171 output.set_len(0).context("failed to set_len on the idsig output")?;
172 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000173 Ok(())
174}
175
Alan Stokes25f69362023-03-06 16:51:54 +0000176fn get_current_sdk() -> Result<u32> {
177 let current_sdk = system_properties::read("ro.build.version.sdk")?;
178 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
179 current_sdk.parse().context("Malformed SDK version")
180}
181
David Brazdil4b4c5102022-12-19 22:56:20 +0000182pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
183 for dir_entry in read_dir(path)? {
184 remove_file(dir_entry?.path())?;
185 }
186 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100187}
188
David Brazdil528e0472022-10-10 15:06:02 +0100189/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000190#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000191pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900192 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000193}
194
Shikha Panward8e35422021-10-11 13:51:27 +0000195impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000197 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
198 let state = &mut *self.state.lock().unwrap();
199 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000201 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
203 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
208 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000209 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000211 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000212 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000213 .or(Err(StatusCode::UNKNOWN_ERROR))?;
214 }
215 Ok(())
216 }
217}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000218impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
220 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221 ///
222 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000224 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000225 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900226 console_out_fd: Option<&ParcelFileDescriptor>,
227 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000228 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000229 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000230 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000231 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900232 let ret = self.create_vm_internal(
233 config,
234 console_out_fd,
235 console_in_fd,
236 log_fd,
237 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000238 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900239 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000240 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000241 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000242 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000243
Shikha Panwar61a74b52024-02-16 13:17:01 +0000244 /// Allocate a new instance_id to the VM
245 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000246 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000247 GLOBAL_SERVICE.allocateInstanceId()
248 }
249
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 /// Initialise an empty partition image of the given size to be used as a writable partition.
251 fn initializeWritablePartition(
252 &self,
253 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000254 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900255 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000256 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900257 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900258 let size_bytes = size_bytes
259 .try_into()
260 .with_context(|| format!("Invalid size: {}", size_bytes))
261 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000262 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000263 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000264 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000265 image
266 .seek(SeekFrom::Start(0))
267 .context("failed to move cursor to start")
268 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900269 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700270 // Set the file length. In most filesystems, this will not allocate any physical disk
271 // space, it will only change the logical size.
272 image
273 .set_len(size_bytes)
274 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900275 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276
277 match partition_type {
278 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700279 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
280 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000281 _ => Err(Error::new(
282 ErrorKind::Unsupported,
283 format!("Unsupported partition type {:?}", partition_type),
284 )),
285 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900286 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
287 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000288
289 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000290 }
291
Jiyong Park0a248432021-08-20 23:32:39 +0900292 /// Creates or update the idsig file by digesting the input APK file.
293 fn createOrUpdateIdsigFile(
294 &self,
295 input_fd: &ParcelFileDescriptor,
296 idsig_fd: &ParcelFileDescriptor,
297 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900298 check_manage_access()?;
299
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900301 Ok(())
302 }
303
Andrew Walbran320b5602021-03-04 16:11:12 +0000304 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
305 /// and as such is only permitted from the shell user.
306 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000307 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000308 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000309 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900310
311 /// Get a list of assignable device types.
312 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
313 // Delegate to the global service, including checking the permission.
314 GLOBAL_SERVICE.getAssignableDevices()
315 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100316
Inseob Kim46257382024-01-03 15:41:22 +0900317 /// Get a list of supported OSes.
318 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
319 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
320 }
321
Jaewan Kimabd328b2024-12-10 15:59:33 +0900322 /// Get printable debug policy for testing and debugging
323 fn getDebugPolicy(&self) -> binder::Result<String> {
324 let debug_policy = DebugPolicy::from_host();
325 Ok(format!("{debug_policy:?}"))
326 }
327
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100328 /// Returns whether given feature is enabled
329 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
330 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000331 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100332 }
Alice Wange64dd182024-01-17 15:57:55 +0000333
334 fn enableTestAttestation(&self) -> binder::Result<()> {
335 GLOBAL_SERVICE.enableTestAttestation()
336 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000337
338 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
339 check_manage_access()?;
340 GLOBAL_SERVICE.isRemoteAttestationSupported()
341 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000342
343 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
344 // The response is specific to Microdroid. Updatable VMs are only possible if device
345 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
346 // this, however other guest OSes may do things differently.
347 check_manage_access()?;
348 Ok(is_secretkeeper_supported())
349 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000350
Shikha Panwar07d701c2024-03-28 14:43:52 +0000351 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
352 check_manage_access()?;
353 GLOBAL_SERVICE.removeVmInstance(instance_id)
354 }
355
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000356 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
357 check_manage_access()?;
358 GLOBAL_SERVICE.claimVmInstance(instance_id)
359 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000360}
361
Inseob Kimecde8c02024-09-03 13:11:08 +0900362/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
363#[derive(Debug, Default)]
364struct EarlyVmContext {
365 /// The unique CID assigned to the VM for vsock communication.
366 cid: Cid,
367 /// Temporary directory for this VM instance.
368 temp_dir: PathBuf,
369}
370
371impl EarlyVmContext {
372 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
373 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
374 // should trust clients, e.g. they won't run two VMs at the same time
375 let _ = remove_dir_all(&temp_dir);
376 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
377
378 Ok(Self { cid, temp_dir })
379 }
380}
381
382impl Interface for EarlyVmContext {}
383
384impl Drop for EarlyVmContext {
385 fn drop(&mut self) {
386 if let Err(e) = remove_dir_all(&self.temp_dir) {
387 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
388 }
389 }
390}
391
392impl IGlobalVmContext for EarlyVmContext {
393 fn getCid(&self) -> binder::Result<i32> {
394 Ok(self.cid as i32)
395 }
396
397 fn getTemporaryDirectory(&self) -> binder::Result<String> {
398 Ok(self.temp_dir.to_string_lossy().to_string())
399 }
400
401 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
402 Err(Status::new_exception_str(
403 ExceptionCode::UNSUPPORTED_OPERATION,
404 Some("Early VM doesn't support setting host console name"),
405 ))
406 }
407}
408
409fn find_partition(path: &Path) -> binder::Result<String> {
Inseob Kimf79c5722024-12-16 17:29:57 +0900410 let mut components = path.components();
411 match components.nth(1) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900412 Some(std::path::Component::Normal(partition)) => {
Inseob Kimf79c5722024-12-16 17:29:57 +0900413 if partition != "apex" {
414 return Ok(partition.to_string_lossy().into_owned());
415 }
416
417 // If path is under /apex, find a partition of the preinstalled .apex path
418 let apex_name = match components.next() {
419 Some(std::path::Component::Normal(name)) => name.to_string_lossy(),
420 _ => {
421 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
422 .or_service_specific_exception(-1)
423 }
424 };
425
426 let apex_info_list = ApexInfoList::load()
427 .context("Failed to get apex info list")
428 .or_service_specific_exception(-1)?;
429
430 for apex_info in apex_info_list.list.iter() {
431 if apex_info.name == apex_name {
432 return Ok(apex_info.partition.to_lowercase());
433 }
434 }
435
436 Err(anyhow!("Can't find apex info for '{apex_name}'")).or_service_specific_exception(-1)
Inseob Kimecde8c02024-09-03 13:11:08 +0900437 }
438 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
439 .or_service_specific_exception(-1),
440 }
441}
442
Jiyong Park8611a6c2021-07-09 18:17:44 +0900443impl VirtualizationService {
444 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000445 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900446 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000447
Inseob Kimecde8c02024-09-03 13:11:08 +0900448 fn create_early_vm_context(
449 &self,
450 config: &VirtualMachineConfig,
451 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
452 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
453 let link = fs::read_link(&calling_exe_path)
454 .context(format!("can't read_link '{calling_exe_path}'"))
455 .or_service_specific_exception(-1)?;
456 let partition = find_partition(&link)?;
457
458 let name = match config {
459 VirtualMachineConfig::RawConfig(config) => &config.name,
460 VirtualMachineConfig::AppConfig(config) => &config.name,
461 };
462 let early_vm =
463 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
464 if Path::new(&early_vm.path) != link {
465 return Err(anyhow!(
466 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
467 &early_vm.path,
468 link.display()
469 ))
470 .or_service_specific_exception(-1);
471 }
472
473 let cid = early_vm.cid as Cid;
474 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
475
476 let context = EarlyVmContext::new(cid, temp_dir.clone())
477 .context(format!("Can't create early vm contexts for {cid}"))
478 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900479
Jiyong Park690c1ca2024-11-28 18:06:50 +0900480 if requires_vm_service(config) {
481 // Start VM service listening for connections from the new CID on port=CID.
482 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
483 let port = cid;
484 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
485 .context(format!("Could not start RpcServer on port {port}"))
486 .or_service_specific_exception(-1)?;
487 vm_server.start();
488 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
489 } else {
490 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
491 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900492 }
493
David Brazdil209074a2023-01-12 16:44:51 +0000494 fn create_vm_context(
495 &self,
496 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900497 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000498 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000499 const NUM_ATTEMPTS: usize = 5;
500
501 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000502 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000503 let cid = vm_context.getCid()? as Cid;
504 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900505
506 // We don't need to start the VM service for custom VMs.
507 if !requires_vm_service(config) {
508 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
509 }
510
David Brazdil8cf8f482022-11-23 14:21:26 +0000511 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
512
513 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000514 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000515 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000516 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000517 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900518 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000519 }
520 Err(err) => {
521 warn!("Could not start RpcServer on port {}: {}", port, err);
522 }
523 }
524 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900525 Err(anyhow!("Too many attempts to create VM context failed"))
526 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000527 }
528
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000529 fn create_vm_internal(
530 &self,
531 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900532 console_out_fd: Option<&ParcelFileDescriptor>,
533 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000534 log_fd: Option<&ParcelFileDescriptor>,
535 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000536 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000537 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000538 let requester_uid = get_calling_uid();
539 let requester_debug_pid = get_calling_pid();
540
Nikita Ioffe631717e2023-09-05 13:38:07 +0100541 check_config_features(config)?;
542
Inseob Kimecde8c02024-09-03 13:11:08 +0900543 if cfg!(early) {
544 check_config_allowed_for_early_vms(config)?;
545 }
546
Nikita Ioffeb1416122024-10-22 12:18:49 +0000547 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
548 info!("callers secontext: {}", caller_secontext);
549
David Brazdil209074a2023-01-12 16:44:51 +0000550 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900551 let (vm_context, cid, temporary_directory) = if cfg!(early) {
552 self.create_early_vm_context(config)?
553 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900554 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900555 };
Inseob Kim1119d702022-05-02 18:01:58 +0900556
Alan Stokesfda70842023-12-20 17:50:14 +0000557 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100558 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900559 }
560
Nikita Ioffe5776f082023-02-10 21:38:26 +0000561 let gdb_port = extract_gdb_port(config);
562
563 // Additional permission checks if caller request gdb.
564 if gdb_port.is_some() {
565 check_gdb_allowed(config)?;
566 }
567
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000568 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900569
Jaewan Kimf3143242024-03-15 06:56:31 +0000570 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000571 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900572 Some(prepare_ramdump_file(&temporary_directory)?)
573 } else {
574 None
575 };
576
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000577 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900578 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100579 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900580 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100581 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100582 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
583 Some(clone_file(fd)?)
584 } else if debug_config.dump_device_tree {
585 Some(prepare_dump_dt_file(&temporary_directory)?)
586 } else {
587 None
588 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000589
590 // Counter to generate unique IDs for temporary image files.
591 let mut next_temporary_image_id = 0;
592 // Files which are referred to from composite images. These must be mapped to the crosvm
593 // child process, and not closed before it is started.
594 let mut indirect_files = vec![];
595
Alan Stokes7bc146c2022-10-20 17:10:32 +0100596 let (is_app_config, config) = match config {
597 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
598 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900599 let config = load_app_config(config, &debug_config, &temporary_directory)
600 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900601 *is_protected = config.protectedVm;
602 let message = format!("Failed to load app config: {:?}", e);
603 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900604 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900605 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100606 (true, BorrowedOrOwned::Owned(config))
607 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000608 };
609 let config = config.as_ref();
610 *is_protected = config.protectedVm;
611
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000612 if !config.teeServices.is_empty() {
613 check_tee_service_permission(&caller_secontext, &config.teeServices)
614 .with_log()
615 .or_binder_exception(ExceptionCode::SECURITY)?;
616 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000617
Jiyong Park3051ffe2024-11-26 14:41:58 +0900618 let kernel = maybe_clone_file(&config.kernel)?;
619 let initrd = maybe_clone_file(&config.initrd)?;
620
621 if config.protectedVm {
622 // Fail fast with a meaningful error message in case device doesn't support pVMs.
623 check_protected_vm_is_supported()?;
624
625 // In a protected VM, we require custom kernels to come from a trusted source
626 // (b/237054515).
627 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
628
629 // Check if partition images are labeled incorrectly. This is to prevent random images
630 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
631 // from being loaded in a pVM. This applies to everything but the instance image in the
632 // raw config, and everything but the non-executable, generated partitions in the app
633 // config.
634 config
635 .disks
636 .iter()
637 .flat_map(|disk| disk.partitions.iter())
638 .filter(|partition| {
639 if is_app_config {
640 !is_safe_app_partition(&partition.label)
641 } else {
642 !is_safe_raw_partition(&partition.label)
643 }
644 })
645 .try_for_each(check_label_for_partition)
646 .or_service_specific_exception(-1)?;
647 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000648
Inseob Kimff48a7c2024-02-26 22:07:21 +0900649 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
650 // have unstable interfaces.
651 // TODO(b/316431494): remove once Treble interfaces are stabilized.
652 check_partitions_for_files(config).or_service_specific_exception(-1)?;
653
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000654 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900655 write_zero_filler(&zero_filler_path)
656 .context("Failed to make composite image")
657 .with_log()
658 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000659
660 // Assemble disk images if needed.
661 let disks = config
662 .disks
663 .iter()
664 .map(|disk| {
665 assemble_disk_image(
666 disk,
667 &zero_filler_path,
668 &temporary_directory,
669 &mut next_temporary_image_id,
670 &mut indirect_files,
671 )
672 })
673 .collect::<Result<Vec<DiskFile>, _>>()?;
674
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700675 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
676
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000677 let (cpus, host_cpu_topology) = match config.cpuTopology {
678 CpuTopology::MATCH_HOST => (None, true),
679 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
Frederick Mayle681254c2024-12-11 19:20:06 -0800680 CpuTopology::CUSTOM => (
681 NonZeroU32::new(
682 u32::try_from(config.customVcpuCount)
683 .context("bad customVcpuCount")
684 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
685 ),
686 false,
687 ),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000688 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900689 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
690 .with_log()
691 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000692 }
693 };
694
David Brazdil2dfefd12023-11-17 14:07:36 +0000695 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900696 let mut set = HashSet::new();
697 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900698 let path = canonicalize(device)
699 .with_context(|| format!("can't canonicalize {device}"))
700 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900701 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900702 return Err(anyhow!("duplicated device {device}"))
703 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900704 }
705 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000706 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000707 let dtbo_file = File::from(
708 GLOBAL_SERVICE
709 .getDtboFile()?
710 .as_ref()
711 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900712 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000713 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
714 );
715 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900716 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000717 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900718 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900719 let display_config = if cfg!(paravirtualized_devices) {
720 config
721 .displayConfig
722 .as_ref()
723 .map(DisplayConfig::new)
724 .transpose()
725 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
726 } else {
727 None
728 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700729 let gpu_config = if cfg!(paravirtualized_devices) {
730 config
731 .gpuConfig
732 .as_ref()
733 .map(GpuConfig::new)
734 .transpose()
735 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
736 } else {
737 None
738 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900739
Jeongik Chac181be72024-03-27 00:18:30 +0900740 let input_device_options = if cfg!(paravirtualized_devices) {
741 config
742 .inputDevices
743 .iter()
744 .map(to_input_device_option_from)
745 .collect::<Result<Vec<InputDeviceOption>, _>>()
746 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
747 } else {
748 vec![]
749 };
750
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900751 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900752 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900753 if *is_protected {
754 return Err(anyhow!("Network feature is not supported for pVM yet"))
755 .with_log()
756 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
757 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900758 Some(File::from(
759 GLOBAL_SERVICE
760 .createTapInterface(&get_this_pid().to_string())?
761 .as_ref()
762 .try_clone()
763 .context("Failed to get TAP interface from ParcelFileDescriptor")
764 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
765 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900766 } else {
767 None
768 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800769
770 let audio_config = if cfg!(paravirtualized_devices) {
771 config.audioConfig.as_ref().map(AudioConfig::new)
772 } else {
773 None
774 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900775
Elie Kheirallah29d72912024-08-07 20:17:26 +0000776 let usb_config = config
777 .usbConfig
778 .as_ref()
779 .map(UsbConfig::new)
780 .unwrap_or(Ok(UsbConfig { controller: false }))
781 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
782
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000783 // Actually start the VM.
784 let crosvm_config = CrosvmConfig {
785 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000786 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000787 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000788 kernel,
789 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000790 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700791 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000792 params: config.params.to_owned(),
793 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900794 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700795 memory_mib: config
796 .memoryMib
797 .try_into()
798 .ok()
799 .and_then(NonZeroU32::new)
800 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000801 cpus,
802 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900803 console_out_fd,
804 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000805 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900806 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000807 indirect_files,
808 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900809 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000810 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900811 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000812 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000813 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900814 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900815 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000816 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900817 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800818 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000819 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700820 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800821 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800822 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000823 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000824 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000825 };
826 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100827 VmInstance::new(
828 crosvm_config,
829 temporary_directory,
830 requester_uid,
831 requester_debug_pid,
832 vm_context,
833 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900834 .with_context(|| format!("Failed to create VM with config {:?}", config))
835 .with_log()
836 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000837 );
838 state.add_vm(Arc::downgrade(&instance));
839 Ok(VirtualMachine::create(instance))
840 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900841}
842
Alan Stokesfda70842023-12-20 17:50:14 +0000843/// Returns whether a VM config represents a "custom" virtual machine, which requires the
844/// USE_CUSTOM_VIRTUAL_MACHINE.
845fn is_custom_config(config: &VirtualMachineConfig) -> bool {
846 match config {
847 // Any raw (non-Microdroid) VM is considered custom.
848 VirtualMachineConfig::RawConfig(_) => true,
849 VirtualMachineConfig::AppConfig(config) => {
850 // Some features are reserved for platform apps only, even when using
851 // VirtualMachineAppConfig. Almost all of these features are grouped in the
852 // CustomConfig struct:
853 // - controlling CPUs;
854 // - gdbPort is set, meaning that crosvm will start a gdb server;
855 // - using anything other than the default kernel;
856 // - specifying devices to be assigned.
857 if config.customConfig.is_some() {
858 true
859 } else {
860 // Additional custom features not included in CustomConfig:
861 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000862 // - specifying extra APKs;
863 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900864 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000865 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900866 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
867 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000868 }
869 }
870 }
871}
872
Jiyong Park690c1ca2024-11-28 18:06:50 +0900873/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
874/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
875/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
876/// "microdroid" we run VirtualMachineService
877fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
878 match config {
879 VirtualMachineConfig::AppConfig(_) => true,
880 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
881 }
882}
883
Seungjae Yoo14e60182024-02-21 13:28:31 +0900884fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
885 let VirtualMachineConfig::AppConfig(config) = config else {
886 return Ok(None);
887 };
888 let Some(custom_config) = &config.customConfig else {
889 return Ok(None);
890 };
891 let Some(file) = custom_config.vendorImage.as_ref() else {
892 return Ok(None);
893 };
894
895 let file = clone_file(file)?;
896 let size =
897 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
898 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
899 .context("Failed to get vbmeta from microdroid-vendor.img")?;
900
901 for descriptor in vbmeta.descriptors()?.iter() {
902 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
903 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
904 return Ok(Some(root_digest.as_bytes().to_vec()));
905 }
906 }
907 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
908}
909
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000910fn maybe_create_device_tree_overlay(
911 config: &VirtualMachineConfig,
912 temporary_directory: &Path,
913) -> binder::Result<Option<File>> {
914 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
915 // (e.g. instance-id)
916 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
917 let host_ref_dt = if host_ref_dt.exists()
918 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
919 {
920 Some(host_ref_dt)
921 } else {
922 warn!("VM reference DT doesn't exist in host DT");
923 None
924 };
925
926 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
927 .context("Failed to extract vendor hashtree digest")
928 .or_service_specific_exception(-1)?;
929
Matt Gilbrideaade4272024-12-05 13:52:42 +0000930 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000931 info!(
932 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
933 match the trusted digest in the pvmfw config, causing the VM to fail to start."
934 );
Matt Gilbrideaade4272024-12-05 13:52:42 +0000935 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000936 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000937 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000938 };
939
940 let instance_id;
Matt Gilbrideaade4272024-12-05 13:52:42 +0000941 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000942 let mut untrusted_props = Vec::with_capacity(2);
943 if cfg!(llpvm_changes) {
944 instance_id = extract_instance_id(config);
945 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
946 let want_updatable = extract_want_updatable(config);
947 if want_updatable && is_secretkeeper_supported() {
948 // Let guest know that it can defer rollback protection to Secretkeeper by setting
949 // an empty property in untrusted node in DT. This enables Updatable VMs.
Matt Gilbrideaade4272024-12-05 13:52:42 +0000950 untrusted_props.push((cstr!("defer-rollback-protection"), &[]));
951 let sk: Strong<dyn ISecretkeeper> =
952 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
953 if sk.getInterfaceVersion()? >= 2 {
954 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
955 key_material = keyMaterial;
956 trusted_props.push((cstr!("secretkeeper_public_key"), key_material.as_slice()));
957 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000958 }
959 }
960
961 let device_tree_overlay = if host_ref_dt.is_some()
962 || !untrusted_props.is_empty()
963 || !trusted_props.is_empty()
964 {
965 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
966 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
967 let fdt =
968 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
969 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
970 .or_service_specific_exception(-1)?;
971 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
972 Some(File::open(dt_output).or_service_specific_exception(-1)?)
973 } else {
974 None
975 };
976 Ok(device_tree_overlay)
977}
978
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000979fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900980 let file = OpenOptions::new()
981 .create_new(true)
982 .read(true)
983 .write(true)
984 .open(zero_filler_path)
985 .with_context(|| "Failed to create zero.img")?;
986 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000987 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900988}
989
David Brazdilf50c7a62023-04-19 14:22:42 +0000990fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
991 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
992 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
993 part.flush()
994}
995
996fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
997 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
998 part.flush()
999}
1000
1001fn round_up(input: u64, granularity: u64) -> u64 {
1002 if granularity == 0 {
1003 return input;
1004 }
1005 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1006 let result = input.checked_add(granularity - 1).unwrap_or(input);
1007 (result / granularity) * granularity
1008}
1009
Jeongik Chac181be72024-03-27 00:18:30 +09001010fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1011 Ok(match input_device {
1012 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1013 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1014 height: u32::try_from(single_touch.height)?,
1015 width: u32::try_from(single_touch.width)?,
1016 name: if !single_touch.name.is_empty() {
1017 Some(single_touch.name.clone())
1018 } else {
1019 None
1020 },
1021 },
1022 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1023 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1024 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001025 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1026 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1027 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001028 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1029 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1030 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001031 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1032 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1033 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001034 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1035 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1036 height: u32::try_from(trackpad.height)?,
1037 width: u32::try_from(trackpad.width)?,
1038 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1039 },
Jeongik Cha10494912024-07-16 11:19:50 +09001040 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1041 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1042 height: u32::try_from(multi_touch.height)?,
1043 width: u32::try_from(multi_touch.width)?,
1044 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1045 },
Jeongik Chac181be72024-03-27 00:18:30 +09001046 })
1047}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001048
1049fn assemble_shared_paths(
1050 shared_paths: &[SharedPath],
1051 temporary_directory: &Path,
1052) -> Result<Vec<SharedPathConfig>, Status> {
1053 if shared_paths.is_empty() {
1054 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1055 }
1056
1057 shared_paths
1058 .iter()
1059 .map(|path| {
1060 Ok(SharedPathConfig {
1061 path: path.sharedPath.clone(),
1062 host_uid: path.hostUid,
1063 host_gid: path.hostGid,
1064 guest_uid: path.guestUid,
1065 guest_gid: path.guestGid,
1066 mask: path.mask,
1067 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001068 socket_path: temporary_directory
1069 .join(&path.socketPath)
1070 .to_string_lossy()
1071 .to_string(),
1072 socket_fd: maybe_clone_file(&path.socketFd)?,
1073 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001074 })
1075 })
1076 .collect()
1077}
1078
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001079/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1080///
1081/// This may involve assembling a composite disk from a set of partition images.
1082fn assemble_disk_image(
1083 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001084 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001085 temporary_directory: &Path,
1086 next_temporary_image_id: &mut u64,
1087 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001088) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001089 let image = if !disk.partitions.is_empty() {
1090 if disk.image.is_some() {
1091 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001092 return Err(anyhow!("DiskImage contains both image and partitions"))
1093 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001094 }
1095
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001096 let composite_image_filenames =
1097 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1098 let (image, partition_files) = make_composite_image(
1099 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001100 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001101 &composite_image_filenames.composite,
1102 &composite_image_filenames.header,
1103 &composite_image_filenames.footer,
1104 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001105 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1106 .with_log()
1107 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001108
1109 // Pass the file descriptors for the various partition files to crosvm when it
1110 // is run.
1111 indirect_files.extend(partition_files);
1112
1113 image
1114 } else if let Some(image) = &disk.image {
1115 clone_file(image)?
1116 } else {
1117 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001118 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1119 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001120 };
1121
1122 Ok(DiskFile { image, writable: disk.writable })
1123}
1124
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001125fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1126 if let Some(ref mut params) = vm_config.params {
1127 params.push(' ');
1128 params.push_str(param)
1129 } else {
1130 vm_config.params = Some(param.to_owned())
1131 }
1132}
1133
Inseob Kim46257382024-01-03 15:41:22 +09001134fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1135 if config.extension()?.to_str()? != "json" {
1136 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001137 }
Inseob Kim46257382024-01-03 15:41:22 +09001138
1139 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1140}
1141
1142fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1143 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1144 let os_names =
1145 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1146
1147 Ok(os_names)
1148}
1149
1150fn get_supported_os_names() -> Result<HashSet<String>> {
1151 if !cfg!(vendor_modules) {
1152 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1153 }
1154
1155 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1156}
1157
1158fn is_valid_os(os_name: &str) -> bool {
1159 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001160}
1161
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001162fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1163 if !cfg!(vendor_modules) {
1164 return false;
1165 }
1166 match config {
1167 VirtualMachineConfig::RawConfig(_) => false,
1168 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1169 }
1170}
1171
Jooyung Han21e9b922021-06-26 04:14:16 +09001172fn load_app_config(
1173 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001174 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001175 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001176) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001177 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1178 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001179 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001180
Shikha Panwar22e70452022-10-10 18:32:55 +00001181 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1182 Some(clone_file(file)?)
1183 } else {
1184 None
1185 };
1186
Alan Stokesfda70842023-12-20 17:50:14 +00001187 let vm_payload_config;
1188 let extra_apk_files: Vec<_>;
1189 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001190 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001191 vm_payload_config =
1192 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1193 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1194 extra_apk_files = vm_payload_config
1195 .extra_apks
1196 .iter()
1197 .enumerate()
1198 .map(|(i, apk)| {
1199 File::open(PathBuf::from(&apk.path))
1200 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1201 })
1202 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001203 }
Alan Stokesfda70842023-12-20 17:50:14 +00001204 Payload::PayloadConfig(payload_config) => {
1205 vm_payload_config = create_vm_payload_config(payload_config)?;
1206 extra_apk_files =
1207 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1208 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001209 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001210
Inseob Kim89b24592024-02-23 18:59:43 +09001211 let payload_config_os = vm_payload_config.os.name.as_str();
1212 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1213 bail!("'os' in payload config is deprecated");
1214 }
1215
Inseob Kim172f9eb2023-11-06 17:02:08 +09001216 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001217 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001218 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001219 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001220 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001221
1222 // It is safe to construct a filename based on the os_name because we've already checked that it
1223 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001224 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1225 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001226 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001227
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001228 if let Some(custom_config) = &config.customConfig {
1229 if let Some(file) = custom_config.customKernelImage.as_ref() {
1230 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1231 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001232 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001233
1234 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001235 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001236 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001237 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001238
Chris Wailes6177c662024-05-09 14:37:44 -07001239 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001240 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001241
1242 for param in custom_config.extraKernelCmdlineParams.iter() {
1243 append_kernel_param(param, &mut vm_config);
1244 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001245
1246 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001247 }
1248
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001249 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1250 // so we need to provide it in the kernel cmdline.
1251 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1252 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1253 append_kernel_param("page_shift=14", &mut vm_config);
1254 }
1255
Andrew Walbrancc045902021-07-27 16:06:17 +00001256 if config.memoryMib > 0 {
1257 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001258 }
1259
Chris Wailes6177c662024-05-09 14:37:44 -07001260 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001261 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001262 vm_config.cpuTopology = config.cpuTopology;
Frederick Mayle681254c2024-12-11 19:20:06 -08001263 if config.cpuTopology == CpuTopology::CUSTOM {
1264 bail!("AppConfig doesn't support CpuTopology::CUSTOM");
1265 }
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001266 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001267 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001268
Shikha Panwar22e70452022-10-10 18:32:55 +00001269 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001270 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001271
1272 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1273 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001274 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001275 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001276 temporary_directory,
1277 apk_file,
1278 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001279 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001280 &vm_payload_config,
1281 &mut vm_config,
1282 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001283
Andrew Walbrancc0db522021-07-12 17:03:42 +00001284 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001285}
1286
Inseob Kimff48a7c2024-02-26 22:07:21 +09001287fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1288 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1289 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1290
1291 // microdroid vendor image is OK
1292 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1293 {
1294 return Ok(());
1295 }
1296
1297 if link.starts_with("/vendor") || link.starts_with("/odm") {
1298 bail!("vendor or odm file {} can't be used for VM", link.display());
1299 }
1300
1301 Ok(())
1302}
1303
1304fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1305 config
1306 .disks
1307 .iter()
1308 .flat_map(|disk| disk.partitions.iter())
1309 .filter_map(|partition| partition.image.as_ref())
1310 .try_for_each(check_partition_for_file)?;
1311
1312 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1313 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1314 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1315
1316 Ok(())
1317}
1318
Alan Stokes0d1ef782022-09-27 13:46:35 +01001319fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1320 let mut apk_zip = ZipArchive::new(apk_file)?;
1321 let config_file = apk_zip.by_name(config_path)?;
1322 Ok(serde_json::from_reader(config_file)?)
1323}
1324
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001325fn create_vm_payload_config(
1326 payload_config: &VirtualMachinePayloadConfig,
1327) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001328 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1329 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1330 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001331
1332 let payload_binary_name = &payload_config.payloadBinaryName;
1333 if payload_binary_name.contains('/') {
1334 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1335 }
1336
1337 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001338
1339 // The VM only cares about how many there are, these names are actually ignored.
1340 let extra_apk_count = payload_config.extraApks.len();
1341 let extra_apks =
1342 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1343
Inseob Kim89b24592024-02-23 18:59:43 +09001344 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001345}
1346
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001347/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001348fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001349 temporary_directory: &Path,
1350 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001351) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001352 let id = *next_temporary_image_id;
1353 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001354 CompositeImageFilenames {
1355 composite: temporary_directory.join(format!("composite-{}.img", id)),
1356 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1357 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1358 }
1359}
1360
1361/// Filenames for a composite disk image, including header and footer partitions.
1362#[derive(Clone, Debug, Eq, PartialEq)]
1363struct CompositeImageFilenames {
1364 /// The composite disk image itself.
1365 composite: PathBuf,
1366 /// The header partition image.
1367 header: PathBuf,
1368 /// The footer partition image.
1369 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001370}
1371
Jiyong Park753553b2021-07-12 21:21:09 +09001372/// Checks whether the caller has a specific permission
1373fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001374 if cfg!(early) {
1375 // Skip permission check for early VMs, in favor of SELinux
1376 return Ok(());
1377 }
David Brazdil1f530702022-10-03 12:18:10 +01001378 let calling_pid = get_calling_pid();
1379 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001380 // Root can do anything
1381 if calling_uid == 0 {
1382 return Ok(());
1383 }
1384 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001385 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001386 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001387 Ok(())
1388 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001389 Err(anyhow!("does not have the {} permission", perm))
1390 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001391 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001392}
1393
Jiyong Park753553b2021-07-12 21:21:09 +09001394/// Check whether the caller of the current Binder method is allowed to manage VMs
1395fn check_manage_access() -> binder::Result<()> {
1396 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1397}
1398
Inseob Kim1119d702022-05-02 18:01:58 +09001399/// Check whether the caller of the current Binder method is allowed to create custom VMs
1400fn check_use_custom_virtual_machine() -> binder::Result<()> {
1401 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1402}
1403
Alan Stokes185fe112023-01-10 16:20:55 +00001404/// Return whether a partition is exempt from selinux label checks, because we know that it does
1405/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001406fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001407 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001408 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001409 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001410 || label == "microdroid-apk-idsig"
1411 || label == "payload-metadata"
1412 || label.starts_with("extra-idsig-")
1413}
1414
Alice Wangc206b9b2023-08-28 14:13:51 +00001415/// Returns whether a partition with the given label is safe for a raw config VM.
1416fn is_safe_raw_partition(label: &str) -> bool {
1417 label == "vm-instance"
1418}
1419
Alan Stokes185fe112023-01-10 16:20:55 +00001420/// Check that a file SELinux label is acceptable.
1421///
1422/// 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 +09001423/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001424///
1425/// Note that sepolicy must also grant read access for these types to both virtualization
1426/// service and crosvm.
1427///
1428/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1429/// user devices (W^X).
1430fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1431 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001432 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001433 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001434 | "staging_data_file" // updated/staged APEX images
1435 | "system_file" // immutable dm-verity protected partition
1436 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001437 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001438 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001439 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001440 }
1441}
1442
Alan Stokes185fe112023-01-10 16:20:55 +00001443fn check_label_for_partition(partition: &Partition) -> Result<()> {
1444 let file = partition.image.as_ref().unwrap().as_ref();
1445 check_label_is_allowed(&getfilecon(file)?)
1446 .with_context(|| format!("Partition {} invalid", &partition.label))
1447}
1448
1449fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1450 if let Some(f) = kernel {
1451 check_label_for_file(f, "kernel")?;
1452 }
1453 if let Some(f) = initrd {
1454 check_label_for_file(f, "initrd")?;
1455 }
1456 Ok(())
1457}
1458fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1459 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1460}
1461
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001462/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1463#[derive(Debug)]
1464struct VirtualMachine {
1465 instance: Arc<VmInstance>,
1466}
1467
1468impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001469 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001470 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001471 }
1472}
1473
1474impl Interface for VirtualMachine {}
1475
Devin Moore407df8f2024-08-27 19:39:16 +00001476impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001477 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001478 // Don't check permission. The owner of the VM might have passed this binder object to
1479 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001480 Ok(self.instance.cid as i32)
1481 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001482
Andrew Walbran6b650662021-09-07 13:13:23 +00001483 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001484 // Don't check permission. The owner of the VM might have passed this binder object to
1485 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001486 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001487 }
1488
1489 fn registerCallback(
1490 &self,
1491 callback: &Strong<dyn IVirtualMachineCallback>,
1492 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001493 // Don't check permission. The owner of the VM might have passed this binder object to
1494 // others.
1495 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001496 // TODO: Should this give an error if the VM is already dead?
1497 self.instance.callbacks.add(callback.clone());
1498 Ok(())
1499 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001500
Andrew Walbranf8d94112021-09-07 11:45:36 +00001501 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001502 self.instance
1503 .start()
1504 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1505 .with_log()
1506 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001507 }
1508
Inseob Kima446f802022-07-11 19:46:37 +09001509 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001510 self.instance
1511 .kill()
1512 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1513 .with_log()
1514 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001515 }
1516
Keir Fraser48221ba2024-07-12 14:05:02 +00001517 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1518 let balloon = self
1519 .instance
1520 .get_memory_balloon()
1521 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1522 .with_log()
1523 .or_service_specific_exception(-1)?;
1524 Ok(balloon.try_into().unwrap())
1525 }
1526
1527 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001528 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001529 .set_memory_balloon(num_bytes.try_into().unwrap())
1530 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001531 .with_log()
1532 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001533 }
1534
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001535 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001536 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001537 return Err(Status::new_service_specific_error_str(
1538 IVirtualMachine::ERROR_UNEXPECTED,
1539 Some("Virtual Machine is not running"),
1540 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001541 }
Alan Stokes10c47672022-12-13 17:17:08 +00001542 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001543 if port < VSOCK_PRIV_PORT_MAX {
1544 return Err(Status::new_service_specific_error_str(
1545 IVirtualMachine::ERROR_UNEXPECTED,
1546 Some("Can't connect to privileged port {port}"),
1547 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001548 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001549 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1550 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001551 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001552 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001553 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001554
Devin Moore407df8f2024-08-27 19:39:16 +00001555 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1556 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1557 return Err(Status::new_service_specific_error_str(
1558 IVirtualMachine::ERROR_UNEXPECTED,
1559 Some("Virtual Machine is not running"),
1560 ));
1561 }
1562 let port = port as u32;
1563 if port < VSOCK_PRIV_PORT_MAX {
1564 return Err(Status::new_service_specific_error_str(
1565 IVirtualMachine::ERROR_UNEXPECTED,
1566 Some("Can't connect to privileged port {port}"),
1567 ));
1568 }
1569 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001570 let addr = sockaddr_vm {
1571 svm_family: AF_VSOCK as sa_family_t,
1572 svm_reserved1: 0,
1573 svm_port: port,
1574 svm_cid: cid,
1575 svm_zero: [0u8; 4],
1576 };
1577 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001578 let accessor = Accessor::new(name, get_connection_info);
1579 accessor
1580 .as_binder()
1581 .context("The newly created Accessor should always have a binder")
1582 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1583 }
1584
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001585 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1586 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1587 }
Jiyong Park23b67392024-07-04 13:51:42 +09001588
1589 fn suspend(&self) -> binder::Result<()> {
1590 self.instance
1591 .suspend()
1592 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1593 .with_log()
1594 .or_service_specific_exception(-1)
1595 }
1596
1597 fn resume(&self) -> binder::Result<()> {
1598 self.instance
1599 .resume()
1600 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1601 .with_log()
1602 .or_service_specific_exception(-1)
1603 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001604}
1605
1606impl Drop for VirtualMachine {
1607 fn drop(&mut self) {
1608 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001609 if let Err(e) = self.instance.kill() {
1610 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1611 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001612 }
1613}
1614
1615/// A set of Binders to be called back in response to various events on the VM, such as when it
1616/// dies.
1617#[derive(Debug, Default)]
1618pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1619
1620impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001621 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001622 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001623 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001624 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001625 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001626 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001627 }
1628 }
1629 }
1630
Inseob Kim14cb8692021-08-31 21:50:39 +09001631 /// Call all registered callbacks to notify that the payload is ready to serve.
1632 pub fn notify_payload_ready(&self, cid: Cid) {
1633 let callbacks = &*self.0.lock().unwrap();
1634 for callback in callbacks {
1635 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001636 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001637 }
1638 }
1639 }
1640
Inseob Kim2444af92021-08-31 01:22:50 +09001641 /// Call all registered callbacks to notify that the payload has finished.
1642 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1643 let callbacks = &*self.0.lock().unwrap();
1644 for callback in callbacks {
1645 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001646 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001647 }
1648 }
1649 }
1650
Jooyung Handd0a1732021-11-23 15:26:20 +09001651 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001652 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001653 let callbacks = &*self.0.lock().unwrap();
1654 for callback in callbacks {
1655 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001656 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001657 }
1658 }
1659 }
1660
Andrew Walbrandae07162021-03-12 17:05:20 +00001661 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001662 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001663 let callbacks = &*self.0.lock().unwrap();
1664 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001665 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001666 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001667 }
1668 }
1669 }
1670
1671 /// Add a new callback to the set.
1672 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1673 self.0.lock().unwrap().push(callback);
1674 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001675}
1676
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001677/// The mutable state of the VirtualizationService. There should only be one instance of this
1678/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001679#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001680struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001681 /// The VMs which have been started. When VMs are started a weak reference is added to this
1682 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1683 /// the Binder client are dropped the weak reference here will become invalid, and will be
1684 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001685 vms: Vec<Weak<VmInstance>>,
1686}
1687
1688impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001689 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001690 fn vms(&self) -> Vec<Arc<VmInstance>> {
1691 // Attempt to upgrade the weak pointers to strong pointers.
1692 self.vms.iter().filter_map(Weak::upgrade).collect()
1693 }
1694
1695 /// Add a new VM to the list.
1696 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1697 // Garbage collect any entries from the stored list which no longer exist.
1698 self.vms.retain(|vm| vm.strong_count() > 0);
1699
1700 // Actually add the new VM.
1701 self.vms.push(vm);
1702 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001703
Jiyong Park8611a6c2021-07-09 18:17:44 +09001704 /// Get a VM that corresponds to the given cid
1705 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1706 self.vms().into_iter().find(|vm| vm.cid == cid)
1707 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001708}
1709
Andrew Walbran6b650662021-09-07 13:13:23 +00001710/// Gets the `VirtualMachineState` of the given `VmInstance`.
1711fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001712 match &*instance.vm_state.lock().unwrap() {
1713 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1714 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001715 PayloadState::Starting => VirtualMachineState::STARTING,
1716 PayloadState::Started => VirtualMachineState::STARTED,
1717 PayloadState::Ready => VirtualMachineState::READY,
1718 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001719 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001720 },
1721 VmState::Dead => VirtualMachineState::DEAD,
1722 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001723 }
1724}
1725
David Brazdilf50c7a62023-04-19 14:22:42 +00001726/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001727pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1728 file.as_ref()
1729 .try_clone()
1730 .context("Failed to clone File from ParcelFileDescriptor")
1731 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001732 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001733}
1734
Andrew Walbrand3a84182021-09-07 14:48:52 +00001735/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001736fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001737 file.as_ref().map(clone_file).transpose()
1738}
1739
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001740/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001741fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1742 // SAFETY: ownership is transferred from stream to f
1743 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1744 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001745}
1746
Jiyong Parkdcf17412022-02-08 15:07:23 +09001747/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001748fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1749 VersionReq::parse(s)
1750 .with_context(|| format!("Invalid platform version requirement {}", s))
1751 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001752}
1753
Jiyong Parked180932023-02-24 19:55:41 +09001754/// Create the empty ramdump file
1755fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1756 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1757 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1758 // owner) for readout.
1759 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001760 let ramdump = File::create(ramdump_path)
1761 .context("Failed to prepare ramdump file")
1762 .with_log()
1763 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001764 Ok(ramdump)
1765}
1766
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001767/// Create the empty device tree dump file
1768fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1769 let path = temporary_directory.join("device_tree.dtb");
1770 let file = File::create(path)
1771 .context("Failed to prepare device tree dump file")
1772 .with_log()
1773 .or_service_specific_exception(-1)?;
1774 Ok(file)
1775}
1776
Nikita Ioffe5776f082023-02-10 21:38:26 +00001777fn is_protected(config: &VirtualMachineConfig) -> bool {
1778 match config {
1779 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1780 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1781 }
1782}
1783
1784fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1785 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001786 return Err(anyhow!("Can't use gdb with protected VMs"))
1787 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001788 }
1789
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001790 if get_debug_level(config) == Some(DebugLevel::NONE) {
1791 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1792 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001793 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001794
1795 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001796}
1797
Shikha Panwar61a74b52024-02-16 13:17:01 +00001798fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1799 match config {
1800 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1801 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1802 }
1803}
1804
Alan Stokesc96b35e2024-05-03 13:21:20 +01001805fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1806 match config {
1807 VirtualMachineConfig::RawConfig(_) => true,
1808 VirtualMachineConfig::AppConfig(config) => {
1809 let Some(custom) = &config.customConfig else { return true };
1810 custom.wantUpdatable
1811 }
1812 }
1813}
1814
Nikita Ioffe5776f082023-02-10 21:38:26 +00001815fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1816 match config {
1817 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001818 VirtualMachineConfig::AppConfig(config) => {
1819 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1820 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001821 }
1822}
1823
Nikita Ioffe631717e2023-09-05 13:38:07 +01001824fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1825 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1826 if let Some(custom_config) = &config.customConfig {
1827 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1828 return Err(anyhow!("vendor modules feature is disabled"))
1829 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1830 }
1831 }
1832 Ok(())
1833}
1834
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001835fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1836 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1837 if let Some(custom_config) = &config.customConfig {
1838 if !custom_config.devices.is_empty() {
1839 return Err(anyhow!("device assignment feature is disabled"))
1840 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1841 }
1842 }
1843 Ok(())
1844}
1845
Alan Stokesfda70842023-12-20 17:50:14 +00001846fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1847 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1848 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1849 if !payload_config.extraApks.is_empty() {
1850 return Err(anyhow!("multi-tenant feature is disabled"))
1851 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1852 }
1853 Ok(())
1854}
1855
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001856fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1857 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1858 if let Some(custom_config) = &config.customConfig {
1859 if !custom_config.extraKernelCmdlineParams.is_empty() {
1860 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1861 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1862 }
1863 }
1864 Ok(())
1865}
1866
Nikita Ioffe99548382024-10-21 15:54:46 +00001867fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1868 match config {
1869 VirtualMachineConfig::RawConfig(config) => {
1870 if !config.teeServices.is_empty() {
1871 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1872 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1873 }
1874 }
1875 VirtualMachineConfig::AppConfig(config) => {
1876 if let Some(custom_config) = &config.customConfig {
1877 if !custom_config.teeServices.is_empty() {
1878 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1879 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1880 }
1881 }
1882 }
1883 };
1884 Ok(())
1885}
1886
Nikita Ioffef934e812024-07-05 15:44:41 +00001887fn check_protected_vm_is_supported() -> binder::Result<()> {
1888 let is_pvm_supported =
1889 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1890 if is_pvm_supported {
1891 Ok(())
1892 } else {
1893 Err(anyhow!("pVM is not supported"))
1894 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1895 }
1896}
1897
Nikita Ioffe631717e2023-09-05 13:38:07 +01001898fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1899 if !cfg!(vendor_modules) {
1900 check_no_vendor_modules(config)?;
1901 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001902 if !cfg!(device_assignment) {
1903 check_no_devices(config)?;
1904 }
Alan Stokesfda70842023-12-20 17:50:14 +00001905 if !cfg!(multi_tenant) {
1906 check_no_extra_apks(config)?;
1907 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001908 if !cfg!(debuggable_vms_improvements) {
1909 check_no_extra_kernel_cmdline_params(config)?;
1910 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001911 if !cfg!(tee_services_allowlist) {
1912 check_no_tee_services(config)?;
1913 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001914 Ok(())
1915}
1916
Inseob Kimecde8c02024-09-03 13:11:08 +09001917fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1918 check_no_vendor_modules(config)?;
1919 check_no_devices(config)?;
1920
1921 Ok(())
1922}
1923
Inseob Kim0168b462022-12-27 14:54:35 +09001924fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001925 fd: Option<&ParcelFileDescriptor>,
1926 tag: String,
1927) -> Result<Option<File>, Status> {
1928 if let Some(fd) = fd {
1929 return Ok(Some(clone_file(fd)?));
1930 }
1931
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001932 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001933 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001934
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001935 let mut reader = BufReader::new(File::from(read_fd));
1936 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001937
1938 std::thread::spawn(move || loop {
1939 let mut buf = vec![];
1940 match reader.read_until(b'\n', &mut buf) {
1941 Ok(0) => {
1942 // EOF
1943 return;
1944 }
1945 Ok(size) => {
1946 if buf[size - 1] == b'\n' {
1947 buf.pop();
1948 }
1949 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1950 }
1951 Err(e) => {
1952 error!("Could not read console pipe: {:?}", e);
1953 return;
1954 }
1955 };
1956 });
1957
1958 Ok(Some(write_fd))
1959}
1960
Jooyung Han35edb8f2021-07-01 16:17:16 +09001961/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1962/// it doesn't require that T implements Clone.
1963enum BorrowedOrOwned<'a, T> {
1964 Borrowed(&'a T),
1965 Owned(T),
1966}
1967
1968impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1969 fn as_ref(&self) -> &T {
1970 match self {
1971 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001972 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001973 }
1974 }
1975}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001976
1977/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1978#[derive(Debug, Default)]
1979struct VirtualMachineService {
1980 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001981 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001982}
1983
1984impl Interface for VirtualMachineService {}
1985
1986impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001987 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1988 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001989 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001990 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001991 vm.update_payload_state(PayloadState::Started)
1992 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001993 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001994
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001995 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1996 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001997 Ok(())
1998 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001999 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002000 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002001 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002002 }
Inseob Kim2444af92021-08-31 01:22:50 +09002003
Inseob Kimc7d28c72021-10-25 14:28:10 +00002004 fn notifyPayloadReady(&self) -> binder::Result<()> {
2005 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002006 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002007 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002008 vm.update_payload_state(PayloadState::Ready)
2009 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002010 vm.callbacks.notify_payload_ready(cid);
2011 Ok(())
2012 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002013 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002014 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002015 }
2016 }
2017
Inseob Kimc7d28c72021-10-25 14:28:10 +00002018 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2019 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002020 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002021 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002022 vm.update_payload_state(PayloadState::Finished)
2023 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002024 vm.callbacks.notify_payload_finished(cid, exit_code);
2025 Ok(())
2026 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002027 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002028 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002029 }
2030 }
2031
Alan Stokes2bead0d2022-09-05 16:58:34 +01002032 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002033 let cid = self.cid;
2034 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002035 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002036 vm.update_payload_state(PayloadState::Finished)
2037 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002038 vm.callbacks.notify_error(cid, error_code, message);
2039 Ok(())
2040 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002041 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002042 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002043 }
2044 }
Alice Wangc2fec932023-02-23 16:24:02 +00002045
Shikha Panware45e9422024-02-28 21:18:10 +00002046 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2047 if !is_secretkeeper_supported() {
2048 return Err(StatusCode::NAME_NOT_FOUND)?;
2049 }
2050 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2051 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002052 }
2053
Alice Wange64dd182024-01-17 15:57:55 +00002054 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2055 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002056 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002057}
2058
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002059fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002060 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2061 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002062}
2063
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002064impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002065 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002066 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002067 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002068 BinderFeatures::default(),
2069 )
2070 }
2071}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002072
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002073struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2074
2075impl Interface for SecretkeeperProxy {}
2076
2077impl ISecretkeeper for SecretkeeperProxy {
2078 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2079 // Pass the request to the channel, and read the response.
2080 self.0.processSecretManagementRequest(req)
2081 }
2082
2083 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2084 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2085 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2086 }
2087
2088 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2089 self.0.deleteIds(ids)
2090 }
2091
2092 fn deleteAll(&self) -> binder::Result<()> {
2093 self.0.deleteAll()
2094 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002095
2096 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2097 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2098 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2099 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2100 // use this API from the proxy.
2101 Err(ExceptionCode::SECURITY.into())
2102 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002103}
2104
2105struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2106
2107impl Interface for AuthGraphKeyExchangeProxy {}
2108
2109impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2110 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2111 self.0.create()
2112 }
2113
2114 fn init(
2115 &self,
2116 peer_pub_key: &PubKey,
2117 peer_id: &Identity,
2118 peer_nonce: &[u8],
2119 peer_version: i32,
2120 ) -> binder::Result<KeInitResult> {
2121 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2122 }
2123
2124 fn finish(
2125 &self,
2126 peer_pub_key: &PubKey,
2127 peer_id: &Identity,
2128 peer_signature: &SessionIdSignature,
2129 peer_nonce: &[u8],
2130 peer_version: i32,
2131 own_key: &Key,
2132 ) -> binder::Result<SessionInfo> {
2133 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2134 }
2135
2136 fn authenticationComplete(
2137 &self,
2138 peer_signature: &SessionIdSignature,
2139 shared_keys: &[AuthgraphArc; 2],
2140 ) -> binder::Result<[AuthgraphArc; 2]> {
2141 self.0.authenticationComplete(peer_signature, shared_keys)
2142 }
2143}
2144
Inseob Kimecde8c02024-09-03 13:11:08 +09002145// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002146#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002147struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002148 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002149 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002150 path: String,
2151}
2152
2153#[derive(Debug, Default, Deserialize)]
2154struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002155 early_vm: Vec<EarlyVm>,
2156}
2157
Inseob Kim7e1877b2024-11-07 17:28:56 +09002158static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2159 LazyLock::new(|| Mutex::new(HashMap::new()));
2160
Inseob Kimecde8c02024-09-03 13:11:08 +09002161fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2162 match partition {
2163 "system" => Ok(100..200),
2164 "system_ext" | "product" => Ok(200..300),
2165 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2166 }
2167}
2168
Inseob Kim7e1877b2024-11-07 17:28:56 +09002169fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002170 if !xml_path.exists() {
2171 bail!("{} doesn't exist", xml_path.display());
2172 }
2173
2174 let xml =
2175 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2176 let xml = String::from_utf8(xml)
2177 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2178 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2179 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2180
Inseob Kim7e1877b2024-11-07 17:28:56 +09002181 Ok(early_vms.early_vm)
2182}
Inseob Kimecde8c02024-09-03 13:11:08 +09002183
Inseob Kim7e1877b2024-11-07 17:28:56 +09002184fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2185 for early_vm in early_vms {
2186 let cid = early_vm
2187 .cid
2188 .try_into()
2189 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2190
2191 ensure!(
2192 cid_range.contains(&cid),
2193 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2194 early_vm.name
2195 );
2196 }
2197 Ok(())
2198}
2199
2200fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2201 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2202
2203 if let Some(result) = cache.get(partition) {
2204 return Ok(result.clone());
2205 }
2206
2207 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2208 let mut early_vms = Vec::new();
2209 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2210 match entry {
2211 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2212 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2213 }
2214 }
2215
2216 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2217 .with_context(|| format!("CID validation for {partition} failed"))?;
2218
2219 cache.insert(partition.to_owned(), early_vms.clone());
2220
2221 Ok(early_vms)
2222}
2223
2224fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2225 let mut found_vm: Option<&EarlyVm> = None;
2226
2227 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002228 if early_vm.name != name {
2229 continue;
2230 }
2231
Inseob Kimecde8c02024-09-03 13:11:08 +09002232 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002233 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002234 }
2235
2236 found_vm = Some(early_vm);
2237 }
2238
Inseob Kim7e1877b2024-11-07 17:28:56 +09002239 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002240}
2241
2242fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002243 let early_vms = get_early_vms_in_partition(partition)
2244 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2245
2246 Ok(find_early_vm(&early_vms, name)
2247 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2248 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002249}
2250
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002251#[cfg(test)]
2252mod tests {
2253 use super::*;
2254
2255 #[test]
2256 fn test_is_allowed_label_for_partition() -> Result<()> {
2257 let expected_results = vec![
2258 ("u:object_r:system_file:s0", true),
2259 ("u:object_r:apk_data_file:s0", true),
2260 ("u:object_r:app_data_file:s0", false),
2261 ("u:object_r:app_data_file:s0:c512,c768", false),
2262 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2263 ("invalid", false),
2264 ("user:role:apk_data_file:severity:categories", true),
2265 ("user:role:apk_data_file:severity:categories:extraneous", false),
2266 ];
2267
2268 for (label, expected_valid) in expected_results {
2269 let context = SeContext::new(label)?;
2270 let result = check_label_is_allowed(&context);
2271 if expected_valid {
2272 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2273 } else if result.is_ok() {
2274 bail!("Expected label {} to be disallowed", label);
2275 }
2276 }
2277 Ok(())
2278 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002279
2280 #[test]
2281 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2282 let apk = tempfile::tempfile().unwrap();
2283 let idsig = tempfile::tempfile().unwrap();
2284
2285 let ret = create_or_update_idsig_file(
2286 &ParcelFileDescriptor::new(apk),
2287 &ParcelFileDescriptor::new(idsig),
2288 );
2289 assert!(ret.is_err(), "should fail");
2290 Ok(())
2291 }
2292
2293 #[test]
2294 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2295 let tmp_dir = tempfile::TempDir::new().unwrap();
2296 let apk = File::open(tmp_dir.path()).unwrap();
2297 let idsig = tempfile::tempfile().unwrap();
2298
2299 let ret = create_or_update_idsig_file(
2300 &ParcelFileDescriptor::new(apk),
2301 &ParcelFileDescriptor::new(idsig),
2302 );
2303 assert!(ret.is_err(), "should fail");
2304 Ok(())
2305 }
2306
2307 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2308 /// on ext4 filesystem is passed.
2309 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2310 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2311 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2312 #[test]
2313 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2314 // APEXes are backed by the ext4.
2315 let apk = File::open("/apex/com.android.virt/").unwrap();
2316 let idsig = tempfile::tempfile().unwrap();
2317
2318 let ret = create_or_update_idsig_file(
2319 &ParcelFileDescriptor::new(apk),
2320 &ParcelFileDescriptor::new(idsig),
2321 );
2322 assert!(ret.is_err(), "should fail");
2323 Ok(())
2324 }
Jiyong Park8d192952023-06-26 14:29:51 +09002325
2326 #[test]
2327 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2328 use std::io::Seek;
2329
2330 // Pick any APK
2331 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2332 let mut idsig = tempfile::tempfile().unwrap();
2333
2334 create_or_update_idsig_file(
2335 &ParcelFileDescriptor::new(apk.try_clone()?),
2336 &ParcelFileDescriptor::new(idsig.try_clone()?),
2337 )?;
2338 let modified_orig = idsig.metadata()?.modified()?;
2339 apk.rewind()?;
2340 idsig.rewind()?;
2341
2342 // Call the function again
2343 create_or_update_idsig_file(
2344 &ParcelFileDescriptor::new(apk.try_clone()?),
2345 &ParcelFileDescriptor::new(idsig.try_clone()?),
2346 )?;
2347 let modified_new = idsig.metadata()?.modified()?;
2348 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2349 Ok(())
2350 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002351
2352 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002353 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2354 use std::io::Read;
2355
2356 // Pick any APK
2357 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2358 let idsig_empty = tempfile::tempfile().unwrap();
2359 let mut idsig_invalid = tempfile::tempfile().unwrap();
2360 idsig_invalid.write_all(b"Oops")?;
2361
2362 // Create new idsig
2363 create_or_update_idsig_file(
2364 &ParcelFileDescriptor::new(apk.try_clone()?),
2365 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2366 )?;
2367 apk.rewind()?;
2368
2369 // Update idsig_invalid
2370 create_or_update_idsig_file(
2371 &ParcelFileDescriptor::new(apk.try_clone()?),
2372 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2373 )?;
2374
2375 // Ensure the 2 idsig files have same size!
2376 assert!(
2377 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2378 "idsig files differ in size"
2379 );
2380 // Ensure the 2 idsig files have same content!
2381 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2382 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2383 }
2384 Ok(())
2385 }
2386 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002387 fn test_append_kernel_param_first_param() {
2388 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2389 append_kernel_param("foo=1", &mut vm_config);
2390 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2391 }
2392
2393 #[test]
2394 fn test_append_kernel_param() {
2395 let mut vm_config =
2396 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2397 append_kernel_param("bar=42", &mut vm_config);
2398 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2399 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002400
Inseob Kim46257382024-01-03 15:41:22 +09002401 fn test_extract_os_name_from_config_path(
2402 path: &Path,
2403 expected_result: Option<&str>,
2404 ) -> Result<()> {
2405 let result = extract_os_name_from_config_path(path);
2406 if result.as_deref() != expected_result {
2407 bail!("Expected {:?} but was {:?}", expected_result, &result)
2408 }
2409 Ok(())
2410 }
2411
2412 #[test]
2413 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2414 test_extract_os_name_from_config_path(
2415 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2416 Some("microdroid"),
2417 )
2418 }
2419
2420 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002421 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2422 test_extract_os_name_from_config_path(
2423 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2424 Some("microdroid_16k"),
2425 )
2426 }
2427
2428 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002429 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2430 test_extract_os_name_from_config_path(
2431 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2432 Some("microdroid_gki-android14-6.1"),
2433 )
2434 }
2435
2436 #[test]
2437 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2438 test_extract_os_name_from_config_path(
2439 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2440 None,
2441 )
2442 }
2443
2444 #[test]
2445 fn test_extract_os_name_from_configs() -> Result<()> {
2446 let tmp_dir = tempfile::TempDir::new()?;
2447 let tmp_dir_path = tmp_dir.path().to_owned();
2448
2449 let mut os_names: HashSet<String> = HashSet::new();
2450 os_names.insert("microdroid".to_owned());
2451 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2452 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2453
2454 // config files
2455 for os_name in &os_names {
2456 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2457 }
2458
2459 // fake files not related to configs
2460 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2461 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2462
2463 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2464 Some(s) => s.to_owned(),
2465 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2466 };
2467
2468 let result = extract_os_names_from_configs(&glob_pattern)?;
2469 if result != os_names {
2470 bail!("Expected {:?} but was {:?}", os_names, result);
2471 }
2472 Ok(())
2473 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002474
2475 #[test]
2476 fn test_find_early_vms_from_xml() -> Result<()> {
2477 let tmp_dir = tempfile::TempDir::new()?;
2478 let tmp_dir_path = tmp_dir.path().to_owned();
2479 let xml_path = tmp_dir_path.join("early_vms.xml");
2480
2481 std::fs::write(
2482 &xml_path,
2483 br#"<?xml version="1.0" encoding="utf-8"?>
2484 <early_vms>
2485 <early_vm>
2486 <name>vm_demo_native_early</name>
2487 <cid>123</cid>
2488 <path>/system/bin/vm_demo_native_early</path>
2489 </early_vm>
2490 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002491 <name>vm_demo_native_early_2</name>
2492 <cid>456</cid>
2493 <path>/system/bin/vm_demo_native_early_2</path>
2494 </early_vm>
2495 </early_vms>
2496 "#,
2497 )?;
2498
2499 let cid_range = 100..1000;
2500
2501 let early_vms = get_early_vms_in_path(&xml_path)?;
2502 validate_cid_range(&early_vms, &cid_range)?;
2503
2504 let test_cases = [
2505 (
2506 "vm_demo_native_early",
2507 EarlyVm {
2508 name: "vm_demo_native_early".to_owned(),
2509 cid: 123,
2510 path: "/system/bin/vm_demo_native_early".to_owned(),
2511 },
2512 ),
2513 (
2514 "vm_demo_native_early_2",
2515 EarlyVm {
2516 name: "vm_demo_native_early_2".to_owned(),
2517 cid: 456,
2518 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2519 },
2520 ),
2521 ];
2522
2523 for (name, expected) in test_cases {
2524 let result = find_early_vm(&early_vms, name)?;
2525 assert_eq!(result, &expected);
2526 }
2527
2528 Ok(())
2529 }
2530
2531 #[test]
2532 fn test_invalid_cid_validation() -> Result<()> {
2533 let tmp_dir = tempfile::TempDir::new()?;
2534 let xml_path = tmp_dir.path().join("early_vms.xml");
2535
2536 let cid_range = 100..1000;
2537
2538 for cid in [-1, 999999] {
2539 std::fs::write(
2540 &xml_path,
2541 format!(
2542 r#"<?xml version="1.0" encoding="utf-8"?>
2543 <early_vms>
2544 <early_vm>
2545 <name>vm_demo_invalid_cid</name>
2546 <cid>{cid}</cid>
2547 <path>/system/bin/vm_demo_invalid_cid</path>
2548 </early_vm>
2549 </early_vms>
2550 "#
2551 ),
2552 )?;
2553
2554 let early_vms = get_early_vms_in_path(&xml_path)?;
2555 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2556 }
2557
2558 Ok(())
2559 }
2560
2561 #[test]
2562 fn test_duplicated_early_vms() -> Result<()> {
2563 let tmp_dir = tempfile::TempDir::new()?;
2564 let tmp_dir_path = tmp_dir.path().to_owned();
2565 let xml_path = tmp_dir_path.join("early_vms.xml");
2566
2567 std::fs::write(
2568 &xml_path,
2569 br#"<?xml version="1.0" encoding="utf-8"?>
2570 <early_vms>
2571 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002572 <name>vm_demo_duplicated_name</name>
2573 <cid>456</cid>
2574 <path>/system/bin/vm_demo_duplicated_name_1</path>
2575 </early_vm>
2576 <early_vm>
2577 <name>vm_demo_duplicated_name</name>
2578 <cid>789</cid>
2579 <path>/system/bin/vm_demo_duplicated_name_2</path>
2580 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002581 </early_vms>
2582 "#,
2583 )?;
2584
2585 let cid_range = 100..1000;
2586
Inseob Kim7e1877b2024-11-07 17:28:56 +09002587 let early_vms = get_early_vms_in_path(&xml_path)?;
2588 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002589
Inseob Kim7e1877b2024-11-07 17:28:56 +09002590 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002591
2592 Ok(())
2593 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002594}