blob: c71b5c5090cd2a97072a4cd4a87ef26512b00bc5 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000034 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070036 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090037 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000038 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000039 IVirtualMachineCallback::IVirtualMachineCallback,
40 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090041 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090043 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010046 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090047 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000048 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090049};
Inseob Kimecde8c02024-09-03 13:11:08 +090050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
Shikha Panware45e9422024-02-28 21:18:10 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000057use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000058use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
59 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
60 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
61 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
62 SessionInitiationInfo::SessionInitiationInfo,
63};
Inseob Kim7e1877b2024-11-07 17:28:56 +090064use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090065use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090066use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010067use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000068 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
69 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000070};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000071use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090072use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000073use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000074use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090075use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090076use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000077use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000078use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090079use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090080use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090081use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000082use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000083use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090084use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090085use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000086use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090087use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000088use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090089use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090090use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000091use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000092use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010093use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090094use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010095use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000096use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090097use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000098
David Brazdil41d1a872022-10-05 14:44:19 +010099/// The unique ID of a VM used (together with a port number) for vsock communication.
100pub type Cid = u32;
101
David Brazdil4b4c5102022-12-19 22:56:20 +0000102pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
103
Devin Moore407df8f2024-08-27 19:39:16 +0000104/// Vsock privileged ports are below this number.
105const VSOCK_PRIV_PORT_MAX: u32 = 1024;
106
Jooyung Han95884632021-07-06 22:27:54 +0900107/// The size of zero.img.
108/// Gaps in composite disk images are filled with a shared zero.img.
109const ZERO_FILLER_SIZE: u64 = 4096;
110
David Brazdilf50c7a62023-04-19 14:22:42 +0000111/// Magic string for the instance image
112const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
113
114/// Version of the instance image format
115const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
116
Alan Stokes0d1ef782022-09-27 13:46:35 +0100117const MICRODROID_OS_NAME: &str = "microdroid";
118
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000120 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000121
David Brazdilf50c7a62023-04-19 14:22:42 +0000122const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
123
124/// crosvm requires all partitions to be a multiple of 4KiB.
125const PARTITION_GRANULARITY_BYTES: u64 = 4096;
126
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000127const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
128
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100129pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
130 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900131 if cfg!(early) {
132 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
133 } else {
134 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
135 .expect("Could not connect to VirtualizationServiceInternal")
136 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100137 });
138static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
139 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000140
Inseob Kime3e932d2024-12-16 20:06:57 +0900141static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
142 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
143 match fs::read_link(&calling_exe_link) {
144 Ok(calling_exe_path) => Some(calling_exe_path),
145 Err(e) => {
146 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
147 // discourage vendor apps, regarding such cases as system is safer.
148 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
149 // apps.
150 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
151 None
152 }
153 }
154});
155
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000156fn create_or_update_idsig_file(
157 input_fd: &ParcelFileDescriptor,
158 idsig_fd: &ParcelFileDescriptor,
159) -> Result<()> {
160 let mut input = clone_file(input_fd)?;
161 let metadata = input.metadata().context("failed to get input metadata")?;
162 if !metadata.is_file() {
163 bail!("input is not a regular file");
164 }
Alan Stokes25f69362023-03-06 16:51:54 +0000165 let mut sig =
166 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
167 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000168
169 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900170
171 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
172 // if the idsig file already has the same APK digest.
173 if output.metadata()?.len() > 0 {
174 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
175 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
176 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
177 return Ok(());
178 }
179 }
180 // if we fail to read v4signature from output, that's fine. User can pass a random file.
181 // We will anyway overwrite the file to the v4signature generated from input_fd.
182 }
183
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000184 output
185 .seek(SeekFrom::Start(0))
186 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000187 output.set_len(0).context("failed to set_len on the idsig output")?;
188 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000189 Ok(())
190}
191
Alan Stokes25f69362023-03-06 16:51:54 +0000192fn get_current_sdk() -> Result<u32> {
193 let current_sdk = system_properties::read("ro.build.version.sdk")?;
194 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
195 current_sdk.parse().context("Malformed SDK version")
196}
197
David Brazdil4b4c5102022-12-19 22:56:20 +0000198pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
199 for dir_entry in read_dir(path)? {
200 remove_file(dir_entry?.path())?;
201 }
202 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100203}
204
David Brazdil528e0472022-10-10 15:06:02 +0100205/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000206#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000207pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900208 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000209}
210
Shikha Panward8e35422021-10-11 13:51:27 +0000211impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000212 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000213 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
214 let state = &mut *self.state.lock().unwrap();
215 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000216 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000217 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000218 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
219 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000220 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000222 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000223 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
224 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000225 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000226 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000227 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000228 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000229 .or(Err(StatusCode::UNKNOWN_ERROR))?;
230 }
231 Ok(())
232 }
233}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000234impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000235 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
236 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000237 ///
238 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000239 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000240 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000241 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900242 console_out_fd: Option<&ParcelFileDescriptor>,
243 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000244 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000245 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000246 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000247 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900248 let ret = self.create_vm_internal(
249 config,
250 console_out_fd,
251 console_in_fd,
252 log_fd,
253 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000254 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900255 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000256 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000257 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000258 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000259
Shikha Panwar61a74b52024-02-16 13:17:01 +0000260 /// Allocate a new instance_id to the VM
261 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000262 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000263 GLOBAL_SERVICE.allocateInstanceId()
264 }
265
Andrew Walbrandff3b942021-06-09 15:20:36 +0000266 /// Initialise an empty partition image of the given size to be used as a writable partition.
267 fn initializeWritablePartition(
268 &self,
269 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000270 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900271 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000272 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900273 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900274 let size_bytes = size_bytes
275 .try_into()
276 .with_context(|| format!("Invalid size: {}", size_bytes))
277 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000279 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000280 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000281 image
282 .seek(SeekFrom::Start(0))
283 .context("failed to move cursor to start")
284 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900285 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700286 // Set the file length. In most filesystems, this will not allocate any physical disk
287 // space, it will only change the logical size.
288 image
289 .set_len(size_bytes)
290 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900291 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000292
293 match partition_type {
294 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700295 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
296 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000297 _ => Err(Error::new(
298 ErrorKind::Unsupported,
299 format!("Unsupported partition type {:?}", partition_type),
300 )),
301 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900302 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
303 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000304
305 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000306 }
307
Jiyong Park0a248432021-08-20 23:32:39 +0900308 /// Creates or update the idsig file by digesting the input APK file.
309 fn createOrUpdateIdsigFile(
310 &self,
311 input_fd: &ParcelFileDescriptor,
312 idsig_fd: &ParcelFileDescriptor,
313 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900314 check_manage_access()?;
315
Jiyong Park2227eaa2023-08-04 11:59:18 +0900316 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900317 Ok(())
318 }
319
Andrew Walbran320b5602021-03-04 16:11:12 +0000320 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
321 /// and as such is only permitted from the shell user.
322 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000323 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000324 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000325 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900326
327 /// Get a list of assignable device types.
328 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
329 // Delegate to the global service, including checking the permission.
330 GLOBAL_SERVICE.getAssignableDevices()
331 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100332
Inseob Kim46257382024-01-03 15:41:22 +0900333 /// Get a list of supported OSes.
334 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
335 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
336 }
337
Jaewan Kimabd328b2024-12-10 15:59:33 +0900338 /// Get printable debug policy for testing and debugging
339 fn getDebugPolicy(&self) -> binder::Result<String> {
340 let debug_policy = DebugPolicy::from_host();
341 Ok(format!("{debug_policy:?}"))
342 }
343
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100344 /// Returns whether given feature is enabled
345 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
346 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000347 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100348 }
Alice Wange64dd182024-01-17 15:57:55 +0000349
350 fn enableTestAttestation(&self) -> binder::Result<()> {
351 GLOBAL_SERVICE.enableTestAttestation()
352 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000353
354 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
355 check_manage_access()?;
356 GLOBAL_SERVICE.isRemoteAttestationSupported()
357 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000358
359 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
360 // The response is specific to Microdroid. Updatable VMs are only possible if device
361 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
362 // this, however other guest OSes may do things differently.
363 check_manage_access()?;
364 Ok(is_secretkeeper_supported())
365 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000366
Shikha Panwar07d701c2024-03-28 14:43:52 +0000367 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
368 check_manage_access()?;
369 GLOBAL_SERVICE.removeVmInstance(instance_id)
370 }
371
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000372 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
373 check_manage_access()?;
374 GLOBAL_SERVICE.claimVmInstance(instance_id)
375 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000376}
377
Inseob Kimecde8c02024-09-03 13:11:08 +0900378/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
379#[derive(Debug, Default)]
380struct EarlyVmContext {
381 /// The unique CID assigned to the VM for vsock communication.
382 cid: Cid,
383 /// Temporary directory for this VM instance.
384 temp_dir: PathBuf,
385}
386
387impl EarlyVmContext {
388 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
389 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
390 // should trust clients, e.g. they won't run two VMs at the same time
391 let _ = remove_dir_all(&temp_dir);
392 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
393
394 Ok(Self { cid, temp_dir })
395 }
396}
397
398impl Interface for EarlyVmContext {}
399
400impl Drop for EarlyVmContext {
401 fn drop(&mut self) {
402 if let Err(e) = remove_dir_all(&self.temp_dir) {
403 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
404 }
405 }
406}
407
408impl IGlobalVmContext for EarlyVmContext {
409 fn getCid(&self) -> binder::Result<i32> {
410 Ok(self.cid as i32)
411 }
412
413 fn getTemporaryDirectory(&self) -> binder::Result<String> {
414 Ok(self.temp_dir.to_string_lossy().to_string())
415 }
416
417 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
418 Err(Status::new_exception_str(
419 ExceptionCode::UNSUPPORTED_OPERATION,
420 Some("Early VM doesn't support setting host console name"),
421 ))
422 }
423}
424
Inseob Kime3e932d2024-12-16 20:06:57 +0900425fn find_partition(path: Option<&Path>) -> binder::Result<String> {
426 let path = match path {
427 Some(path) => path,
428 None => return Ok("system".to_owned()),
429 };
Inseob Kimf79c5722024-12-16 17:29:57 +0900430 let mut components = path.components();
431 match components.nth(1) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900432 Some(std::path::Component::Normal(partition)) => {
Inseob Kimf79c5722024-12-16 17:29:57 +0900433 if partition != "apex" {
434 return Ok(partition.to_string_lossy().into_owned());
435 }
436
437 // If path is under /apex, find a partition of the preinstalled .apex path
438 let apex_name = match components.next() {
439 Some(std::path::Component::Normal(name)) => name.to_string_lossy(),
440 _ => {
441 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
442 .or_service_specific_exception(-1)
443 }
444 };
445
446 let apex_info_list = ApexInfoList::load()
447 .context("Failed to get apex info list")
448 .or_service_specific_exception(-1)?;
449
450 for apex_info in apex_info_list.list.iter() {
451 if apex_info.name == apex_name {
452 return Ok(apex_info.partition.to_lowercase());
453 }
454 }
455
456 Err(anyhow!("Can't find apex info for '{apex_name}'")).or_service_specific_exception(-1)
Inseob Kimecde8c02024-09-03 13:11:08 +0900457 }
458 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
459 .or_service_specific_exception(-1),
460 }
461}
462
Jiyong Park8611a6c2021-07-09 18:17:44 +0900463impl VirtualizationService {
464 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000465 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900466 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000467
Inseob Kimecde8c02024-09-03 13:11:08 +0900468 fn create_early_vm_context(
469 &self,
470 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900471 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900472 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900473 let name = match config {
474 VirtualMachineConfig::RawConfig(config) => &config.name,
475 VirtualMachineConfig::AppConfig(config) => &config.name,
476 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900477 let calling_partition = find_partition(calling_exe_path)?;
478 let early_vm = find_early_vm_for_partition(&calling_partition, name)
479 .or_service_specific_exception(-1)?;
480 let calling_exe_path = match calling_exe_path {
481 Some(path) => path,
482 None => {
483 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
484 .or_service_specific_exception(-1)
485 }
486 };
487 if Path::new(&early_vm.path) != calling_exe_path {
Inseob Kimecde8c02024-09-03 13:11:08 +0900488 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900489 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900490 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900491 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900492 ))
493 .or_service_specific_exception(-1);
494 }
495
496 let cid = early_vm.cid as Cid;
497 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
498
499 let context = EarlyVmContext::new(cid, temp_dir.clone())
500 .context(format!("Can't create early vm contexts for {cid}"))
501 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900502
Jiyong Park690c1ca2024-11-28 18:06:50 +0900503 if requires_vm_service(config) {
504 // Start VM service listening for connections from the new CID on port=CID.
505 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
506 let port = cid;
507 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
508 .context(format!("Could not start RpcServer on port {port}"))
509 .or_service_specific_exception(-1)?;
510 vm_server.start();
511 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
512 } else {
513 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
514 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900515 }
516
David Brazdil209074a2023-01-12 16:44:51 +0000517 fn create_vm_context(
518 &self,
519 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900520 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000521 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000522 const NUM_ATTEMPTS: usize = 5;
523
524 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000525 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000526 let cid = vm_context.getCid()? as Cid;
527 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900528
529 // We don't need to start the VM service for custom VMs.
530 if !requires_vm_service(config) {
531 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
532 }
533
David Brazdil8cf8f482022-11-23 14:21:26 +0000534 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
535
536 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000537 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000538 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000539 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000540 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900541 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000542 }
543 Err(err) => {
544 warn!("Could not start RpcServer on port {}: {}", port, err);
545 }
546 }
547 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900548 Err(anyhow!("Too many attempts to create VM context failed"))
549 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000550 }
551
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000552 fn create_vm_internal(
553 &self,
554 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900555 console_out_fd: Option<&ParcelFileDescriptor>,
556 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000557 log_fd: Option<&ParcelFileDescriptor>,
558 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000559 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000560 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000561 let requester_uid = get_calling_uid();
562 let requester_debug_pid = get_calling_pid();
563
Nikita Ioffe631717e2023-09-05 13:38:07 +0100564 check_config_features(config)?;
565
Inseob Kimecde8c02024-09-03 13:11:08 +0900566 if cfg!(early) {
567 check_config_allowed_for_early_vms(config)?;
568 }
569
Nikita Ioffeb1416122024-10-22 12:18:49 +0000570 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
571 info!("callers secontext: {}", caller_secontext);
572
David Brazdil209074a2023-01-12 16:44:51 +0000573 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900574 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900575 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900576 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900577 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900578 };
Inseob Kim1119d702022-05-02 18:01:58 +0900579
Alan Stokesfda70842023-12-20 17:50:14 +0000580 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100581 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900582 }
583
Nikita Ioffe5776f082023-02-10 21:38:26 +0000584 let gdb_port = extract_gdb_port(config);
585
586 // Additional permission checks if caller request gdb.
587 if gdb_port.is_some() {
588 check_gdb_allowed(config)?;
589 }
590
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800591 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900592 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800593 if let Some(dt_overlay) =
594 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
595 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900596 device_tree_overlays.push(dt_overlay);
597 }
598 if let Some(dtbo) = get_dtbo(config) {
599 let dtbo = File::from(
600 dtbo.as_ref()
601 .try_clone()
602 .context("Failed to create VM DTBO from ParcelFileDescriptor")
603 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
604 );
605 device_tree_overlays.push(dtbo);
606 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900607
Jaewan Kimf3143242024-03-15 06:56:31 +0000608 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000609 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900610 Some(prepare_ramdump_file(&temporary_directory)?)
611 } else {
612 None
613 };
614
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000615 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900616 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100617 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900618 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100619 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100620 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
621 Some(clone_file(fd)?)
622 } else if debug_config.dump_device_tree {
623 Some(prepare_dump_dt_file(&temporary_directory)?)
624 } else {
625 None
626 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000627
628 // Counter to generate unique IDs for temporary image files.
629 let mut next_temporary_image_id = 0;
630 // Files which are referred to from composite images. These must be mapped to the crosvm
631 // child process, and not closed before it is started.
632 let mut indirect_files = vec![];
633
Alan Stokes7bc146c2022-10-20 17:10:32 +0100634 let (is_app_config, config) = match config {
635 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
636 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900637 let config = load_app_config(config, &debug_config, &temporary_directory)
638 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900639 *is_protected = config.protectedVm;
640 let message = format!("Failed to load app config: {:?}", e);
641 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900642 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900643 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100644 (true, BorrowedOrOwned::Owned(config))
645 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000646 };
647 let config = config.as_ref();
648 *is_protected = config.protectedVm;
649
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000650 if !config.teeServices.is_empty() {
651 check_tee_service_permission(&caller_secontext, &config.teeServices)
652 .with_log()
653 .or_binder_exception(ExceptionCode::SECURITY)?;
654 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000655
Jiyong Park3051ffe2024-11-26 14:41:58 +0900656 let kernel = maybe_clone_file(&config.kernel)?;
657 let initrd = maybe_clone_file(&config.initrd)?;
658
659 if config.protectedVm {
660 // Fail fast with a meaningful error message in case device doesn't support pVMs.
661 check_protected_vm_is_supported()?;
662
663 // In a protected VM, we require custom kernels to come from a trusted source
664 // (b/237054515).
665 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
666
667 // Check if partition images are labeled incorrectly. This is to prevent random images
668 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
669 // from being loaded in a pVM. This applies to everything but the instance image in the
670 // raw config, and everything but the non-executable, generated partitions in the app
671 // config.
672 config
673 .disks
674 .iter()
675 .flat_map(|disk| disk.partitions.iter())
676 .filter(|partition| {
677 if is_app_config {
678 !is_safe_app_partition(&partition.label)
679 } else {
680 !is_safe_raw_partition(&partition.label)
681 }
682 })
683 .try_for_each(check_label_for_partition)
684 .or_service_specific_exception(-1)?;
685 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000686
Inseob Kimff48a7c2024-02-26 22:07:21 +0900687 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
688 // have unstable interfaces.
689 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Inseob Kime3e932d2024-12-16 20:06:57 +0900690 check_partitions_for_files(config, &find_partition(CALLING_EXE_PATH.as_deref())?)
691 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900692
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000693 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900694 write_zero_filler(&zero_filler_path)
695 .context("Failed to make composite image")
696 .with_log()
697 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000698
699 // Assemble disk images if needed.
700 let disks = config
701 .disks
702 .iter()
703 .map(|disk| {
704 assemble_disk_image(
705 disk,
706 &zero_filler_path,
707 &temporary_directory,
708 &mut next_temporary_image_id,
709 &mut indirect_files,
710 )
711 })
712 .collect::<Result<Vec<DiskFile>, _>>()?;
713
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700714 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
715
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000716 let (cpus, host_cpu_topology) = match config.cpuTopology {
717 CpuTopology::MATCH_HOST => (None, true),
718 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
Frederick Mayle681254c2024-12-11 19:20:06 -0800719 CpuTopology::CUSTOM => (
720 NonZeroU32::new(
721 u32::try_from(config.customVcpuCount)
722 .context("bad customVcpuCount")
723 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
724 ),
725 false,
726 ),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000727 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900728 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
729 .with_log()
730 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000731 }
732 };
733
Jaewan Kimf43372b2024-12-13 18:33:58 +0900734 let (vfio_devices, dtbo) = match &config.devices {
735 AssignedDevices::Devices(devices) if !devices.is_empty() => {
736 let mut set = HashSet::new();
737 for device in devices.iter() {
738 let path = canonicalize(device)
739 .with_context(|| format!("can't canonicalize {device}"))
740 .or_service_specific_exception(-1)?;
741 if !set.insert(path) {
742 return Err(anyhow!("duplicated device {device}"))
743 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
744 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900745 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900746 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
747 let dtbo_file = File::from(
748 GLOBAL_SERVICE
749 .getDtboFile()?
750 .as_ref()
751 .try_clone()
752 .context("Failed to create VM DTBO from ParcelFileDescriptor")
753 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
754 );
755 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900756 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900757 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900758 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900759 let display_config = if cfg!(paravirtualized_devices) {
760 config
761 .displayConfig
762 .as_ref()
763 .map(DisplayConfig::new)
764 .transpose()
765 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
766 } else {
767 None
768 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700769 let gpu_config = if cfg!(paravirtualized_devices) {
770 config
771 .gpuConfig
772 .as_ref()
773 .map(GpuConfig::new)
774 .transpose()
775 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
776 } else {
777 None
778 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900779
Jeongik Chac181be72024-03-27 00:18:30 +0900780 let input_device_options = if cfg!(paravirtualized_devices) {
781 config
782 .inputDevices
783 .iter()
784 .map(to_input_device_option_from)
785 .collect::<Result<Vec<InputDeviceOption>, _>>()
786 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
787 } else {
788 vec![]
789 };
790
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900791 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900792 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900793 if *is_protected {
794 return Err(anyhow!("Network feature is not supported for pVM yet"))
795 .with_log()
796 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
797 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900798 Some(File::from(
799 GLOBAL_SERVICE
800 .createTapInterface(&get_this_pid().to_string())?
801 .as_ref()
802 .try_clone()
803 .context("Failed to get TAP interface from ParcelFileDescriptor")
804 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
805 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900806 } else {
807 None
808 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800809
810 let audio_config = if cfg!(paravirtualized_devices) {
811 config.audioConfig.as_ref().map(AudioConfig::new)
812 } else {
813 None
814 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900815
Elie Kheirallah29d72912024-08-07 20:17:26 +0000816 let usb_config = config
817 .usbConfig
818 .as_ref()
819 .map(UsbConfig::new)
820 .unwrap_or(Ok(UsbConfig { controller: false }))
821 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
822
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000823 // Actually start the VM.
824 let crosvm_config = CrosvmConfig {
825 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000826 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000827 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000828 kernel,
829 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000830 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700831 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000832 params: config.params.to_owned(),
833 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900834 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700835 memory_mib: config
836 .memoryMib
837 .try_into()
838 .ok()
839 .and_then(NonZeroU32::new)
840 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800841 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000842 cpus,
843 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900844 console_out_fd,
845 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000846 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900847 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000848 indirect_files,
849 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900850 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000851 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900852 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000853 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900854 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900855 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900856 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000857 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900858 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800859 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000860 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700861 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800862 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800863 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000864 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000865 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800866 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
867 instance_id,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000868 };
869 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100870 VmInstance::new(
871 crosvm_config,
872 temporary_directory,
873 requester_uid,
874 requester_debug_pid,
875 vm_context,
876 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900877 .with_context(|| format!("Failed to create VM with config {:?}", config))
878 .with_log()
879 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000880 );
881 state.add_vm(Arc::downgrade(&instance));
882 Ok(VirtualMachine::create(instance))
883 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900884}
885
Alan Stokesfda70842023-12-20 17:50:14 +0000886/// Returns whether a VM config represents a "custom" virtual machine, which requires the
887/// USE_CUSTOM_VIRTUAL_MACHINE.
888fn is_custom_config(config: &VirtualMachineConfig) -> bool {
889 match config {
890 // Any raw (non-Microdroid) VM is considered custom.
891 VirtualMachineConfig::RawConfig(_) => true,
892 VirtualMachineConfig::AppConfig(config) => {
893 // Some features are reserved for platform apps only, even when using
894 // VirtualMachineAppConfig. Almost all of these features are grouped in the
895 // CustomConfig struct:
896 // - controlling CPUs;
897 // - gdbPort is set, meaning that crosvm will start a gdb server;
898 // - using anything other than the default kernel;
899 // - specifying devices to be assigned.
900 if config.customConfig.is_some() {
901 true
902 } else {
903 // Additional custom features not included in CustomConfig:
904 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000905 // - specifying extra APKs;
906 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900907 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000908 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900909 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
910 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000911 }
912 }
913 }
914}
915
Jiyong Park690c1ca2024-11-28 18:06:50 +0900916/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
917/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
918/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
919/// "microdroid" we run VirtualMachineService
920fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
921 match config {
922 VirtualMachineConfig::AppConfig(_) => true,
923 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
924 }
925}
926
Seungjae Yoo14e60182024-02-21 13:28:31 +0900927fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
928 let VirtualMachineConfig::AppConfig(config) = config else {
929 return Ok(None);
930 };
931 let Some(custom_config) = &config.customConfig else {
932 return Ok(None);
933 };
934 let Some(file) = custom_config.vendorImage.as_ref() else {
935 return Ok(None);
936 };
937
938 let file = clone_file(file)?;
939 let size =
940 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
941 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
942 .context("Failed to get vbmeta from microdroid-vendor.img")?;
943
944 for descriptor in vbmeta.descriptors()?.iter() {
945 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
946 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
947 return Ok(Some(root_digest.as_bytes().to_vec()));
948 }
949 }
950 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
951}
952
Jaewan Kimf43372b2024-12-13 18:33:58 +0900953fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000954 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800955 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000956 temporary_directory: &Path,
957) -> binder::Result<Option<File>> {
958 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
959 // (e.g. instance-id)
960 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
961 let host_ref_dt = if host_ref_dt.exists()
962 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
963 {
964 Some(host_ref_dt)
965 } else {
966 warn!("VM reference DT doesn't exist in host DT");
967 None
968 };
969
970 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
971 .context("Failed to extract vendor hashtree digest")
972 .or_service_specific_exception(-1)?;
973
Matt Gilbrideaade4272024-12-05 13:52:42 +0000974 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000975 info!(
976 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
977 match the trusted digest in the pvmfw config, causing the VM to fail to start."
978 );
Matt Gilbrideaade4272024-12-05 13:52:42 +0000979 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000980 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000981 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000982 };
983
Matt Gilbrideaade4272024-12-05 13:52:42 +0000984 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000985 let mut untrusted_props = Vec::with_capacity(2);
986 if cfg!(llpvm_changes) {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000987 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
988 let want_updatable = extract_want_updatable(config);
989 if want_updatable && is_secretkeeper_supported() {
990 // Let guest know that it can defer rollback protection to Secretkeeper by setting
991 // an empty property in untrusted node in DT. This enables Updatable VMs.
Matt Gilbrideaade4272024-12-05 13:52:42 +0000992 untrusted_props.push((cstr!("defer-rollback-protection"), &[]));
993 let sk: Strong<dyn ISecretkeeper> =
994 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
995 if sk.getInterfaceVersion()? >= 2 {
996 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
997 key_material = keyMaterial;
998 trusted_props.push((cstr!("secretkeeper_public_key"), key_material.as_slice()));
999 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001000 }
1001 }
1002
1003 let device_tree_overlay = if host_ref_dt.is_some()
1004 || !untrusted_props.is_empty()
1005 || !trusted_props.is_empty()
1006 {
1007 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1008 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1009 let fdt =
1010 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1011 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1012 .or_service_specific_exception(-1)?;
1013 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1014 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1015 } else {
1016 None
1017 };
1018 Ok(device_tree_overlay)
1019}
1020
Jaewan Kimf43372b2024-12-13 18:33:58 +09001021fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1022 let VirtualMachineConfig::RawConfig(config) = config else {
1023 return None;
1024 };
1025 match &config.devices {
1026 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1027 _ => None,
1028 }
1029}
1030
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001031fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001032 let file = OpenOptions::new()
1033 .create_new(true)
1034 .read(true)
1035 .write(true)
1036 .open(zero_filler_path)
1037 .with_context(|| "Failed to create zero.img")?;
1038 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001039 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001040}
1041
David Brazdilf50c7a62023-04-19 14:22:42 +00001042fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1043 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1044 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1045 part.flush()
1046}
1047
1048fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1049 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1050 part.flush()
1051}
1052
1053fn round_up(input: u64, granularity: u64) -> u64 {
1054 if granularity == 0 {
1055 return input;
1056 }
1057 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1058 let result = input.checked_add(granularity - 1).unwrap_or(input);
1059 (result / granularity) * granularity
1060}
1061
Jeongik Chac181be72024-03-27 00:18:30 +09001062fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1063 Ok(match input_device {
1064 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1065 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1066 height: u32::try_from(single_touch.height)?,
1067 width: u32::try_from(single_touch.width)?,
1068 name: if !single_touch.name.is_empty() {
1069 Some(single_touch.name.clone())
1070 } else {
1071 None
1072 },
1073 },
1074 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1075 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1076 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001077 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1078 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1079 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001080 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1081 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1082 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001083 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1084 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1085 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001086 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1087 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1088 height: u32::try_from(trackpad.height)?,
1089 width: u32::try_from(trackpad.width)?,
1090 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1091 },
Jeongik Cha10494912024-07-16 11:19:50 +09001092 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1093 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1094 height: u32::try_from(multi_touch.height)?,
1095 width: u32::try_from(multi_touch.width)?,
1096 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1097 },
Jeongik Chac181be72024-03-27 00:18:30 +09001098 })
1099}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001100
1101fn assemble_shared_paths(
1102 shared_paths: &[SharedPath],
1103 temporary_directory: &Path,
1104) -> Result<Vec<SharedPathConfig>, Status> {
1105 if shared_paths.is_empty() {
1106 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1107 }
1108
1109 shared_paths
1110 .iter()
1111 .map(|path| {
1112 Ok(SharedPathConfig {
1113 path: path.sharedPath.clone(),
1114 host_uid: path.hostUid,
1115 host_gid: path.hostGid,
1116 guest_uid: path.guestUid,
1117 guest_gid: path.guestGid,
1118 mask: path.mask,
1119 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001120 socket_path: temporary_directory
1121 .join(&path.socketPath)
1122 .to_string_lossy()
1123 .to_string(),
1124 socket_fd: maybe_clone_file(&path.socketFd)?,
1125 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001126 })
1127 })
1128 .collect()
1129}
1130
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001131/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1132///
1133/// This may involve assembling a composite disk from a set of partition images.
1134fn assemble_disk_image(
1135 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001136 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001137 temporary_directory: &Path,
1138 next_temporary_image_id: &mut u64,
1139 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001140) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001141 let image = if !disk.partitions.is_empty() {
1142 if disk.image.is_some() {
1143 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001144 return Err(anyhow!("DiskImage contains both image and partitions"))
1145 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001146 }
1147
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001148 let composite_image_filenames =
1149 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1150 let (image, partition_files) = make_composite_image(
1151 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001152 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001153 &composite_image_filenames.composite,
1154 &composite_image_filenames.header,
1155 &composite_image_filenames.footer,
1156 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001157 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1158 .with_log()
1159 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001160
1161 // Pass the file descriptors for the various partition files to crosvm when it
1162 // is run.
1163 indirect_files.extend(partition_files);
1164
1165 image
1166 } else if let Some(image) = &disk.image {
1167 clone_file(image)?
1168 } else {
1169 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001170 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1171 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001172 };
1173
1174 Ok(DiskFile { image, writable: disk.writable })
1175}
1176
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001177fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1178 if let Some(ref mut params) = vm_config.params {
1179 params.push(' ');
1180 params.push_str(param)
1181 } else {
1182 vm_config.params = Some(param.to_owned())
1183 }
1184}
1185
Inseob Kim46257382024-01-03 15:41:22 +09001186fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1187 if config.extension()?.to_str()? != "json" {
1188 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001189 }
Inseob Kim46257382024-01-03 15:41:22 +09001190
1191 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1192}
1193
1194fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1195 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1196 let os_names =
1197 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1198
1199 Ok(os_names)
1200}
1201
1202fn get_supported_os_names() -> Result<HashSet<String>> {
1203 if !cfg!(vendor_modules) {
1204 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1205 }
1206
1207 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1208}
1209
1210fn is_valid_os(os_name: &str) -> bool {
1211 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001212}
1213
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001214fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1215 if !cfg!(vendor_modules) {
1216 return false;
1217 }
1218 match config {
1219 VirtualMachineConfig::RawConfig(_) => false,
1220 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1221 }
1222}
1223
Jooyung Han21e9b922021-06-26 04:14:16 +09001224fn load_app_config(
1225 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001226 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001227 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001228) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001229 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1230 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001231 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001232
Shikha Panwar22e70452022-10-10 18:32:55 +00001233 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1234 Some(clone_file(file)?)
1235 } else {
1236 None
1237 };
1238
Alan Stokesfda70842023-12-20 17:50:14 +00001239 let vm_payload_config;
1240 let extra_apk_files: Vec<_>;
1241 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001242 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001243 vm_payload_config =
1244 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1245 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1246 extra_apk_files = vm_payload_config
1247 .extra_apks
1248 .iter()
1249 .enumerate()
1250 .map(|(i, apk)| {
1251 File::open(PathBuf::from(&apk.path))
1252 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1253 })
1254 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001255 }
Alan Stokesfda70842023-12-20 17:50:14 +00001256 Payload::PayloadConfig(payload_config) => {
1257 vm_payload_config = create_vm_payload_config(payload_config)?;
1258 extra_apk_files =
1259 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1260 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001261 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001262
Inseob Kim89b24592024-02-23 18:59:43 +09001263 let payload_config_os = vm_payload_config.os.name.as_str();
1264 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1265 bail!("'os' in payload config is deprecated");
1266 }
1267
Inseob Kim172f9eb2023-11-06 17:02:08 +09001268 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001269 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001270 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001271 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001272 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001273
1274 // It is safe to construct a filename based on the os_name because we've already checked that it
1275 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001276 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1277 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001278 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001279
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001280 if let Some(custom_config) = &config.customConfig {
1281 if let Some(file) = custom_config.customKernelImage.as_ref() {
1282 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1283 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001284 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001285
1286 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001287 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001288 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001289 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001290
Jaewan Kimf43372b2024-12-13 18:33:58 +09001291 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001292 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001293
1294 for param in custom_config.extraKernelCmdlineParams.iter() {
1295 append_kernel_param(param, &mut vm_config);
1296 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001297
1298 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001299 }
1300
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001301 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1302 // so we need to provide it in the kernel cmdline.
1303 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1304 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1305 append_kernel_param("page_shift=14", &mut vm_config);
1306 }
1307
Andrew Walbrancc045902021-07-27 16:06:17 +00001308 if config.memoryMib > 0 {
1309 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001310 }
1311
Chris Wailes6177c662024-05-09 14:37:44 -07001312 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001313 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001314 vm_config.cpuTopology = config.cpuTopology;
Frederick Mayle681254c2024-12-11 19:20:06 -08001315 if config.cpuTopology == CpuTopology::CUSTOM {
1316 bail!("AppConfig doesn't support CpuTopology::CUSTOM");
1317 }
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001318 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001319 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001320
Shikha Panwar22e70452022-10-10 18:32:55 +00001321 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001322 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001323
1324 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1325 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001326 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001327 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001328 temporary_directory,
1329 apk_file,
1330 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001331 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001332 &vm_payload_config,
1333 &mut vm_config,
1334 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001335
Andrew Walbrancc0db522021-07-12 17:03:42 +00001336 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001337}
1338
Inseob Kime3e932d2024-12-16 20:06:57 +09001339fn check_partition_for_file(fd: &ParcelFileDescriptor, calling_partition: &str) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001340 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1341 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1342
1343 // microdroid vendor image is OK
1344 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1345 {
1346 return Ok(());
1347 }
1348
Inseob Kime3e932d2024-12-16 20:06:57 +09001349 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
1350 let is_caller_vendor = calling_partition == "vendor" || calling_partition == "odm";
1351
1352 if is_fd_vendor != is_caller_vendor {
1353 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001354 }
1355
1356 Ok(())
1357}
1358
Inseob Kime3e932d2024-12-16 20:06:57 +09001359fn check_partitions_for_files(
1360 config: &VirtualMachineRawConfig,
1361 calling_partition: &str,
1362) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001363 config
1364 .disks
1365 .iter()
1366 .flat_map(|disk| disk.partitions.iter())
1367 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001368 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001369
Inseob Kime3e932d2024-12-16 20:06:57 +09001370 config
1371 .disks
1372 .iter()
1373 .filter_map(|disk| disk.image.as_ref())
1374 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1375
1376 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1377 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1378 config
1379 .bootloader
1380 .as_ref()
1381 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001382
1383 Ok(())
1384}
1385
Alan Stokes0d1ef782022-09-27 13:46:35 +01001386fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1387 let mut apk_zip = ZipArchive::new(apk_file)?;
1388 let config_file = apk_zip.by_name(config_path)?;
1389 Ok(serde_json::from_reader(config_file)?)
1390}
1391
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001392fn create_vm_payload_config(
1393 payload_config: &VirtualMachinePayloadConfig,
1394) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001395 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1396 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1397 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001398
1399 let payload_binary_name = &payload_config.payloadBinaryName;
1400 if payload_binary_name.contains('/') {
1401 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1402 }
1403
1404 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001405
1406 // The VM only cares about how many there are, these names are actually ignored.
1407 let extra_apk_count = payload_config.extraApks.len();
1408 let extra_apks =
1409 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1410
Inseob Kim89b24592024-02-23 18:59:43 +09001411 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001412}
1413
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001414/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001415fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001416 temporary_directory: &Path,
1417 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001418) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001419 let id = *next_temporary_image_id;
1420 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001421 CompositeImageFilenames {
1422 composite: temporary_directory.join(format!("composite-{}.img", id)),
1423 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1424 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1425 }
1426}
1427
1428/// Filenames for a composite disk image, including header and footer partitions.
1429#[derive(Clone, Debug, Eq, PartialEq)]
1430struct CompositeImageFilenames {
1431 /// The composite disk image itself.
1432 composite: PathBuf,
1433 /// The header partition image.
1434 header: PathBuf,
1435 /// The footer partition image.
1436 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001437}
1438
Jiyong Park753553b2021-07-12 21:21:09 +09001439/// Checks whether the caller has a specific permission
1440fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001441 if cfg!(early) {
1442 // Skip permission check for early VMs, in favor of SELinux
1443 return Ok(());
1444 }
David Brazdil1f530702022-10-03 12:18:10 +01001445 let calling_pid = get_calling_pid();
1446 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001447 // Root can do anything
1448 if calling_uid == 0 {
1449 return Ok(());
1450 }
1451 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001452 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001453 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001454 Ok(())
1455 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001456 Err(anyhow!("does not have the {} permission", perm))
1457 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001458 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001459}
1460
Jiyong Park753553b2021-07-12 21:21:09 +09001461/// Check whether the caller of the current Binder method is allowed to manage VMs
1462fn check_manage_access() -> binder::Result<()> {
1463 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1464}
1465
Inseob Kim1119d702022-05-02 18:01:58 +09001466/// Check whether the caller of the current Binder method is allowed to create custom VMs
1467fn check_use_custom_virtual_machine() -> binder::Result<()> {
1468 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1469}
1470
Alan Stokes185fe112023-01-10 16:20:55 +00001471/// Return whether a partition is exempt from selinux label checks, because we know that it does
1472/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001473fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001474 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001475 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001476 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001477 || label == "microdroid-apk-idsig"
1478 || label == "payload-metadata"
1479 || label.starts_with("extra-idsig-")
1480}
1481
Alice Wangc206b9b2023-08-28 14:13:51 +00001482/// Returns whether a partition with the given label is safe for a raw config VM.
1483fn is_safe_raw_partition(label: &str) -> bool {
1484 label == "vm-instance"
1485}
1486
Alan Stokes185fe112023-01-10 16:20:55 +00001487/// Check that a file SELinux label is acceptable.
1488///
1489/// 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 +09001490/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001491///
1492/// Note that sepolicy must also grant read access for these types to both virtualization
1493/// service and crosvm.
1494///
1495/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1496/// user devices (W^X).
1497fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1498 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001499 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001500 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001501 | "staging_data_file" // updated/staged APEX images
1502 | "system_file" // immutable dm-verity protected partition
1503 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001504 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001505 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001506 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001507 }
1508}
1509
Alan Stokes185fe112023-01-10 16:20:55 +00001510fn check_label_for_partition(partition: &Partition) -> Result<()> {
1511 let file = partition.image.as_ref().unwrap().as_ref();
1512 check_label_is_allowed(&getfilecon(file)?)
1513 .with_context(|| format!("Partition {} invalid", &partition.label))
1514}
1515
1516fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1517 if let Some(f) = kernel {
1518 check_label_for_file(f, "kernel")?;
1519 }
1520 if let Some(f) = initrd {
1521 check_label_for_file(f, "initrd")?;
1522 }
1523 Ok(())
1524}
1525fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1526 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1527}
1528
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001529/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1530#[derive(Debug)]
1531struct VirtualMachine {
1532 instance: Arc<VmInstance>,
1533}
1534
1535impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001536 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001537 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001538 }
1539}
1540
1541impl Interface for VirtualMachine {}
1542
Devin Moore407df8f2024-08-27 19:39:16 +00001543impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001544 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001545 // Don't check permission. The owner of the VM might have passed this binder object to
1546 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001547 Ok(self.instance.cid as i32)
1548 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001549
Andrew Walbran6b650662021-09-07 13:13:23 +00001550 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001551 // Don't check permission. The owner of the VM might have passed this binder object to
1552 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001553 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001554 }
1555
1556 fn registerCallback(
1557 &self,
1558 callback: &Strong<dyn IVirtualMachineCallback>,
1559 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001560 // Don't check permission. The owner of the VM might have passed this binder object to
1561 // others.
1562 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001563 // TODO: Should this give an error if the VM is already dead?
1564 self.instance.callbacks.add(callback.clone());
1565 Ok(())
1566 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001567
Andrew Walbranf8d94112021-09-07 11:45:36 +00001568 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001569 self.instance
1570 .start()
1571 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1572 .with_log()
1573 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001574 }
1575
Inseob Kima446f802022-07-11 19:46:37 +09001576 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001577 self.instance
1578 .kill()
1579 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1580 .with_log()
1581 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001582 }
1583
Keir Fraser48221ba2024-07-12 14:05:02 +00001584 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1585 let balloon = self
1586 .instance
1587 .get_memory_balloon()
1588 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1589 .with_log()
1590 .or_service_specific_exception(-1)?;
1591 Ok(balloon.try_into().unwrap())
1592 }
1593
1594 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001595 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001596 .set_memory_balloon(num_bytes.try_into().unwrap())
1597 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001598 .with_log()
1599 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001600 }
1601
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001602 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001603 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001604 return Err(Status::new_service_specific_error_str(
1605 IVirtualMachine::ERROR_UNEXPECTED,
1606 Some("Virtual Machine is not running"),
1607 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001608 }
Alan Stokes10c47672022-12-13 17:17:08 +00001609 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001610 if port < VSOCK_PRIV_PORT_MAX {
1611 return Err(Status::new_service_specific_error_str(
1612 IVirtualMachine::ERROR_UNEXPECTED,
1613 Some("Can't connect to privileged port {port}"),
1614 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001615 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001616 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1617 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001618 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001619 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001620 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001621
Devin Moore407df8f2024-08-27 19:39:16 +00001622 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1623 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1624 return Err(Status::new_service_specific_error_str(
1625 IVirtualMachine::ERROR_UNEXPECTED,
1626 Some("Virtual Machine is not running"),
1627 ));
1628 }
1629 let port = port as u32;
1630 if port < VSOCK_PRIV_PORT_MAX {
1631 return Err(Status::new_service_specific_error_str(
1632 IVirtualMachine::ERROR_UNEXPECTED,
1633 Some("Can't connect to privileged port {port}"),
1634 ));
1635 }
1636 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001637 let addr = sockaddr_vm {
1638 svm_family: AF_VSOCK as sa_family_t,
1639 svm_reserved1: 0,
1640 svm_port: port,
1641 svm_cid: cid,
1642 svm_zero: [0u8; 4],
1643 };
1644 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001645 let accessor = Accessor::new(name, get_connection_info);
1646 accessor
1647 .as_binder()
1648 .context("The newly created Accessor should always have a binder")
1649 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1650 }
1651
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001652 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1653 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1654 }
Jiyong Park23b67392024-07-04 13:51:42 +09001655
1656 fn suspend(&self) -> binder::Result<()> {
1657 self.instance
1658 .suspend()
1659 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1660 .with_log()
1661 .or_service_specific_exception(-1)
1662 }
1663
1664 fn resume(&self) -> binder::Result<()> {
1665 self.instance
1666 .resume()
1667 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1668 .with_log()
1669 .or_service_specific_exception(-1)
1670 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001671}
1672
1673impl Drop for VirtualMachine {
1674 fn drop(&mut self) {
1675 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001676 if let Err(e) = self.instance.kill() {
1677 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1678 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001679 }
1680}
1681
1682/// A set of Binders to be called back in response to various events on the VM, such as when it
1683/// dies.
1684#[derive(Debug, Default)]
1685pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1686
1687impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001688 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001689 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001690 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001691 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001692 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001693 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001694 }
1695 }
1696 }
1697
Inseob Kim14cb8692021-08-31 21:50:39 +09001698 /// Call all registered callbacks to notify that the payload is ready to serve.
1699 pub fn notify_payload_ready(&self, cid: Cid) {
1700 let callbacks = &*self.0.lock().unwrap();
1701 for callback in callbacks {
1702 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001703 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001704 }
1705 }
1706 }
1707
Inseob Kim2444af92021-08-31 01:22:50 +09001708 /// Call all registered callbacks to notify that the payload has finished.
1709 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1710 let callbacks = &*self.0.lock().unwrap();
1711 for callback in callbacks {
1712 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001713 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001714 }
1715 }
1716 }
1717
Jooyung Handd0a1732021-11-23 15:26:20 +09001718 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001719 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001720 let callbacks = &*self.0.lock().unwrap();
1721 for callback in callbacks {
1722 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001723 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001724 }
1725 }
1726 }
1727
Andrew Walbrandae07162021-03-12 17:05:20 +00001728 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001729 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001730 let callbacks = &*self.0.lock().unwrap();
1731 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001732 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001733 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001734 }
1735 }
1736 }
1737
1738 /// Add a new callback to the set.
1739 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1740 self.0.lock().unwrap().push(callback);
1741 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001742}
1743
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001744/// The mutable state of the VirtualizationService. There should only be one instance of this
1745/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001746#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001747struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001748 /// The VMs which have been started. When VMs are started a weak reference is added to this
1749 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1750 /// the Binder client are dropped the weak reference here will become invalid, and will be
1751 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001752 vms: Vec<Weak<VmInstance>>,
1753}
1754
1755impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001756 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001757 fn vms(&self) -> Vec<Arc<VmInstance>> {
1758 // Attempt to upgrade the weak pointers to strong pointers.
1759 self.vms.iter().filter_map(Weak::upgrade).collect()
1760 }
1761
1762 /// Add a new VM to the list.
1763 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1764 // Garbage collect any entries from the stored list which no longer exist.
1765 self.vms.retain(|vm| vm.strong_count() > 0);
1766
1767 // Actually add the new VM.
1768 self.vms.push(vm);
1769 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001770
Jiyong Park8611a6c2021-07-09 18:17:44 +09001771 /// Get a VM that corresponds to the given cid
1772 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1773 self.vms().into_iter().find(|vm| vm.cid == cid)
1774 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001775}
1776
Andrew Walbran6b650662021-09-07 13:13:23 +00001777/// Gets the `VirtualMachineState` of the given `VmInstance`.
1778fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001779 match &*instance.vm_state.lock().unwrap() {
1780 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1781 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001782 PayloadState::Starting => VirtualMachineState::STARTING,
1783 PayloadState::Started => VirtualMachineState::STARTED,
1784 PayloadState::Ready => VirtualMachineState::READY,
1785 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001786 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001787 },
1788 VmState::Dead => VirtualMachineState::DEAD,
1789 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001790 }
1791}
1792
David Brazdilf50c7a62023-04-19 14:22:42 +00001793/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001794pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1795 file.as_ref()
1796 .try_clone()
1797 .context("Failed to clone File from ParcelFileDescriptor")
1798 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001799 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001800}
1801
Andrew Walbrand3a84182021-09-07 14:48:52 +00001802/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001803fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001804 file.as_ref().map(clone_file).transpose()
1805}
1806
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001807/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001808fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1809 // SAFETY: ownership is transferred from stream to f
1810 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1811 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001812}
1813
Jiyong Parkdcf17412022-02-08 15:07:23 +09001814/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001815fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1816 VersionReq::parse(s)
1817 .with_context(|| format!("Invalid platform version requirement {}", s))
1818 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001819}
1820
Jiyong Parked180932023-02-24 19:55:41 +09001821/// Create the empty ramdump file
1822fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1823 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1824 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1825 // owner) for readout.
1826 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001827 let ramdump = File::create(ramdump_path)
1828 .context("Failed to prepare ramdump file")
1829 .with_log()
1830 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001831 Ok(ramdump)
1832}
1833
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001834/// Create the empty device tree dump file
1835fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1836 let path = temporary_directory.join("device_tree.dtb");
1837 let file = File::create(path)
1838 .context("Failed to prepare device tree dump file")
1839 .with_log()
1840 .or_service_specific_exception(-1)?;
1841 Ok(file)
1842}
1843
Nikita Ioffe5776f082023-02-10 21:38:26 +00001844fn is_protected(config: &VirtualMachineConfig) -> bool {
1845 match config {
1846 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1847 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1848 }
1849}
1850
1851fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1852 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001853 return Err(anyhow!("Can't use gdb with protected VMs"))
1854 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001855 }
1856
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001857 if get_debug_level(config) == Some(DebugLevel::NONE) {
1858 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1859 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001860 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001861
1862 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001863}
1864
Shikha Panwar61a74b52024-02-16 13:17:01 +00001865fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1866 match config {
1867 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1868 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1869 }
1870}
1871
Alan Stokesc96b35e2024-05-03 13:21:20 +01001872fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1873 match config {
1874 VirtualMachineConfig::RawConfig(_) => true,
1875 VirtualMachineConfig::AppConfig(config) => {
1876 let Some(custom) = &config.customConfig else { return true };
1877 custom.wantUpdatable
1878 }
1879 }
1880}
1881
Nikita Ioffe5776f082023-02-10 21:38:26 +00001882fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1883 match config {
1884 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001885 VirtualMachineConfig::AppConfig(config) => {
1886 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1887 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001888 }
1889}
1890
Nikita Ioffe631717e2023-09-05 13:38:07 +01001891fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1892 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1893 if let Some(custom_config) = &config.customConfig {
1894 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1895 return Err(anyhow!("vendor modules feature is disabled"))
1896 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1897 }
1898 }
1899 Ok(())
1900}
1901
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001902fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1903 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1904 if let Some(custom_config) = &config.customConfig {
1905 if !custom_config.devices.is_empty() {
1906 return Err(anyhow!("device assignment feature is disabled"))
1907 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1908 }
1909 }
1910 Ok(())
1911}
1912
Alan Stokesfda70842023-12-20 17:50:14 +00001913fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1914 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1915 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1916 if !payload_config.extraApks.is_empty() {
1917 return Err(anyhow!("multi-tenant feature is disabled"))
1918 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1919 }
1920 Ok(())
1921}
1922
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001923fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1924 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1925 if let Some(custom_config) = &config.customConfig {
1926 if !custom_config.extraKernelCmdlineParams.is_empty() {
1927 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1928 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1929 }
1930 }
1931 Ok(())
1932}
1933
Nikita Ioffe99548382024-10-21 15:54:46 +00001934fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1935 match config {
1936 VirtualMachineConfig::RawConfig(config) => {
1937 if !config.teeServices.is_empty() {
1938 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1939 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1940 }
1941 }
1942 VirtualMachineConfig::AppConfig(config) => {
1943 if let Some(custom_config) = &config.customConfig {
1944 if !custom_config.teeServices.is_empty() {
1945 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1946 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1947 }
1948 }
1949 }
1950 };
1951 Ok(())
1952}
1953
Nikita Ioffef934e812024-07-05 15:44:41 +00001954fn check_protected_vm_is_supported() -> binder::Result<()> {
1955 let is_pvm_supported =
1956 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1957 if is_pvm_supported {
1958 Ok(())
1959 } else {
1960 Err(anyhow!("pVM is not supported"))
1961 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1962 }
1963}
1964
Nikita Ioffe631717e2023-09-05 13:38:07 +01001965fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1966 if !cfg!(vendor_modules) {
1967 check_no_vendor_modules(config)?;
1968 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001969 if !cfg!(device_assignment) {
1970 check_no_devices(config)?;
1971 }
Alan Stokesfda70842023-12-20 17:50:14 +00001972 if !cfg!(multi_tenant) {
1973 check_no_extra_apks(config)?;
1974 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001975 if !cfg!(debuggable_vms_improvements) {
1976 check_no_extra_kernel_cmdline_params(config)?;
1977 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001978 if !cfg!(tee_services_allowlist) {
1979 check_no_tee_services(config)?;
1980 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001981 Ok(())
1982}
1983
Inseob Kimecde8c02024-09-03 13:11:08 +09001984fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1985 check_no_vendor_modules(config)?;
1986 check_no_devices(config)?;
1987
1988 Ok(())
1989}
1990
Inseob Kim0168b462022-12-27 14:54:35 +09001991fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001992 fd: Option<&ParcelFileDescriptor>,
1993 tag: String,
1994) -> Result<Option<File>, Status> {
1995 if let Some(fd) = fd {
1996 return Ok(Some(clone_file(fd)?));
1997 }
1998
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001999 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002000 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002001
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002002 let mut reader = BufReader::new(File::from(read_fd));
2003 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002004
2005 std::thread::spawn(move || loop {
2006 let mut buf = vec![];
2007 match reader.read_until(b'\n', &mut buf) {
2008 Ok(0) => {
2009 // EOF
2010 return;
2011 }
2012 Ok(size) => {
2013 if buf[size - 1] == b'\n' {
2014 buf.pop();
2015 }
2016 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2017 }
2018 Err(e) => {
2019 error!("Could not read console pipe: {:?}", e);
2020 return;
2021 }
2022 };
2023 });
2024
2025 Ok(Some(write_fd))
2026}
2027
Jooyung Han35edb8f2021-07-01 16:17:16 +09002028/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2029/// it doesn't require that T implements Clone.
2030enum BorrowedOrOwned<'a, T> {
2031 Borrowed(&'a T),
2032 Owned(T),
2033}
2034
2035impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
2036 fn as_ref(&self) -> &T {
2037 match self {
2038 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002039 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002040 }
2041 }
2042}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002043
2044/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2045#[derive(Debug, Default)]
2046struct VirtualMachineService {
2047 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002048 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002049}
2050
2051impl Interface for VirtualMachineService {}
2052
2053impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002054 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2055 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002056 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002057 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002058 vm.update_payload_state(PayloadState::Started)
2059 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002060 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002061
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002062 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2063 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002064 Ok(())
2065 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002066 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002067 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002068 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002069 }
Inseob Kim2444af92021-08-31 01:22:50 +09002070
Inseob Kimc7d28c72021-10-25 14:28:10 +00002071 fn notifyPayloadReady(&self) -> binder::Result<()> {
2072 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002073 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002074 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002075 vm.update_payload_state(PayloadState::Ready)
2076 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002077 vm.callbacks.notify_payload_ready(cid);
2078 Ok(())
2079 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002080 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002081 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002082 }
2083 }
2084
Inseob Kimc7d28c72021-10-25 14:28:10 +00002085 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2086 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002087 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002088 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002089 vm.update_payload_state(PayloadState::Finished)
2090 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002091 vm.callbacks.notify_payload_finished(cid, exit_code);
2092 Ok(())
2093 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002094 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002095 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002096 }
2097 }
2098
Alan Stokes2bead0d2022-09-05 16:58:34 +01002099 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002100 let cid = self.cid;
2101 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002102 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002103 vm.update_payload_state(PayloadState::Finished)
2104 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002105 vm.callbacks.notify_error(cid, error_code, message);
2106 Ok(())
2107 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002108 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002109 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002110 }
2111 }
Alice Wangc2fec932023-02-23 16:24:02 +00002112
Shikha Panware45e9422024-02-28 21:18:10 +00002113 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2114 if !is_secretkeeper_supported() {
2115 return Err(StatusCode::NAME_NOT_FOUND)?;
2116 }
2117 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2118 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002119 }
2120
Alice Wange64dd182024-01-17 15:57:55 +00002121 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2122 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002123 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002124}
2125
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002126fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002127 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2128 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002129}
2130
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002131impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002132 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002133 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002134 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002135 BinderFeatures::default(),
2136 )
2137 }
2138}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002139
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002140struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2141
2142impl Interface for SecretkeeperProxy {}
2143
2144impl ISecretkeeper for SecretkeeperProxy {
2145 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2146 // Pass the request to the channel, and read the response.
2147 self.0.processSecretManagementRequest(req)
2148 }
2149
2150 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2151 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2152 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2153 }
2154
2155 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2156 self.0.deleteIds(ids)
2157 }
2158
2159 fn deleteAll(&self) -> binder::Result<()> {
2160 self.0.deleteAll()
2161 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002162
2163 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2164 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2165 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2166 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2167 // use this API from the proxy.
2168 Err(ExceptionCode::SECURITY.into())
2169 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002170}
2171
2172struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2173
2174impl Interface for AuthGraphKeyExchangeProxy {}
2175
2176impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2177 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2178 self.0.create()
2179 }
2180
2181 fn init(
2182 &self,
2183 peer_pub_key: &PubKey,
2184 peer_id: &Identity,
2185 peer_nonce: &[u8],
2186 peer_version: i32,
2187 ) -> binder::Result<KeInitResult> {
2188 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2189 }
2190
2191 fn finish(
2192 &self,
2193 peer_pub_key: &PubKey,
2194 peer_id: &Identity,
2195 peer_signature: &SessionIdSignature,
2196 peer_nonce: &[u8],
2197 peer_version: i32,
2198 own_key: &Key,
2199 ) -> binder::Result<SessionInfo> {
2200 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2201 }
2202
2203 fn authenticationComplete(
2204 &self,
2205 peer_signature: &SessionIdSignature,
2206 shared_keys: &[AuthgraphArc; 2],
2207 ) -> binder::Result<[AuthgraphArc; 2]> {
2208 self.0.authenticationComplete(peer_signature, shared_keys)
2209 }
2210}
2211
Inseob Kimecde8c02024-09-03 13:11:08 +09002212// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002213#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002214struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002215 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002216 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002217 path: String,
2218}
2219
2220#[derive(Debug, Default, Deserialize)]
2221struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002222 early_vm: Vec<EarlyVm>,
2223}
2224
Inseob Kim7e1877b2024-11-07 17:28:56 +09002225static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2226 LazyLock::new(|| Mutex::new(HashMap::new()));
2227
Inseob Kimecde8c02024-09-03 13:11:08 +09002228fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2229 match partition {
2230 "system" => Ok(100..200),
2231 "system_ext" | "product" => Ok(200..300),
Inseob Kime3e932d2024-12-16 20:06:57 +09002232 "vendor" | "odm" => Ok(300..400),
Inseob Kimecde8c02024-09-03 13:11:08 +09002233 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2234 }
2235}
2236
Inseob Kim7e1877b2024-11-07 17:28:56 +09002237fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002238 if !xml_path.exists() {
2239 bail!("{} doesn't exist", xml_path.display());
2240 }
2241
2242 let xml =
2243 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2244 let xml = String::from_utf8(xml)
2245 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2246 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2247 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2248
Inseob Kim7e1877b2024-11-07 17:28:56 +09002249 Ok(early_vms.early_vm)
2250}
Inseob Kimecde8c02024-09-03 13:11:08 +09002251
Inseob Kim7e1877b2024-11-07 17:28:56 +09002252fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2253 for early_vm in early_vms {
2254 let cid = early_vm
2255 .cid
2256 .try_into()
2257 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2258
2259 ensure!(
2260 cid_range.contains(&cid),
2261 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2262 early_vm.name
2263 );
2264 }
2265 Ok(())
2266}
2267
2268fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2269 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2270
2271 if let Some(result) = cache.get(partition) {
2272 return Ok(result.clone());
2273 }
2274
2275 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2276 let mut early_vms = Vec::new();
2277 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2278 match entry {
2279 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2280 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2281 }
2282 }
2283
2284 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2285 .with_context(|| format!("CID validation for {partition} failed"))?;
2286
2287 cache.insert(partition.to_owned(), early_vms.clone());
2288
2289 Ok(early_vms)
2290}
2291
2292fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2293 let mut found_vm: Option<&EarlyVm> = None;
2294
2295 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002296 if early_vm.name != name {
2297 continue;
2298 }
2299
Inseob Kimecde8c02024-09-03 13:11:08 +09002300 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002301 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002302 }
2303
2304 found_vm = Some(early_vm);
2305 }
2306
Inseob Kim7e1877b2024-11-07 17:28:56 +09002307 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002308}
2309
2310fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002311 let early_vms = get_early_vms_in_partition(partition)
2312 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2313
2314 Ok(find_early_vm(&early_vms, name)
2315 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2316 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002317}
2318
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002319#[cfg(test)]
2320mod tests {
2321 use super::*;
2322
2323 #[test]
2324 fn test_is_allowed_label_for_partition() -> Result<()> {
2325 let expected_results = vec![
2326 ("u:object_r:system_file:s0", true),
2327 ("u:object_r:apk_data_file:s0", true),
2328 ("u:object_r:app_data_file:s0", false),
2329 ("u:object_r:app_data_file:s0:c512,c768", false),
2330 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2331 ("invalid", false),
2332 ("user:role:apk_data_file:severity:categories", true),
2333 ("user:role:apk_data_file:severity:categories:extraneous", false),
2334 ];
2335
2336 for (label, expected_valid) in expected_results {
2337 let context = SeContext::new(label)?;
2338 let result = check_label_is_allowed(&context);
2339 if expected_valid {
2340 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2341 } else if result.is_ok() {
2342 bail!("Expected label {} to be disallowed", label);
2343 }
2344 }
2345 Ok(())
2346 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002347
2348 #[test]
2349 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2350 let apk = tempfile::tempfile().unwrap();
2351 let idsig = tempfile::tempfile().unwrap();
2352
2353 let ret = create_or_update_idsig_file(
2354 &ParcelFileDescriptor::new(apk),
2355 &ParcelFileDescriptor::new(idsig),
2356 );
2357 assert!(ret.is_err(), "should fail");
2358 Ok(())
2359 }
2360
2361 #[test]
2362 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2363 let tmp_dir = tempfile::TempDir::new().unwrap();
2364 let apk = File::open(tmp_dir.path()).unwrap();
2365 let idsig = tempfile::tempfile().unwrap();
2366
2367 let ret = create_or_update_idsig_file(
2368 &ParcelFileDescriptor::new(apk),
2369 &ParcelFileDescriptor::new(idsig),
2370 );
2371 assert!(ret.is_err(), "should fail");
2372 Ok(())
2373 }
2374
2375 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2376 /// on ext4 filesystem is passed.
2377 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2378 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2379 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2380 #[test]
2381 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2382 // APEXes are backed by the ext4.
2383 let apk = File::open("/apex/com.android.virt/").unwrap();
2384 let idsig = tempfile::tempfile().unwrap();
2385
2386 let ret = create_or_update_idsig_file(
2387 &ParcelFileDescriptor::new(apk),
2388 &ParcelFileDescriptor::new(idsig),
2389 );
2390 assert!(ret.is_err(), "should fail");
2391 Ok(())
2392 }
Jiyong Park8d192952023-06-26 14:29:51 +09002393
2394 #[test]
2395 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2396 use std::io::Seek;
2397
2398 // Pick any APK
2399 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2400 let mut idsig = tempfile::tempfile().unwrap();
2401
2402 create_or_update_idsig_file(
2403 &ParcelFileDescriptor::new(apk.try_clone()?),
2404 &ParcelFileDescriptor::new(idsig.try_clone()?),
2405 )?;
2406 let modified_orig = idsig.metadata()?.modified()?;
2407 apk.rewind()?;
2408 idsig.rewind()?;
2409
2410 // Call the function again
2411 create_or_update_idsig_file(
2412 &ParcelFileDescriptor::new(apk.try_clone()?),
2413 &ParcelFileDescriptor::new(idsig.try_clone()?),
2414 )?;
2415 let modified_new = idsig.metadata()?.modified()?;
2416 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2417 Ok(())
2418 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002419
2420 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002421 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2422 use std::io::Read;
2423
2424 // Pick any APK
2425 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2426 let idsig_empty = tempfile::tempfile().unwrap();
2427 let mut idsig_invalid = tempfile::tempfile().unwrap();
2428 idsig_invalid.write_all(b"Oops")?;
2429
2430 // Create new idsig
2431 create_or_update_idsig_file(
2432 &ParcelFileDescriptor::new(apk.try_clone()?),
2433 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2434 )?;
2435 apk.rewind()?;
2436
2437 // Update idsig_invalid
2438 create_or_update_idsig_file(
2439 &ParcelFileDescriptor::new(apk.try_clone()?),
2440 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2441 )?;
2442
2443 // Ensure the 2 idsig files have same size!
2444 assert!(
2445 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2446 "idsig files differ in size"
2447 );
2448 // Ensure the 2 idsig files have same content!
2449 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2450 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2451 }
2452 Ok(())
2453 }
2454 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002455 fn test_append_kernel_param_first_param() {
2456 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2457 append_kernel_param("foo=1", &mut vm_config);
2458 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2459 }
2460
2461 #[test]
2462 fn test_append_kernel_param() {
2463 let mut vm_config =
2464 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2465 append_kernel_param("bar=42", &mut vm_config);
2466 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2467 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002468
Inseob Kim46257382024-01-03 15:41:22 +09002469 fn test_extract_os_name_from_config_path(
2470 path: &Path,
2471 expected_result: Option<&str>,
2472 ) -> Result<()> {
2473 let result = extract_os_name_from_config_path(path);
2474 if result.as_deref() != expected_result {
2475 bail!("Expected {:?} but was {:?}", expected_result, &result)
2476 }
2477 Ok(())
2478 }
2479
2480 #[test]
2481 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2482 test_extract_os_name_from_config_path(
2483 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2484 Some("microdroid"),
2485 )
2486 }
2487
2488 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002489 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2490 test_extract_os_name_from_config_path(
2491 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2492 Some("microdroid_16k"),
2493 )
2494 }
2495
2496 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002497 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2498 test_extract_os_name_from_config_path(
2499 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2500 Some("microdroid_gki-android14-6.1"),
2501 )
2502 }
2503
2504 #[test]
2505 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2506 test_extract_os_name_from_config_path(
2507 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2508 None,
2509 )
2510 }
2511
2512 #[test]
2513 fn test_extract_os_name_from_configs() -> Result<()> {
2514 let tmp_dir = tempfile::TempDir::new()?;
2515 let tmp_dir_path = tmp_dir.path().to_owned();
2516
2517 let mut os_names: HashSet<String> = HashSet::new();
2518 os_names.insert("microdroid".to_owned());
2519 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2520 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2521
2522 // config files
2523 for os_name in &os_names {
2524 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2525 }
2526
2527 // fake files not related to configs
2528 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2529 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2530
2531 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2532 Some(s) => s.to_owned(),
2533 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2534 };
2535
2536 let result = extract_os_names_from_configs(&glob_pattern)?;
2537 if result != os_names {
2538 bail!("Expected {:?} but was {:?}", os_names, result);
2539 }
2540 Ok(())
2541 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002542
2543 #[test]
2544 fn test_find_early_vms_from_xml() -> Result<()> {
2545 let tmp_dir = tempfile::TempDir::new()?;
2546 let tmp_dir_path = tmp_dir.path().to_owned();
2547 let xml_path = tmp_dir_path.join("early_vms.xml");
2548
2549 std::fs::write(
2550 &xml_path,
2551 br#"<?xml version="1.0" encoding="utf-8"?>
2552 <early_vms>
2553 <early_vm>
2554 <name>vm_demo_native_early</name>
2555 <cid>123</cid>
2556 <path>/system/bin/vm_demo_native_early</path>
2557 </early_vm>
2558 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002559 <name>vm_demo_native_early_2</name>
2560 <cid>456</cid>
2561 <path>/system/bin/vm_demo_native_early_2</path>
2562 </early_vm>
2563 </early_vms>
2564 "#,
2565 )?;
2566
2567 let cid_range = 100..1000;
2568
2569 let early_vms = get_early_vms_in_path(&xml_path)?;
2570 validate_cid_range(&early_vms, &cid_range)?;
2571
2572 let test_cases = [
2573 (
2574 "vm_demo_native_early",
2575 EarlyVm {
2576 name: "vm_demo_native_early".to_owned(),
2577 cid: 123,
2578 path: "/system/bin/vm_demo_native_early".to_owned(),
2579 },
2580 ),
2581 (
2582 "vm_demo_native_early_2",
2583 EarlyVm {
2584 name: "vm_demo_native_early_2".to_owned(),
2585 cid: 456,
2586 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2587 },
2588 ),
2589 ];
2590
2591 for (name, expected) in test_cases {
2592 let result = find_early_vm(&early_vms, name)?;
2593 assert_eq!(result, &expected);
2594 }
2595
2596 Ok(())
2597 }
2598
2599 #[test]
2600 fn test_invalid_cid_validation() -> Result<()> {
2601 let tmp_dir = tempfile::TempDir::new()?;
2602 let xml_path = tmp_dir.path().join("early_vms.xml");
2603
2604 let cid_range = 100..1000;
2605
2606 for cid in [-1, 999999] {
2607 std::fs::write(
2608 &xml_path,
2609 format!(
2610 r#"<?xml version="1.0" encoding="utf-8"?>
2611 <early_vms>
2612 <early_vm>
2613 <name>vm_demo_invalid_cid</name>
2614 <cid>{cid}</cid>
2615 <path>/system/bin/vm_demo_invalid_cid</path>
2616 </early_vm>
2617 </early_vms>
2618 "#
2619 ),
2620 )?;
2621
2622 let early_vms = get_early_vms_in_path(&xml_path)?;
2623 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2624 }
2625
2626 Ok(())
2627 }
2628
2629 #[test]
2630 fn test_duplicated_early_vms() -> Result<()> {
2631 let tmp_dir = tempfile::TempDir::new()?;
2632 let tmp_dir_path = tmp_dir.path().to_owned();
2633 let xml_path = tmp_dir_path.join("early_vms.xml");
2634
2635 std::fs::write(
2636 &xml_path,
2637 br#"<?xml version="1.0" encoding="utf-8"?>
2638 <early_vms>
2639 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002640 <name>vm_demo_duplicated_name</name>
2641 <cid>456</cid>
2642 <path>/system/bin/vm_demo_duplicated_name_1</path>
2643 </early_vm>
2644 <early_vm>
2645 <name>vm_demo_duplicated_name</name>
2646 <cid>789</cid>
2647 <path>/system/bin/vm_demo_duplicated_name_2</path>
2648 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002649 </early_vms>
2650 "#,
2651 )?;
2652
2653 let cid_range = 100..1000;
2654
Inseob Kim7e1877b2024-11-07 17:28:56 +09002655 let early_vms = get_early_vms_in_path(&xml_path)?;
2656 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002657
Inseob Kim7e1877b2024-11-07 17:28:56 +09002658 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002659
2660 Ok(())
2661 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002662}