blob: 15a80a64f24a62c16bb81aa75bbe7b248cb2ddc3 [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};
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000070use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090071use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000072use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000073use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090074use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090075use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000076use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000077use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090078use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090079use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090080use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000081use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000082use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090083use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090084use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090086use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000087use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090088use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090089use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000090use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010092use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090093use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010094use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000095use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090096use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097
David Brazdil41d1a872022-10-05 14:44:19 +010098/// The unique ID of a VM used (together with a port number) for vsock communication.
99pub type Cid = u32;
100
David Brazdil4b4c5102022-12-19 22:56:20 +0000101pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
102
Devin Moore407df8f2024-08-27 19:39:16 +0000103/// Vsock privileged ports are below this number.
104const VSOCK_PRIV_PORT_MAX: u32 = 1024;
105
Jooyung Han95884632021-07-06 22:27:54 +0900106/// The size of zero.img.
107/// Gaps in composite disk images are filled with a shared zero.img.
108const ZERO_FILLER_SIZE: u64 = 4096;
109
David Brazdilf50c7a62023-04-19 14:22:42 +0000110/// Magic string for the instance image
111const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
112
113/// Version of the instance image format
114const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
115
Alan Stokes0d1ef782022-09-27 13:46:35 +0100116const MICRODROID_OS_NAME: &str = "microdroid";
117
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000118const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000119 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000120
David Brazdilf50c7a62023-04-19 14:22:42 +0000121const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
122
123/// crosvm requires all partitions to be a multiple of 4KiB.
124const PARTITION_GRANULARITY_BYTES: u64 = 4096;
125
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000126const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
127
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100128pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
129 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900130 if cfg!(early) {
131 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
132 } else {
133 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
134 .expect("Could not connect to VirtualizationServiceInternal")
135 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100136 });
137static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
138 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000139
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000140fn create_or_update_idsig_file(
141 input_fd: &ParcelFileDescriptor,
142 idsig_fd: &ParcelFileDescriptor,
143) -> Result<()> {
144 let mut input = clone_file(input_fd)?;
145 let metadata = input.metadata().context("failed to get input metadata")?;
146 if !metadata.is_file() {
147 bail!("input is not a regular file");
148 }
Alan Stokes25f69362023-03-06 16:51:54 +0000149 let mut sig =
150 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
151 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000152
153 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900154
155 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
156 // if the idsig file already has the same APK digest.
157 if output.metadata()?.len() > 0 {
158 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
159 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
160 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
161 return Ok(());
162 }
163 }
164 // if we fail to read v4signature from output, that's fine. User can pass a random file.
165 // We will anyway overwrite the file to the v4signature generated from input_fd.
166 }
167
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000168 output
169 .seek(SeekFrom::Start(0))
170 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000171 output.set_len(0).context("failed to set_len on the idsig output")?;
172 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000173 Ok(())
174}
175
Alan Stokes25f69362023-03-06 16:51:54 +0000176fn get_current_sdk() -> Result<u32> {
177 let current_sdk = system_properties::read("ro.build.version.sdk")?;
178 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
179 current_sdk.parse().context("Malformed SDK version")
180}
181
David Brazdil4b4c5102022-12-19 22:56:20 +0000182pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
183 for dir_entry in read_dir(path)? {
184 remove_file(dir_entry?.path())?;
185 }
186 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100187}
188
David Brazdil528e0472022-10-10 15:06:02 +0100189/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000190#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000191pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900192 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000193}
194
Shikha Panward8e35422021-10-11 13:51:27 +0000195impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000197 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
198 let state = &mut *self.state.lock().unwrap();
199 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000201 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
203 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
208 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000209 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000211 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000212 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000213 .or(Err(StatusCode::UNKNOWN_ERROR))?;
214 }
215 Ok(())
216 }
217}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000218impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
220 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221 ///
222 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000224 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000225 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900226 console_out_fd: Option<&ParcelFileDescriptor>,
227 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000228 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000229 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000230 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000231 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900232 let ret = self.create_vm_internal(
233 config,
234 console_out_fd,
235 console_in_fd,
236 log_fd,
237 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000238 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900239 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000240 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000241 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000242 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000243
Shikha Panwar61a74b52024-02-16 13:17:01 +0000244 /// Allocate a new instance_id to the VM
245 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000246 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000247 GLOBAL_SERVICE.allocateInstanceId()
248 }
249
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 /// Initialise an empty partition image of the given size to be used as a writable partition.
251 fn initializeWritablePartition(
252 &self,
253 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000254 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900255 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000256 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900257 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900258 let size_bytes = size_bytes
259 .try_into()
260 .with_context(|| format!("Invalid size: {}", size_bytes))
261 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000262 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000263 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000264 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000265 image
266 .seek(SeekFrom::Start(0))
267 .context("failed to move cursor to start")
268 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900269 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700270 // Set the file length. In most filesystems, this will not allocate any physical disk
271 // space, it will only change the logical size.
272 image
273 .set_len(size_bytes)
274 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900275 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276
277 match partition_type {
278 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700279 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
280 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000281 _ => Err(Error::new(
282 ErrorKind::Unsupported,
283 format!("Unsupported partition type {:?}", partition_type),
284 )),
285 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900286 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
287 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000288
289 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000290 }
291
Jiyong Park0a248432021-08-20 23:32:39 +0900292 /// Creates or update the idsig file by digesting the input APK file.
293 fn createOrUpdateIdsigFile(
294 &self,
295 input_fd: &ParcelFileDescriptor,
296 idsig_fd: &ParcelFileDescriptor,
297 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900298 check_manage_access()?;
299
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900301 Ok(())
302 }
303
Andrew Walbran320b5602021-03-04 16:11:12 +0000304 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
305 /// and as such is only permitted from the shell user.
306 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000307 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000308 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000309 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900310
311 /// Get a list of assignable device types.
312 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
313 // Delegate to the global service, including checking the permission.
314 GLOBAL_SERVICE.getAssignableDevices()
315 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100316
Inseob Kim46257382024-01-03 15:41:22 +0900317 /// Get a list of supported OSes.
318 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
319 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
320 }
321
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> {
410 match path.components().nth(1) {
411 Some(std::path::Component::Normal(partition)) => {
412 Ok(partition.to_string_lossy().into_owned())
413 }
414 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
415 .or_service_specific_exception(-1),
416 }
417}
418
Jiyong Park8611a6c2021-07-09 18:17:44 +0900419impl VirtualizationService {
420 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000421 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900422 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000423
Inseob Kimecde8c02024-09-03 13:11:08 +0900424 fn create_early_vm_context(
425 &self,
426 config: &VirtualMachineConfig,
427 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
428 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
429 let link = fs::read_link(&calling_exe_path)
430 .context(format!("can't read_link '{calling_exe_path}'"))
431 .or_service_specific_exception(-1)?;
432 let partition = find_partition(&link)?;
433
434 let name = match config {
435 VirtualMachineConfig::RawConfig(config) => &config.name,
436 VirtualMachineConfig::AppConfig(config) => &config.name,
437 };
438 let early_vm =
439 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
440 if Path::new(&early_vm.path) != link {
441 return Err(anyhow!(
442 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
443 &early_vm.path,
444 link.display()
445 ))
446 .or_service_specific_exception(-1);
447 }
448
449 let cid = early_vm.cid as Cid;
450 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
451
452 let context = EarlyVmContext::new(cid, temp_dir.clone())
453 .context(format!("Can't create early vm contexts for {cid}"))
454 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900455
Jiyong Park690c1ca2024-11-28 18:06:50 +0900456 if requires_vm_service(config) {
457 // Start VM service listening for connections from the new CID on port=CID.
458 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
459 let port = cid;
460 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
461 .context(format!("Could not start RpcServer on port {port}"))
462 .or_service_specific_exception(-1)?;
463 vm_server.start();
464 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
465 } else {
466 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
467 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900468 }
469
David Brazdil209074a2023-01-12 16:44:51 +0000470 fn create_vm_context(
471 &self,
472 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900473 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000474 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000475 const NUM_ATTEMPTS: usize = 5;
476
477 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000478 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000479 let cid = vm_context.getCid()? as Cid;
480 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900481
482 // We don't need to start the VM service for custom VMs.
483 if !requires_vm_service(config) {
484 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
485 }
486
David Brazdil8cf8f482022-11-23 14:21:26 +0000487 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
488
489 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000490 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000491 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000492 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000493 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900494 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000495 }
496 Err(err) => {
497 warn!("Could not start RpcServer on port {}: {}", port, err);
498 }
499 }
500 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900501 Err(anyhow!("Too many attempts to create VM context failed"))
502 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000503 }
504
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000505 fn create_vm_internal(
506 &self,
507 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900508 console_out_fd: Option<&ParcelFileDescriptor>,
509 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000510 log_fd: Option<&ParcelFileDescriptor>,
511 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000512 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000513 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000514 let requester_uid = get_calling_uid();
515 let requester_debug_pid = get_calling_pid();
516
Nikita Ioffe631717e2023-09-05 13:38:07 +0100517 check_config_features(config)?;
518
Inseob Kimecde8c02024-09-03 13:11:08 +0900519 if cfg!(early) {
520 check_config_allowed_for_early_vms(config)?;
521 }
522
Nikita Ioffeb1416122024-10-22 12:18:49 +0000523 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
524 info!("callers secontext: {}", caller_secontext);
525
David Brazdil209074a2023-01-12 16:44:51 +0000526 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900527 let (vm_context, cid, temporary_directory) = if cfg!(early) {
528 self.create_early_vm_context(config)?
529 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900530 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900531 };
Inseob Kim1119d702022-05-02 18:01:58 +0900532
Alan Stokesfda70842023-12-20 17:50:14 +0000533 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100534 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900535 }
536
Nikita Ioffe5776f082023-02-10 21:38:26 +0000537 let gdb_port = extract_gdb_port(config);
538
539 // Additional permission checks if caller request gdb.
540 if gdb_port.is_some() {
541 check_gdb_allowed(config)?;
542 }
543
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000544 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900545
Jaewan Kimf3143242024-03-15 06:56:31 +0000546 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000547 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900548 Some(prepare_ramdump_file(&temporary_directory)?)
549 } else {
550 None
551 };
552
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000553 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900554 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100555 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900556 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100557 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100558 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
559 Some(clone_file(fd)?)
560 } else if debug_config.dump_device_tree {
561 Some(prepare_dump_dt_file(&temporary_directory)?)
562 } else {
563 None
564 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000565
566 // Counter to generate unique IDs for temporary image files.
567 let mut next_temporary_image_id = 0;
568 // Files which are referred to from composite images. These must be mapped to the crosvm
569 // child process, and not closed before it is started.
570 let mut indirect_files = vec![];
571
Alan Stokes7bc146c2022-10-20 17:10:32 +0100572 let (is_app_config, config) = match config {
573 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
574 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900575 let config = load_app_config(config, &debug_config, &temporary_directory)
576 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900577 *is_protected = config.protectedVm;
578 let message = format!("Failed to load app config: {:?}", e);
579 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900580 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900581 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100582 (true, BorrowedOrOwned::Owned(config))
583 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000584 };
585 let config = config.as_ref();
586 *is_protected = config.protectedVm;
587
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000588 if !config.teeServices.is_empty() {
589 check_tee_service_permission(&caller_secontext, &config.teeServices)
590 .with_log()
591 .or_binder_exception(ExceptionCode::SECURITY)?;
592 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000593
Jiyong Park3051ffe2024-11-26 14:41:58 +0900594 let kernel = maybe_clone_file(&config.kernel)?;
595 let initrd = maybe_clone_file(&config.initrd)?;
596
597 if config.protectedVm {
598 // Fail fast with a meaningful error message in case device doesn't support pVMs.
599 check_protected_vm_is_supported()?;
600
601 // In a protected VM, we require custom kernels to come from a trusted source
602 // (b/237054515).
603 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
604
605 // Check if partition images are labeled incorrectly. This is to prevent random images
606 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
607 // from being loaded in a pVM. This applies to everything but the instance image in the
608 // raw config, and everything but the non-executable, generated partitions in the app
609 // config.
610 config
611 .disks
612 .iter()
613 .flat_map(|disk| disk.partitions.iter())
614 .filter(|partition| {
615 if is_app_config {
616 !is_safe_app_partition(&partition.label)
617 } else {
618 !is_safe_raw_partition(&partition.label)
619 }
620 })
621 .try_for_each(check_label_for_partition)
622 .or_service_specific_exception(-1)?;
623 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000624
Inseob Kimff48a7c2024-02-26 22:07:21 +0900625 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
626 // have unstable interfaces.
627 // TODO(b/316431494): remove once Treble interfaces are stabilized.
628 check_partitions_for_files(config).or_service_specific_exception(-1)?;
629
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000630 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900631 write_zero_filler(&zero_filler_path)
632 .context("Failed to make composite image")
633 .with_log()
634 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000635
636 // Assemble disk images if needed.
637 let disks = config
638 .disks
639 .iter()
640 .map(|disk| {
641 assemble_disk_image(
642 disk,
643 &zero_filler_path,
644 &temporary_directory,
645 &mut next_temporary_image_id,
646 &mut indirect_files,
647 )
648 })
649 .collect::<Result<Vec<DiskFile>, _>>()?;
650
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700651 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
652
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000653 let (cpus, host_cpu_topology) = match config.cpuTopology {
654 CpuTopology::MATCH_HOST => (None, true),
655 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
Frederick Mayle681254c2024-12-11 19:20:06 -0800656 CpuTopology::CUSTOM => (
657 NonZeroU32::new(
658 u32::try_from(config.customVcpuCount)
659 .context("bad customVcpuCount")
660 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
661 ),
662 false,
663 ),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000664 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900665 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
666 .with_log()
667 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000668 }
669 };
670
David Brazdil2dfefd12023-11-17 14:07:36 +0000671 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900672 let mut set = HashSet::new();
673 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900674 let path = canonicalize(device)
675 .with_context(|| format!("can't canonicalize {device}"))
676 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900677 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900678 return Err(anyhow!("duplicated device {device}"))
679 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900680 }
681 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000682 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000683 let dtbo_file = File::from(
684 GLOBAL_SERVICE
685 .getDtboFile()?
686 .as_ref()
687 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900688 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000689 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
690 );
691 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900692 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000693 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900694 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900695 let display_config = if cfg!(paravirtualized_devices) {
696 config
697 .displayConfig
698 .as_ref()
699 .map(DisplayConfig::new)
700 .transpose()
701 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
702 } else {
703 None
704 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700705 let gpu_config = if cfg!(paravirtualized_devices) {
706 config
707 .gpuConfig
708 .as_ref()
709 .map(GpuConfig::new)
710 .transpose()
711 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
712 } else {
713 None
714 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900715
Jeongik Chac181be72024-03-27 00:18:30 +0900716 let input_device_options = if cfg!(paravirtualized_devices) {
717 config
718 .inputDevices
719 .iter()
720 .map(to_input_device_option_from)
721 .collect::<Result<Vec<InputDeviceOption>, _>>()
722 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
723 } else {
724 vec![]
725 };
726
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900727 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900728 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900729 if *is_protected {
730 return Err(anyhow!("Network feature is not supported for pVM yet"))
731 .with_log()
732 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
733 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900734 Some(File::from(
735 GLOBAL_SERVICE
736 .createTapInterface(&get_this_pid().to_string())?
737 .as_ref()
738 .try_clone()
739 .context("Failed to get TAP interface from ParcelFileDescriptor")
740 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
741 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900742 } else {
743 None
744 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800745
746 let audio_config = if cfg!(paravirtualized_devices) {
747 config.audioConfig.as_ref().map(AudioConfig::new)
748 } else {
749 None
750 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900751
Elie Kheirallah29d72912024-08-07 20:17:26 +0000752 let usb_config = config
753 .usbConfig
754 .as_ref()
755 .map(UsbConfig::new)
756 .unwrap_or(Ok(UsbConfig { controller: false }))
757 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
758
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000759 // Actually start the VM.
760 let crosvm_config = CrosvmConfig {
761 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000762 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000763 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000764 kernel,
765 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000766 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700767 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000768 params: config.params.to_owned(),
769 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900770 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700771 memory_mib: config
772 .memoryMib
773 .try_into()
774 .ok()
775 .and_then(NonZeroU32::new)
776 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000777 cpus,
778 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900779 console_out_fd,
780 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000781 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900782 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000783 indirect_files,
784 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900785 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000786 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900787 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000788 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000789 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900790 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900791 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000792 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900793 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800794 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000795 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700796 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800797 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800798 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000799 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000800 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000801 };
802 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100803 VmInstance::new(
804 crosvm_config,
805 temporary_directory,
806 requester_uid,
807 requester_debug_pid,
808 vm_context,
809 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900810 .with_context(|| format!("Failed to create VM with config {:?}", config))
811 .with_log()
812 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000813 );
814 state.add_vm(Arc::downgrade(&instance));
815 Ok(VirtualMachine::create(instance))
816 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900817}
818
Alan Stokesfda70842023-12-20 17:50:14 +0000819/// Returns whether a VM config represents a "custom" virtual machine, which requires the
820/// USE_CUSTOM_VIRTUAL_MACHINE.
821fn is_custom_config(config: &VirtualMachineConfig) -> bool {
822 match config {
823 // Any raw (non-Microdroid) VM is considered custom.
824 VirtualMachineConfig::RawConfig(_) => true,
825 VirtualMachineConfig::AppConfig(config) => {
826 // Some features are reserved for platform apps only, even when using
827 // VirtualMachineAppConfig. Almost all of these features are grouped in the
828 // CustomConfig struct:
829 // - controlling CPUs;
830 // - gdbPort is set, meaning that crosvm will start a gdb server;
831 // - using anything other than the default kernel;
832 // - specifying devices to be assigned.
833 if config.customConfig.is_some() {
834 true
835 } else {
836 // Additional custom features not included in CustomConfig:
837 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000838 // - specifying extra APKs;
839 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900840 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000841 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900842 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
843 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000844 }
845 }
846 }
847}
848
Jiyong Park690c1ca2024-11-28 18:06:50 +0900849/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
850/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
851/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
852/// "microdroid" we run VirtualMachineService
853fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
854 match config {
855 VirtualMachineConfig::AppConfig(_) => true,
856 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
857 }
858}
859
Seungjae Yoo14e60182024-02-21 13:28:31 +0900860fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
861 let VirtualMachineConfig::AppConfig(config) = config else {
862 return Ok(None);
863 };
864 let Some(custom_config) = &config.customConfig else {
865 return Ok(None);
866 };
867 let Some(file) = custom_config.vendorImage.as_ref() else {
868 return Ok(None);
869 };
870
871 let file = clone_file(file)?;
872 let size =
873 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
874 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
875 .context("Failed to get vbmeta from microdroid-vendor.img")?;
876
877 for descriptor in vbmeta.descriptors()?.iter() {
878 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
879 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
880 return Ok(Some(root_digest.as_bytes().to_vec()));
881 }
882 }
883 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
884}
885
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000886fn maybe_create_device_tree_overlay(
887 config: &VirtualMachineConfig,
888 temporary_directory: &Path,
889) -> binder::Result<Option<File>> {
890 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
891 // (e.g. instance-id)
892 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
893 let host_ref_dt = if host_ref_dt.exists()
894 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
895 {
896 Some(host_ref_dt)
897 } else {
898 warn!("VM reference DT doesn't exist in host DT");
899 None
900 };
901
902 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
903 .context("Failed to extract vendor hashtree digest")
904 .or_service_specific_exception(-1)?;
905
Matt Gilbrideaade4272024-12-05 13:52:42 +0000906 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000907 info!(
908 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
909 match the trusted digest in the pvmfw config, causing the VM to fail to start."
910 );
Matt Gilbrideaade4272024-12-05 13:52:42 +0000911 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000912 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000913 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000914 };
915
916 let instance_id;
Matt Gilbrideaade4272024-12-05 13:52:42 +0000917 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000918 let mut untrusted_props = Vec::with_capacity(2);
919 if cfg!(llpvm_changes) {
920 instance_id = extract_instance_id(config);
921 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
922 let want_updatable = extract_want_updatable(config);
923 if want_updatable && is_secretkeeper_supported() {
924 // Let guest know that it can defer rollback protection to Secretkeeper by setting
925 // an empty property in untrusted node in DT. This enables Updatable VMs.
Matt Gilbrideaade4272024-12-05 13:52:42 +0000926 untrusted_props.push((cstr!("defer-rollback-protection"), &[]));
927 let sk: Strong<dyn ISecretkeeper> =
928 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
929 if sk.getInterfaceVersion()? >= 2 {
930 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
931 key_material = keyMaterial;
932 trusted_props.push((cstr!("secretkeeper_public_key"), key_material.as_slice()));
933 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000934 }
935 }
936
937 let device_tree_overlay = if host_ref_dt.is_some()
938 || !untrusted_props.is_empty()
939 || !trusted_props.is_empty()
940 {
941 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
942 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
943 let fdt =
944 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
945 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
946 .or_service_specific_exception(-1)?;
947 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
948 Some(File::open(dt_output).or_service_specific_exception(-1)?)
949 } else {
950 None
951 };
952 Ok(device_tree_overlay)
953}
954
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000955fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900956 let file = OpenOptions::new()
957 .create_new(true)
958 .read(true)
959 .write(true)
960 .open(zero_filler_path)
961 .with_context(|| "Failed to create zero.img")?;
962 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000963 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900964}
965
David Brazdilf50c7a62023-04-19 14:22:42 +0000966fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
967 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
968 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
969 part.flush()
970}
971
972fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
973 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
974 part.flush()
975}
976
977fn round_up(input: u64, granularity: u64) -> u64 {
978 if granularity == 0 {
979 return input;
980 }
981 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
982 let result = input.checked_add(granularity - 1).unwrap_or(input);
983 (result / granularity) * granularity
984}
985
Jeongik Chac181be72024-03-27 00:18:30 +0900986fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
987 Ok(match input_device {
988 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
989 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
990 height: u32::try_from(single_touch.height)?,
991 width: u32::try_from(single_touch.width)?,
992 name: if !single_touch.name.is_empty() {
993 Some(single_touch.name.clone())
994 } else {
995 None
996 },
997 },
998 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
999 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1000 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001001 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1002 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1003 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001004 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1005 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1006 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001007 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1008 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1009 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001010 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1011 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1012 height: u32::try_from(trackpad.height)?,
1013 width: u32::try_from(trackpad.width)?,
1014 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1015 },
Jeongik Cha10494912024-07-16 11:19:50 +09001016 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1017 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1018 height: u32::try_from(multi_touch.height)?,
1019 width: u32::try_from(multi_touch.width)?,
1020 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1021 },
Jeongik Chac181be72024-03-27 00:18:30 +09001022 })
1023}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001024
1025fn assemble_shared_paths(
1026 shared_paths: &[SharedPath],
1027 temporary_directory: &Path,
1028) -> Result<Vec<SharedPathConfig>, Status> {
1029 if shared_paths.is_empty() {
1030 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1031 }
1032
1033 shared_paths
1034 .iter()
1035 .map(|path| {
1036 Ok(SharedPathConfig {
1037 path: path.sharedPath.clone(),
1038 host_uid: path.hostUid,
1039 host_gid: path.hostGid,
1040 guest_uid: path.guestUid,
1041 guest_gid: path.guestGid,
1042 mask: path.mask,
1043 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001044 socket_path: temporary_directory
1045 .join(&path.socketPath)
1046 .to_string_lossy()
1047 .to_string(),
1048 socket_fd: maybe_clone_file(&path.socketFd)?,
1049 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001050 })
1051 })
1052 .collect()
1053}
1054
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001055/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1056///
1057/// This may involve assembling a composite disk from a set of partition images.
1058fn assemble_disk_image(
1059 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001060 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001061 temporary_directory: &Path,
1062 next_temporary_image_id: &mut u64,
1063 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001064) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001065 let image = if !disk.partitions.is_empty() {
1066 if disk.image.is_some() {
1067 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001068 return Err(anyhow!("DiskImage contains both image and partitions"))
1069 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001070 }
1071
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001072 let composite_image_filenames =
1073 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1074 let (image, partition_files) = make_composite_image(
1075 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001076 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001077 &composite_image_filenames.composite,
1078 &composite_image_filenames.header,
1079 &composite_image_filenames.footer,
1080 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001081 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1082 .with_log()
1083 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001084
1085 // Pass the file descriptors for the various partition files to crosvm when it
1086 // is run.
1087 indirect_files.extend(partition_files);
1088
1089 image
1090 } else if let Some(image) = &disk.image {
1091 clone_file(image)?
1092 } else {
1093 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001094 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1095 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001096 };
1097
1098 Ok(DiskFile { image, writable: disk.writable })
1099}
1100
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001101fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1102 if let Some(ref mut params) = vm_config.params {
1103 params.push(' ');
1104 params.push_str(param)
1105 } else {
1106 vm_config.params = Some(param.to_owned())
1107 }
1108}
1109
Inseob Kim46257382024-01-03 15:41:22 +09001110fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1111 if config.extension()?.to_str()? != "json" {
1112 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001113 }
Inseob Kim46257382024-01-03 15:41:22 +09001114
1115 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1116}
1117
1118fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1119 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1120 let os_names =
1121 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1122
1123 Ok(os_names)
1124}
1125
1126fn get_supported_os_names() -> Result<HashSet<String>> {
1127 if !cfg!(vendor_modules) {
1128 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1129 }
1130
1131 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1132}
1133
1134fn is_valid_os(os_name: &str) -> bool {
1135 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001136}
1137
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001138fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1139 if !cfg!(vendor_modules) {
1140 return false;
1141 }
1142 match config {
1143 VirtualMachineConfig::RawConfig(_) => false,
1144 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1145 }
1146}
1147
Jooyung Han21e9b922021-06-26 04:14:16 +09001148fn load_app_config(
1149 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001150 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001151 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001152) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001153 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1154 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001155 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001156
Shikha Panwar22e70452022-10-10 18:32:55 +00001157 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1158 Some(clone_file(file)?)
1159 } else {
1160 None
1161 };
1162
Alan Stokesfda70842023-12-20 17:50:14 +00001163 let vm_payload_config;
1164 let extra_apk_files: Vec<_>;
1165 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001166 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001167 vm_payload_config =
1168 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1169 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1170 extra_apk_files = vm_payload_config
1171 .extra_apks
1172 .iter()
1173 .enumerate()
1174 .map(|(i, apk)| {
1175 File::open(PathBuf::from(&apk.path))
1176 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1177 })
1178 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001179 }
Alan Stokesfda70842023-12-20 17:50:14 +00001180 Payload::PayloadConfig(payload_config) => {
1181 vm_payload_config = create_vm_payload_config(payload_config)?;
1182 extra_apk_files =
1183 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1184 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001185 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001186
Inseob Kim89b24592024-02-23 18:59:43 +09001187 let payload_config_os = vm_payload_config.os.name.as_str();
1188 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1189 bail!("'os' in payload config is deprecated");
1190 }
1191
Inseob Kim172f9eb2023-11-06 17:02:08 +09001192 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001193 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001194 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001195 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001196 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001197
1198 // It is safe to construct a filename based on the os_name because we've already checked that it
1199 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001200 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1201 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001202 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001203
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001204 if let Some(custom_config) = &config.customConfig {
1205 if let Some(file) = custom_config.customKernelImage.as_ref() {
1206 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1207 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001208 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001209
1210 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001211 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001212 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001213 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001214
Chris Wailes6177c662024-05-09 14:37:44 -07001215 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001216 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001217
1218 for param in custom_config.extraKernelCmdlineParams.iter() {
1219 append_kernel_param(param, &mut vm_config);
1220 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001221
1222 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001223 }
1224
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001225 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1226 // so we need to provide it in the kernel cmdline.
1227 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1228 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1229 append_kernel_param("page_shift=14", &mut vm_config);
1230 }
1231
Andrew Walbrancc045902021-07-27 16:06:17 +00001232 if config.memoryMib > 0 {
1233 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001234 }
1235
Chris Wailes6177c662024-05-09 14:37:44 -07001236 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001237 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001238 vm_config.cpuTopology = config.cpuTopology;
Frederick Mayle681254c2024-12-11 19:20:06 -08001239 if config.cpuTopology == CpuTopology::CUSTOM {
1240 bail!("AppConfig doesn't support CpuTopology::CUSTOM");
1241 }
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001242 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001243 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001244
Shikha Panwar22e70452022-10-10 18:32:55 +00001245 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001246 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001247
1248 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1249 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001250 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001251 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001252 temporary_directory,
1253 apk_file,
1254 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001255 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001256 &vm_payload_config,
1257 &mut vm_config,
1258 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001259
Andrew Walbrancc0db522021-07-12 17:03:42 +00001260 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001261}
1262
Inseob Kimff48a7c2024-02-26 22:07:21 +09001263fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1264 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1265 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1266
1267 // microdroid vendor image is OK
1268 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1269 {
1270 return Ok(());
1271 }
1272
1273 if link.starts_with("/vendor") || link.starts_with("/odm") {
1274 bail!("vendor or odm file {} can't be used for VM", link.display());
1275 }
1276
1277 Ok(())
1278}
1279
1280fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1281 config
1282 .disks
1283 .iter()
1284 .flat_map(|disk| disk.partitions.iter())
1285 .filter_map(|partition| partition.image.as_ref())
1286 .try_for_each(check_partition_for_file)?;
1287
1288 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1289 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1290 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1291
1292 Ok(())
1293}
1294
Alan Stokes0d1ef782022-09-27 13:46:35 +01001295fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1296 let mut apk_zip = ZipArchive::new(apk_file)?;
1297 let config_file = apk_zip.by_name(config_path)?;
1298 Ok(serde_json::from_reader(config_file)?)
1299}
1300
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001301fn create_vm_payload_config(
1302 payload_config: &VirtualMachinePayloadConfig,
1303) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001304 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1305 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1306 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001307
1308 let payload_binary_name = &payload_config.payloadBinaryName;
1309 if payload_binary_name.contains('/') {
1310 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1311 }
1312
1313 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001314
1315 // The VM only cares about how many there are, these names are actually ignored.
1316 let extra_apk_count = payload_config.extraApks.len();
1317 let extra_apks =
1318 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1319
Inseob Kim89b24592024-02-23 18:59:43 +09001320 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001321}
1322
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001323/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001324fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001325 temporary_directory: &Path,
1326 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001327) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001328 let id = *next_temporary_image_id;
1329 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001330 CompositeImageFilenames {
1331 composite: temporary_directory.join(format!("composite-{}.img", id)),
1332 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1333 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1334 }
1335}
1336
1337/// Filenames for a composite disk image, including header and footer partitions.
1338#[derive(Clone, Debug, Eq, PartialEq)]
1339struct CompositeImageFilenames {
1340 /// The composite disk image itself.
1341 composite: PathBuf,
1342 /// The header partition image.
1343 header: PathBuf,
1344 /// The footer partition image.
1345 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001346}
1347
Jiyong Park753553b2021-07-12 21:21:09 +09001348/// Checks whether the caller has a specific permission
1349fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001350 if cfg!(early) {
1351 // Skip permission check for early VMs, in favor of SELinux
1352 return Ok(());
1353 }
David Brazdil1f530702022-10-03 12:18:10 +01001354 let calling_pid = get_calling_pid();
1355 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001356 // Root can do anything
1357 if calling_uid == 0 {
1358 return Ok(());
1359 }
1360 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001361 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001362 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001363 Ok(())
1364 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001365 Err(anyhow!("does not have the {} permission", perm))
1366 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001367 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001368}
1369
Jiyong Park753553b2021-07-12 21:21:09 +09001370/// Check whether the caller of the current Binder method is allowed to manage VMs
1371fn check_manage_access() -> binder::Result<()> {
1372 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1373}
1374
Inseob Kim1119d702022-05-02 18:01:58 +09001375/// Check whether the caller of the current Binder method is allowed to create custom VMs
1376fn check_use_custom_virtual_machine() -> binder::Result<()> {
1377 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1378}
1379
Alan Stokes185fe112023-01-10 16:20:55 +00001380/// Return whether a partition is exempt from selinux label checks, because we know that it does
1381/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001382fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001383 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001384 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001385 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001386 || label == "microdroid-apk-idsig"
1387 || label == "payload-metadata"
1388 || label.starts_with("extra-idsig-")
1389}
1390
Alice Wangc206b9b2023-08-28 14:13:51 +00001391/// Returns whether a partition with the given label is safe for a raw config VM.
1392fn is_safe_raw_partition(label: &str) -> bool {
1393 label == "vm-instance"
1394}
1395
Alan Stokes185fe112023-01-10 16:20:55 +00001396/// Check that a file SELinux label is acceptable.
1397///
1398/// 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 +09001399/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001400///
1401/// Note that sepolicy must also grant read access for these types to both virtualization
1402/// service and crosvm.
1403///
1404/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1405/// user devices (W^X).
1406fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1407 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001408 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001409 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001410 | "staging_data_file" // updated/staged APEX images
1411 | "system_file" // immutable dm-verity protected partition
1412 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001413 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001414 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001415 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001416 }
1417}
1418
Alan Stokes185fe112023-01-10 16:20:55 +00001419fn check_label_for_partition(partition: &Partition) -> Result<()> {
1420 let file = partition.image.as_ref().unwrap().as_ref();
1421 check_label_is_allowed(&getfilecon(file)?)
1422 .with_context(|| format!("Partition {} invalid", &partition.label))
1423}
1424
1425fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1426 if let Some(f) = kernel {
1427 check_label_for_file(f, "kernel")?;
1428 }
1429 if let Some(f) = initrd {
1430 check_label_for_file(f, "initrd")?;
1431 }
1432 Ok(())
1433}
1434fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1435 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1436}
1437
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001438/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1439#[derive(Debug)]
1440struct VirtualMachine {
1441 instance: Arc<VmInstance>,
1442}
1443
1444impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001445 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001446 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001447 }
1448}
1449
1450impl Interface for VirtualMachine {}
1451
Devin Moore407df8f2024-08-27 19:39:16 +00001452impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001453 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001454 // Don't check permission. The owner of the VM might have passed this binder object to
1455 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001456 Ok(self.instance.cid as i32)
1457 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001458
Andrew Walbran6b650662021-09-07 13:13:23 +00001459 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001460 // Don't check permission. The owner of the VM might have passed this binder object to
1461 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001462 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001463 }
1464
1465 fn registerCallback(
1466 &self,
1467 callback: &Strong<dyn IVirtualMachineCallback>,
1468 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001469 // Don't check permission. The owner of the VM might have passed this binder object to
1470 // others.
1471 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001472 // TODO: Should this give an error if the VM is already dead?
1473 self.instance.callbacks.add(callback.clone());
1474 Ok(())
1475 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001476
Andrew Walbranf8d94112021-09-07 11:45:36 +00001477 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001478 self.instance
1479 .start()
1480 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1481 .with_log()
1482 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001483 }
1484
Inseob Kima446f802022-07-11 19:46:37 +09001485 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001486 self.instance
1487 .kill()
1488 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1489 .with_log()
1490 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001491 }
1492
Keir Fraser48221ba2024-07-12 14:05:02 +00001493 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1494 let balloon = self
1495 .instance
1496 .get_memory_balloon()
1497 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1498 .with_log()
1499 .or_service_specific_exception(-1)?;
1500 Ok(balloon.try_into().unwrap())
1501 }
1502
1503 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001504 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001505 .set_memory_balloon(num_bytes.try_into().unwrap())
1506 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001507 .with_log()
1508 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001509 }
1510
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001511 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001512 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001513 return Err(Status::new_service_specific_error_str(
1514 IVirtualMachine::ERROR_UNEXPECTED,
1515 Some("Virtual Machine is not running"),
1516 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001517 }
Alan Stokes10c47672022-12-13 17:17:08 +00001518 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001519 if port < VSOCK_PRIV_PORT_MAX {
1520 return Err(Status::new_service_specific_error_str(
1521 IVirtualMachine::ERROR_UNEXPECTED,
1522 Some("Can't connect to privileged port {port}"),
1523 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001524 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001525 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1526 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001527 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001528 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001529 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001530
Devin Moore407df8f2024-08-27 19:39:16 +00001531 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1532 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1533 return Err(Status::new_service_specific_error_str(
1534 IVirtualMachine::ERROR_UNEXPECTED,
1535 Some("Virtual Machine is not running"),
1536 ));
1537 }
1538 let port = port as u32;
1539 if port < VSOCK_PRIV_PORT_MAX {
1540 return Err(Status::new_service_specific_error_str(
1541 IVirtualMachine::ERROR_UNEXPECTED,
1542 Some("Can't connect to privileged port {port}"),
1543 ));
1544 }
1545 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001546 let addr = sockaddr_vm {
1547 svm_family: AF_VSOCK as sa_family_t,
1548 svm_reserved1: 0,
1549 svm_port: port,
1550 svm_cid: cid,
1551 svm_zero: [0u8; 4],
1552 };
1553 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001554 let accessor = Accessor::new(name, get_connection_info);
1555 accessor
1556 .as_binder()
1557 .context("The newly created Accessor should always have a binder")
1558 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1559 }
1560
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001561 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1562 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1563 }
Jiyong Park23b67392024-07-04 13:51:42 +09001564
1565 fn suspend(&self) -> binder::Result<()> {
1566 self.instance
1567 .suspend()
1568 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1569 .with_log()
1570 .or_service_specific_exception(-1)
1571 }
1572
1573 fn resume(&self) -> binder::Result<()> {
1574 self.instance
1575 .resume()
1576 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1577 .with_log()
1578 .or_service_specific_exception(-1)
1579 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001580}
1581
1582impl Drop for VirtualMachine {
1583 fn drop(&mut self) {
1584 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001585 if let Err(e) = self.instance.kill() {
1586 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1587 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001588 }
1589}
1590
1591/// A set of Binders to be called back in response to various events on the VM, such as when it
1592/// dies.
1593#[derive(Debug, Default)]
1594pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1595
1596impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001597 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001598 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001599 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001600 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001601 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001602 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001603 }
1604 }
1605 }
1606
Inseob Kim14cb8692021-08-31 21:50:39 +09001607 /// Call all registered callbacks to notify that the payload is ready to serve.
1608 pub fn notify_payload_ready(&self, cid: Cid) {
1609 let callbacks = &*self.0.lock().unwrap();
1610 for callback in callbacks {
1611 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001612 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001613 }
1614 }
1615 }
1616
Inseob Kim2444af92021-08-31 01:22:50 +09001617 /// Call all registered callbacks to notify that the payload has finished.
1618 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1619 let callbacks = &*self.0.lock().unwrap();
1620 for callback in callbacks {
1621 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001622 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001623 }
1624 }
1625 }
1626
Jooyung Handd0a1732021-11-23 15:26:20 +09001627 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001628 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001629 let callbacks = &*self.0.lock().unwrap();
1630 for callback in callbacks {
1631 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001632 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001633 }
1634 }
1635 }
1636
Andrew Walbrandae07162021-03-12 17:05:20 +00001637 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001638 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001639 let callbacks = &*self.0.lock().unwrap();
1640 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001641 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001642 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001643 }
1644 }
1645 }
1646
1647 /// Add a new callback to the set.
1648 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1649 self.0.lock().unwrap().push(callback);
1650 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001651}
1652
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001653/// The mutable state of the VirtualizationService. There should only be one instance of this
1654/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001655#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001656struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001657 /// The VMs which have been started. When VMs are started a weak reference is added to this
1658 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1659 /// the Binder client are dropped the weak reference here will become invalid, and will be
1660 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001661 vms: Vec<Weak<VmInstance>>,
1662}
1663
1664impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001665 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001666 fn vms(&self) -> Vec<Arc<VmInstance>> {
1667 // Attempt to upgrade the weak pointers to strong pointers.
1668 self.vms.iter().filter_map(Weak::upgrade).collect()
1669 }
1670
1671 /// Add a new VM to the list.
1672 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1673 // Garbage collect any entries from the stored list which no longer exist.
1674 self.vms.retain(|vm| vm.strong_count() > 0);
1675
1676 // Actually add the new VM.
1677 self.vms.push(vm);
1678 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001679
Jiyong Park8611a6c2021-07-09 18:17:44 +09001680 /// Get a VM that corresponds to the given cid
1681 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1682 self.vms().into_iter().find(|vm| vm.cid == cid)
1683 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001684}
1685
Andrew Walbran6b650662021-09-07 13:13:23 +00001686/// Gets the `VirtualMachineState` of the given `VmInstance`.
1687fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001688 match &*instance.vm_state.lock().unwrap() {
1689 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1690 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001691 PayloadState::Starting => VirtualMachineState::STARTING,
1692 PayloadState::Started => VirtualMachineState::STARTED,
1693 PayloadState::Ready => VirtualMachineState::READY,
1694 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001695 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001696 },
1697 VmState::Dead => VirtualMachineState::DEAD,
1698 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001699 }
1700}
1701
David Brazdilf50c7a62023-04-19 14:22:42 +00001702/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001703pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1704 file.as_ref()
1705 .try_clone()
1706 .context("Failed to clone File from ParcelFileDescriptor")
1707 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001708 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001709}
1710
Andrew Walbrand3a84182021-09-07 14:48:52 +00001711/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001712fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001713 file.as_ref().map(clone_file).transpose()
1714}
1715
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001716/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001717fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1718 // SAFETY: ownership is transferred from stream to f
1719 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1720 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001721}
1722
Jiyong Parkdcf17412022-02-08 15:07:23 +09001723/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001724fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1725 VersionReq::parse(s)
1726 .with_context(|| format!("Invalid platform version requirement {}", s))
1727 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001728}
1729
Jiyong Parked180932023-02-24 19:55:41 +09001730/// Create the empty ramdump file
1731fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1732 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1733 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1734 // owner) for readout.
1735 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001736 let ramdump = File::create(ramdump_path)
1737 .context("Failed to prepare ramdump file")
1738 .with_log()
1739 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001740 Ok(ramdump)
1741}
1742
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001743/// Create the empty device tree dump file
1744fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1745 let path = temporary_directory.join("device_tree.dtb");
1746 let file = File::create(path)
1747 .context("Failed to prepare device tree dump file")
1748 .with_log()
1749 .or_service_specific_exception(-1)?;
1750 Ok(file)
1751}
1752
Nikita Ioffe5776f082023-02-10 21:38:26 +00001753fn is_protected(config: &VirtualMachineConfig) -> bool {
1754 match config {
1755 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1756 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1757 }
1758}
1759
1760fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1761 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001762 return Err(anyhow!("Can't use gdb with protected VMs"))
1763 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001764 }
1765
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001766 if get_debug_level(config) == Some(DebugLevel::NONE) {
1767 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1768 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001769 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001770
1771 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001772}
1773
Shikha Panwar61a74b52024-02-16 13:17:01 +00001774fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1775 match config {
1776 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1777 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1778 }
1779}
1780
Alan Stokesc96b35e2024-05-03 13:21:20 +01001781fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1782 match config {
1783 VirtualMachineConfig::RawConfig(_) => true,
1784 VirtualMachineConfig::AppConfig(config) => {
1785 let Some(custom) = &config.customConfig else { return true };
1786 custom.wantUpdatable
1787 }
1788 }
1789}
1790
Nikita Ioffe5776f082023-02-10 21:38:26 +00001791fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1792 match config {
1793 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001794 VirtualMachineConfig::AppConfig(config) => {
1795 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1796 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001797 }
1798}
1799
Nikita Ioffe631717e2023-09-05 13:38:07 +01001800fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1801 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1802 if let Some(custom_config) = &config.customConfig {
1803 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1804 return Err(anyhow!("vendor modules feature is disabled"))
1805 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1806 }
1807 }
1808 Ok(())
1809}
1810
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001811fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1812 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1813 if let Some(custom_config) = &config.customConfig {
1814 if !custom_config.devices.is_empty() {
1815 return Err(anyhow!("device assignment feature is disabled"))
1816 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1817 }
1818 }
1819 Ok(())
1820}
1821
Alan Stokesfda70842023-12-20 17:50:14 +00001822fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1823 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1824 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1825 if !payload_config.extraApks.is_empty() {
1826 return Err(anyhow!("multi-tenant feature is disabled"))
1827 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1828 }
1829 Ok(())
1830}
1831
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001832fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1833 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1834 if let Some(custom_config) = &config.customConfig {
1835 if !custom_config.extraKernelCmdlineParams.is_empty() {
1836 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1837 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1838 }
1839 }
1840 Ok(())
1841}
1842
Nikita Ioffe99548382024-10-21 15:54:46 +00001843fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1844 match config {
1845 VirtualMachineConfig::RawConfig(config) => {
1846 if !config.teeServices.is_empty() {
1847 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1848 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1849 }
1850 }
1851 VirtualMachineConfig::AppConfig(config) => {
1852 if let Some(custom_config) = &config.customConfig {
1853 if !custom_config.teeServices.is_empty() {
1854 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1855 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1856 }
1857 }
1858 }
1859 };
1860 Ok(())
1861}
1862
Nikita Ioffef934e812024-07-05 15:44:41 +00001863fn check_protected_vm_is_supported() -> binder::Result<()> {
1864 let is_pvm_supported =
1865 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1866 if is_pvm_supported {
1867 Ok(())
1868 } else {
1869 Err(anyhow!("pVM is not supported"))
1870 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1871 }
1872}
1873
Nikita Ioffe631717e2023-09-05 13:38:07 +01001874fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1875 if !cfg!(vendor_modules) {
1876 check_no_vendor_modules(config)?;
1877 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001878 if !cfg!(device_assignment) {
1879 check_no_devices(config)?;
1880 }
Alan Stokesfda70842023-12-20 17:50:14 +00001881 if !cfg!(multi_tenant) {
1882 check_no_extra_apks(config)?;
1883 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001884 if !cfg!(debuggable_vms_improvements) {
1885 check_no_extra_kernel_cmdline_params(config)?;
1886 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001887 if !cfg!(tee_services_allowlist) {
1888 check_no_tee_services(config)?;
1889 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001890 Ok(())
1891}
1892
Inseob Kimecde8c02024-09-03 13:11:08 +09001893fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1894 check_no_vendor_modules(config)?;
1895 check_no_devices(config)?;
1896
1897 Ok(())
1898}
1899
Inseob Kim0168b462022-12-27 14:54:35 +09001900fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001901 fd: Option<&ParcelFileDescriptor>,
1902 tag: String,
1903) -> Result<Option<File>, Status> {
1904 if let Some(fd) = fd {
1905 return Ok(Some(clone_file(fd)?));
1906 }
1907
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001908 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001909 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001910
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001911 let mut reader = BufReader::new(File::from(read_fd));
1912 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001913
1914 std::thread::spawn(move || loop {
1915 let mut buf = vec![];
1916 match reader.read_until(b'\n', &mut buf) {
1917 Ok(0) => {
1918 // EOF
1919 return;
1920 }
1921 Ok(size) => {
1922 if buf[size - 1] == b'\n' {
1923 buf.pop();
1924 }
1925 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1926 }
1927 Err(e) => {
1928 error!("Could not read console pipe: {:?}", e);
1929 return;
1930 }
1931 };
1932 });
1933
1934 Ok(Some(write_fd))
1935}
1936
Jooyung Han35edb8f2021-07-01 16:17:16 +09001937/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1938/// it doesn't require that T implements Clone.
1939enum BorrowedOrOwned<'a, T> {
1940 Borrowed(&'a T),
1941 Owned(T),
1942}
1943
1944impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1945 fn as_ref(&self) -> &T {
1946 match self {
1947 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001948 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001949 }
1950 }
1951}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001952
1953/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1954#[derive(Debug, Default)]
1955struct VirtualMachineService {
1956 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001957 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001958}
1959
1960impl Interface for VirtualMachineService {}
1961
1962impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001963 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1964 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001965 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001966 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001967 vm.update_payload_state(PayloadState::Started)
1968 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001969 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001970
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001971 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1972 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001973 Ok(())
1974 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001975 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001976 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001977 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001978 }
Inseob Kim2444af92021-08-31 01:22:50 +09001979
Inseob Kimc7d28c72021-10-25 14:28:10 +00001980 fn notifyPayloadReady(&self) -> binder::Result<()> {
1981 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001982 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001983 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001984 vm.update_payload_state(PayloadState::Ready)
1985 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001986 vm.callbacks.notify_payload_ready(cid);
1987 Ok(())
1988 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001989 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001990 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001991 }
1992 }
1993
Inseob Kimc7d28c72021-10-25 14:28:10 +00001994 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1995 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001996 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001997 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001998 vm.update_payload_state(PayloadState::Finished)
1999 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002000 vm.callbacks.notify_payload_finished(cid, exit_code);
2001 Ok(())
2002 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002003 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002004 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002005 }
2006 }
2007
Alan Stokes2bead0d2022-09-05 16:58:34 +01002008 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002009 let cid = self.cid;
2010 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002011 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002012 vm.update_payload_state(PayloadState::Finished)
2013 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002014 vm.callbacks.notify_error(cid, error_code, message);
2015 Ok(())
2016 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002017 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002018 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002019 }
2020 }
Alice Wangc2fec932023-02-23 16:24:02 +00002021
Shikha Panware45e9422024-02-28 21:18:10 +00002022 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2023 if !is_secretkeeper_supported() {
2024 return Err(StatusCode::NAME_NOT_FOUND)?;
2025 }
2026 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2027 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002028 }
2029
Alice Wange64dd182024-01-17 15:57:55 +00002030 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2031 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002032 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002033}
2034
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002035fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002036 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2037 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002038}
2039
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002040impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002041 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002042 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002043 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002044 BinderFeatures::default(),
2045 )
2046 }
2047}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002048
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002049struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2050
2051impl Interface for SecretkeeperProxy {}
2052
2053impl ISecretkeeper for SecretkeeperProxy {
2054 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2055 // Pass the request to the channel, and read the response.
2056 self.0.processSecretManagementRequest(req)
2057 }
2058
2059 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2060 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2061 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2062 }
2063
2064 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2065 self.0.deleteIds(ids)
2066 }
2067
2068 fn deleteAll(&self) -> binder::Result<()> {
2069 self.0.deleteAll()
2070 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002071
2072 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2073 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2074 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2075 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2076 // use this API from the proxy.
2077 Err(ExceptionCode::SECURITY.into())
2078 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002079}
2080
2081struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2082
2083impl Interface for AuthGraphKeyExchangeProxy {}
2084
2085impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2086 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2087 self.0.create()
2088 }
2089
2090 fn init(
2091 &self,
2092 peer_pub_key: &PubKey,
2093 peer_id: &Identity,
2094 peer_nonce: &[u8],
2095 peer_version: i32,
2096 ) -> binder::Result<KeInitResult> {
2097 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2098 }
2099
2100 fn finish(
2101 &self,
2102 peer_pub_key: &PubKey,
2103 peer_id: &Identity,
2104 peer_signature: &SessionIdSignature,
2105 peer_nonce: &[u8],
2106 peer_version: i32,
2107 own_key: &Key,
2108 ) -> binder::Result<SessionInfo> {
2109 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2110 }
2111
2112 fn authenticationComplete(
2113 &self,
2114 peer_signature: &SessionIdSignature,
2115 shared_keys: &[AuthgraphArc; 2],
2116 ) -> binder::Result<[AuthgraphArc; 2]> {
2117 self.0.authenticationComplete(peer_signature, shared_keys)
2118 }
2119}
2120
Inseob Kimecde8c02024-09-03 13:11:08 +09002121// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002122#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002123struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002124 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002125 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002126 path: String,
2127}
2128
2129#[derive(Debug, Default, Deserialize)]
2130struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002131 early_vm: Vec<EarlyVm>,
2132}
2133
Inseob Kim7e1877b2024-11-07 17:28:56 +09002134static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2135 LazyLock::new(|| Mutex::new(HashMap::new()));
2136
Inseob Kimecde8c02024-09-03 13:11:08 +09002137fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2138 match partition {
2139 "system" => Ok(100..200),
2140 "system_ext" | "product" => Ok(200..300),
2141 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2142 }
2143}
2144
Inseob Kim7e1877b2024-11-07 17:28:56 +09002145fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002146 if !xml_path.exists() {
2147 bail!("{} doesn't exist", xml_path.display());
2148 }
2149
2150 let xml =
2151 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2152 let xml = String::from_utf8(xml)
2153 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2154 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2155 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2156
Inseob Kim7e1877b2024-11-07 17:28:56 +09002157 Ok(early_vms.early_vm)
2158}
Inseob Kimecde8c02024-09-03 13:11:08 +09002159
Inseob Kim7e1877b2024-11-07 17:28:56 +09002160fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2161 for early_vm in early_vms {
2162 let cid = early_vm
2163 .cid
2164 .try_into()
2165 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2166
2167 ensure!(
2168 cid_range.contains(&cid),
2169 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2170 early_vm.name
2171 );
2172 }
2173 Ok(())
2174}
2175
2176fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2177 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2178
2179 if let Some(result) = cache.get(partition) {
2180 return Ok(result.clone());
2181 }
2182
2183 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2184 let mut early_vms = Vec::new();
2185 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2186 match entry {
2187 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2188 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2189 }
2190 }
2191
2192 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2193 .with_context(|| format!("CID validation for {partition} failed"))?;
2194
2195 cache.insert(partition.to_owned(), early_vms.clone());
2196
2197 Ok(early_vms)
2198}
2199
2200fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2201 let mut found_vm: Option<&EarlyVm> = None;
2202
2203 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002204 if early_vm.name != name {
2205 continue;
2206 }
2207
Inseob Kimecde8c02024-09-03 13:11:08 +09002208 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002209 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002210 }
2211
2212 found_vm = Some(early_vm);
2213 }
2214
Inseob Kim7e1877b2024-11-07 17:28:56 +09002215 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002216}
2217
2218fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002219 let early_vms = get_early_vms_in_partition(partition)
2220 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2221
2222 Ok(find_early_vm(&early_vms, name)
2223 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2224 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002225}
2226
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002227#[cfg(test)]
2228mod tests {
2229 use super::*;
2230
2231 #[test]
2232 fn test_is_allowed_label_for_partition() -> Result<()> {
2233 let expected_results = vec![
2234 ("u:object_r:system_file:s0", true),
2235 ("u:object_r:apk_data_file:s0", true),
2236 ("u:object_r:app_data_file:s0", false),
2237 ("u:object_r:app_data_file:s0:c512,c768", false),
2238 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2239 ("invalid", false),
2240 ("user:role:apk_data_file:severity:categories", true),
2241 ("user:role:apk_data_file:severity:categories:extraneous", false),
2242 ];
2243
2244 for (label, expected_valid) in expected_results {
2245 let context = SeContext::new(label)?;
2246 let result = check_label_is_allowed(&context);
2247 if expected_valid {
2248 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2249 } else if result.is_ok() {
2250 bail!("Expected label {} to be disallowed", label);
2251 }
2252 }
2253 Ok(())
2254 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002255
2256 #[test]
2257 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2258 let apk = tempfile::tempfile().unwrap();
2259 let idsig = tempfile::tempfile().unwrap();
2260
2261 let ret = create_or_update_idsig_file(
2262 &ParcelFileDescriptor::new(apk),
2263 &ParcelFileDescriptor::new(idsig),
2264 );
2265 assert!(ret.is_err(), "should fail");
2266 Ok(())
2267 }
2268
2269 #[test]
2270 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2271 let tmp_dir = tempfile::TempDir::new().unwrap();
2272 let apk = File::open(tmp_dir.path()).unwrap();
2273 let idsig = tempfile::tempfile().unwrap();
2274
2275 let ret = create_or_update_idsig_file(
2276 &ParcelFileDescriptor::new(apk),
2277 &ParcelFileDescriptor::new(idsig),
2278 );
2279 assert!(ret.is_err(), "should fail");
2280 Ok(())
2281 }
2282
2283 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2284 /// on ext4 filesystem is passed.
2285 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2286 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2287 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2288 #[test]
2289 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2290 // APEXes are backed by the ext4.
2291 let apk = File::open("/apex/com.android.virt/").unwrap();
2292 let idsig = tempfile::tempfile().unwrap();
2293
2294 let ret = create_or_update_idsig_file(
2295 &ParcelFileDescriptor::new(apk),
2296 &ParcelFileDescriptor::new(idsig),
2297 );
2298 assert!(ret.is_err(), "should fail");
2299 Ok(())
2300 }
Jiyong Park8d192952023-06-26 14:29:51 +09002301
2302 #[test]
2303 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2304 use std::io::Seek;
2305
2306 // Pick any APK
2307 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2308 let mut idsig = tempfile::tempfile().unwrap();
2309
2310 create_or_update_idsig_file(
2311 &ParcelFileDescriptor::new(apk.try_clone()?),
2312 &ParcelFileDescriptor::new(idsig.try_clone()?),
2313 )?;
2314 let modified_orig = idsig.metadata()?.modified()?;
2315 apk.rewind()?;
2316 idsig.rewind()?;
2317
2318 // Call the function again
2319 create_or_update_idsig_file(
2320 &ParcelFileDescriptor::new(apk.try_clone()?),
2321 &ParcelFileDescriptor::new(idsig.try_clone()?),
2322 )?;
2323 let modified_new = idsig.metadata()?.modified()?;
2324 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2325 Ok(())
2326 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002327
2328 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002329 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2330 use std::io::Read;
2331
2332 // Pick any APK
2333 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2334 let idsig_empty = tempfile::tempfile().unwrap();
2335 let mut idsig_invalid = tempfile::tempfile().unwrap();
2336 idsig_invalid.write_all(b"Oops")?;
2337
2338 // Create new idsig
2339 create_or_update_idsig_file(
2340 &ParcelFileDescriptor::new(apk.try_clone()?),
2341 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2342 )?;
2343 apk.rewind()?;
2344
2345 // Update idsig_invalid
2346 create_or_update_idsig_file(
2347 &ParcelFileDescriptor::new(apk.try_clone()?),
2348 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2349 )?;
2350
2351 // Ensure the 2 idsig files have same size!
2352 assert!(
2353 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2354 "idsig files differ in size"
2355 );
2356 // Ensure the 2 idsig files have same content!
2357 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2358 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2359 }
2360 Ok(())
2361 }
2362 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002363 fn test_append_kernel_param_first_param() {
2364 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2365 append_kernel_param("foo=1", &mut vm_config);
2366 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2367 }
2368
2369 #[test]
2370 fn test_append_kernel_param() {
2371 let mut vm_config =
2372 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2373 append_kernel_param("bar=42", &mut vm_config);
2374 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2375 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002376
Inseob Kim46257382024-01-03 15:41:22 +09002377 fn test_extract_os_name_from_config_path(
2378 path: &Path,
2379 expected_result: Option<&str>,
2380 ) -> Result<()> {
2381 let result = extract_os_name_from_config_path(path);
2382 if result.as_deref() != expected_result {
2383 bail!("Expected {:?} but was {:?}", expected_result, &result)
2384 }
2385 Ok(())
2386 }
2387
2388 #[test]
2389 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2390 test_extract_os_name_from_config_path(
2391 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2392 Some("microdroid"),
2393 )
2394 }
2395
2396 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002397 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2398 test_extract_os_name_from_config_path(
2399 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2400 Some("microdroid_16k"),
2401 )
2402 }
2403
2404 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002405 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2406 test_extract_os_name_from_config_path(
2407 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2408 Some("microdroid_gki-android14-6.1"),
2409 )
2410 }
2411
2412 #[test]
2413 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2414 test_extract_os_name_from_config_path(
2415 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2416 None,
2417 )
2418 }
2419
2420 #[test]
2421 fn test_extract_os_name_from_configs() -> Result<()> {
2422 let tmp_dir = tempfile::TempDir::new()?;
2423 let tmp_dir_path = tmp_dir.path().to_owned();
2424
2425 let mut os_names: HashSet<String> = HashSet::new();
2426 os_names.insert("microdroid".to_owned());
2427 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2428 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2429
2430 // config files
2431 for os_name in &os_names {
2432 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2433 }
2434
2435 // fake files not related to configs
2436 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2437 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2438
2439 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2440 Some(s) => s.to_owned(),
2441 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2442 };
2443
2444 let result = extract_os_names_from_configs(&glob_pattern)?;
2445 if result != os_names {
2446 bail!("Expected {:?} but was {:?}", os_names, result);
2447 }
2448 Ok(())
2449 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002450
2451 #[test]
2452 fn test_find_early_vms_from_xml() -> Result<()> {
2453 let tmp_dir = tempfile::TempDir::new()?;
2454 let tmp_dir_path = tmp_dir.path().to_owned();
2455 let xml_path = tmp_dir_path.join("early_vms.xml");
2456
2457 std::fs::write(
2458 &xml_path,
2459 br#"<?xml version="1.0" encoding="utf-8"?>
2460 <early_vms>
2461 <early_vm>
2462 <name>vm_demo_native_early</name>
2463 <cid>123</cid>
2464 <path>/system/bin/vm_demo_native_early</path>
2465 </early_vm>
2466 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002467 <name>vm_demo_native_early_2</name>
2468 <cid>456</cid>
2469 <path>/system/bin/vm_demo_native_early_2</path>
2470 </early_vm>
2471 </early_vms>
2472 "#,
2473 )?;
2474
2475 let cid_range = 100..1000;
2476
2477 let early_vms = get_early_vms_in_path(&xml_path)?;
2478 validate_cid_range(&early_vms, &cid_range)?;
2479
2480 let test_cases = [
2481 (
2482 "vm_demo_native_early",
2483 EarlyVm {
2484 name: "vm_demo_native_early".to_owned(),
2485 cid: 123,
2486 path: "/system/bin/vm_demo_native_early".to_owned(),
2487 },
2488 ),
2489 (
2490 "vm_demo_native_early_2",
2491 EarlyVm {
2492 name: "vm_demo_native_early_2".to_owned(),
2493 cid: 456,
2494 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2495 },
2496 ),
2497 ];
2498
2499 for (name, expected) in test_cases {
2500 let result = find_early_vm(&early_vms, name)?;
2501 assert_eq!(result, &expected);
2502 }
2503
2504 Ok(())
2505 }
2506
2507 #[test]
2508 fn test_invalid_cid_validation() -> Result<()> {
2509 let tmp_dir = tempfile::TempDir::new()?;
2510 let xml_path = tmp_dir.path().join("early_vms.xml");
2511
2512 let cid_range = 100..1000;
2513
2514 for cid in [-1, 999999] {
2515 std::fs::write(
2516 &xml_path,
2517 format!(
2518 r#"<?xml version="1.0" encoding="utf-8"?>
2519 <early_vms>
2520 <early_vm>
2521 <name>vm_demo_invalid_cid</name>
2522 <cid>{cid}</cid>
2523 <path>/system/bin/vm_demo_invalid_cid</path>
2524 </early_vm>
2525 </early_vms>
2526 "#
2527 ),
2528 )?;
2529
2530 let early_vms = get_early_vms_in_path(&xml_path)?;
2531 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2532 }
2533
2534 Ok(())
2535 }
2536
2537 #[test]
2538 fn test_duplicated_early_vms() -> Result<()> {
2539 let tmp_dir = tempfile::TempDir::new()?;
2540 let tmp_dir_path = tmp_dir.path().to_owned();
2541 let xml_path = tmp_dir_path.join("early_vms.xml");
2542
2543 std::fs::write(
2544 &xml_path,
2545 br#"<?xml version="1.0" encoding="utf-8"?>
2546 <early_vms>
2547 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002548 <name>vm_demo_duplicated_name</name>
2549 <cid>456</cid>
2550 <path>/system/bin/vm_demo_duplicated_name_1</path>
2551 </early_vm>
2552 <early_vm>
2553 <name>vm_demo_duplicated_name</name>
2554 <cid>789</cid>
2555 <path>/system/bin/vm_demo_duplicated_name_2</path>
2556 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002557 </early_vms>
2558 "#,
2559 )?;
2560
2561 let cid_range = 100..1000;
2562
Inseob Kim7e1877b2024-11-07 17:28:56 +09002563 let early_vms = get_early_vms_in_path(&xml_path)?;
2564 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002565
Inseob Kim7e1877b2024-11-07 17:28:56 +09002566 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002567
2568 Ok(())
2569 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002570}