blob: 9d985ad1e4532363930795f8f5c0c184421cbb45 [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;
Elie Kheirallah29d72912024-08-07 20:17:26 +000020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090021use crate::debug_config::DebugConfig;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Jeongik Chac181be72024-03-27 00:18:30 +090035 InputDevice::InputDevice,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010036 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000037 IVirtualMachineCallback::IVirtualMachineCallback,
38 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090039 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090041 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010044 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090047};
Inseob Kimecde8c02024-09-03 13:11:08 +090048use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090050use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000051 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052};
Shikha Panware45e9422024-02-28 21:18:10 +000053use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
55use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
56 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
57 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
58 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
59 SessionInitiationInfo::SessionInitiationInfo,
60};
Alan Stokes25f69362023-03-06 16:51:54 +000061use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090062use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090063use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010064use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000065 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
66 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090067 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000068};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000069use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000071use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090072use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090073use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000074use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000075use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090076use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090077use serde::Deserialize;
Inseob Kim6ef80972023-07-20 17:23:36 +090078use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000079use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000080use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090081use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090082use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000083use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090084use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000085use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090086use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090087use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000088use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010090use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090091use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010092use vmconfig::{VmConfig, get_debug_level};
David Brazdilafc9a9e2023-01-12 16:08:10 +000093use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090094use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000095
David Brazdil41d1a872022-10-05 14:44:19 +010096/// The unique ID of a VM used (together with a port number) for vsock communication.
97pub type Cid = u32;
98
David Brazdil4b4c5102022-12-19 22:56:20 +000099pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
100
Jooyung Han95884632021-07-06 22:27:54 +0900101/// The size of zero.img.
102/// Gaps in composite disk images are filled with a shared zero.img.
103const ZERO_FILLER_SIZE: u64 = 4096;
104
David Brazdilf50c7a62023-04-19 14:22:42 +0000105/// Magic string for the instance image
106const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
107
108/// Version of the instance image format
109const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
110
Alan Stokes0d1ef782022-09-27 13:46:35 +0100111const MICRODROID_OS_NAME: &str = "microdroid";
112
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000113const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000114 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000115
David Brazdilf50c7a62023-04-19 14:22:42 +0000116const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
117
118/// crosvm requires all partitions to be a multiple of 4KiB.
119const PARTITION_GRANULARITY_BYTES: u64 = 4096;
120
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000121const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
122
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100123pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
124 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900125 if cfg!(early) {
126 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
127 } else {
128 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
129 .expect("Could not connect to VirtualizationServiceInternal")
130 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100131 });
132static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
133 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000134
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000135fn create_or_update_idsig_file(
136 input_fd: &ParcelFileDescriptor,
137 idsig_fd: &ParcelFileDescriptor,
138) -> Result<()> {
139 let mut input = clone_file(input_fd)?;
140 let metadata = input.metadata().context("failed to get input metadata")?;
141 if !metadata.is_file() {
142 bail!("input is not a regular file");
143 }
Alan Stokes25f69362023-03-06 16:51:54 +0000144 let mut sig =
145 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
146 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000147
148 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900149
150 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
151 // if the idsig file already has the same APK digest.
152 if output.metadata()?.len() > 0 {
153 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
154 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
155 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
156 return Ok(());
157 }
158 }
159 // if we fail to read v4signature from output, that's fine. User can pass a random file.
160 // We will anyway overwrite the file to the v4signature generated from input_fd.
161 }
162
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000163 output
164 .seek(SeekFrom::Start(0))
165 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000166 output.set_len(0).context("failed to set_len on the idsig output")?;
167 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000168 Ok(())
169}
170
Alan Stokes25f69362023-03-06 16:51:54 +0000171fn get_current_sdk() -> Result<u32> {
172 let current_sdk = system_properties::read("ro.build.version.sdk")?;
173 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
174 current_sdk.parse().context("Malformed SDK version")
175}
176
David Brazdil4b4c5102022-12-19 22:56:20 +0000177pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
178 for dir_entry in read_dir(path)? {
179 remove_file(dir_entry?.path())?;
180 }
181 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100182}
183
David Brazdil528e0472022-10-10 15:06:02 +0100184/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000185#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000186pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900187 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000188}
189
Shikha Panward8e35422021-10-11 13:51:27 +0000190impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000191 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000192 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
193 let state = &mut *self.state.lock().unwrap();
194 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000195 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000196 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000197 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
198 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000199 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000201 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
203 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000208 .or(Err(StatusCode::UNKNOWN_ERROR))?;
209 }
210 Ok(())
211 }
212}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000213impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000214 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
215 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000216 ///
217 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000218 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000219 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000220 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900221 console_out_fd: Option<&ParcelFileDescriptor>,
222 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000223 log_fd: Option<&ParcelFileDescriptor>,
224 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000225 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900226 let ret = self.create_vm_internal(
227 config,
228 console_out_fd,
229 console_in_fd,
230 log_fd,
231 &mut is_protected,
232 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000233 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000234 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000235 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000236
Shikha Panwar61a74b52024-02-16 13:17:01 +0000237 /// Allocate a new instance_id to the VM
238 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000239 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000240 GLOBAL_SERVICE.allocateInstanceId()
241 }
242
Andrew Walbrandff3b942021-06-09 15:20:36 +0000243 /// Initialise an empty partition image of the given size to be used as a writable partition.
244 fn initializeWritablePartition(
245 &self,
246 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000247 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900248 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000249 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900250 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900251 let size_bytes = size_bytes
252 .try_into()
253 .with_context(|| format!("Invalid size: {}", size_bytes))
254 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000255 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000256 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000257 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000258 image
259 .seek(SeekFrom::Start(0))
260 .context("failed to move cursor to start")
261 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900262 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700263 // Set the file length. In most filesystems, this will not allocate any physical disk
264 // space, it will only change the logical size.
265 image
266 .set_len(size_bytes)
267 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900268 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000269
270 match partition_type {
271 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700272 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
273 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000274 _ => Err(Error::new(
275 ErrorKind::Unsupported,
276 format!("Unsupported partition type {:?}", partition_type),
277 )),
278 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900279 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
280 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000281
282 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000283 }
284
Jiyong Park0a248432021-08-20 23:32:39 +0900285 /// Creates or update the idsig file by digesting the input APK file.
286 fn createOrUpdateIdsigFile(
287 &self,
288 input_fd: &ParcelFileDescriptor,
289 idsig_fd: &ParcelFileDescriptor,
290 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900291 check_manage_access()?;
292
Jiyong Park2227eaa2023-08-04 11:59:18 +0900293 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900294 Ok(())
295 }
296
Andrew Walbran320b5602021-03-04 16:11:12 +0000297 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
298 /// and as such is only permitted from the shell user.
299 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000300 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000301 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000302 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900303
304 /// Get a list of assignable device types.
305 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
306 // Delegate to the global service, including checking the permission.
307 GLOBAL_SERVICE.getAssignableDevices()
308 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100309
Inseob Kim46257382024-01-03 15:41:22 +0900310 /// Get a list of supported OSes.
311 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
312 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
313 }
314
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100315 /// Returns whether given feature is enabled
316 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
317 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000318 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100319 }
Alice Wange64dd182024-01-17 15:57:55 +0000320
321 fn enableTestAttestation(&self) -> binder::Result<()> {
322 GLOBAL_SERVICE.enableTestAttestation()
323 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000324
325 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
326 check_manage_access()?;
327 GLOBAL_SERVICE.isRemoteAttestationSupported()
328 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000329
330 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
331 // The response is specific to Microdroid. Updatable VMs are only possible if device
332 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
333 // this, however other guest OSes may do things differently.
334 check_manage_access()?;
335 Ok(is_secretkeeper_supported())
336 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000337
Shikha Panwar07d701c2024-03-28 14:43:52 +0000338 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
339 check_manage_access()?;
340 GLOBAL_SERVICE.removeVmInstance(instance_id)
341 }
342
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000343 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
344 check_manage_access()?;
345 GLOBAL_SERVICE.claimVmInstance(instance_id)
346 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000347}
348
Inseob Kimecde8c02024-09-03 13:11:08 +0900349/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
350#[derive(Debug, Default)]
351struct EarlyVmContext {
352 /// The unique CID assigned to the VM for vsock communication.
353 cid: Cid,
354 /// Temporary directory for this VM instance.
355 temp_dir: PathBuf,
356}
357
358impl EarlyVmContext {
359 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
360 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
361 // should trust clients, e.g. they won't run two VMs at the same time
362 let _ = remove_dir_all(&temp_dir);
363 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
364
365 Ok(Self { cid, temp_dir })
366 }
367}
368
369impl Interface for EarlyVmContext {}
370
371impl Drop for EarlyVmContext {
372 fn drop(&mut self) {
373 if let Err(e) = remove_dir_all(&self.temp_dir) {
374 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
375 }
376 }
377}
378
379impl IGlobalVmContext for EarlyVmContext {
380 fn getCid(&self) -> binder::Result<i32> {
381 Ok(self.cid as i32)
382 }
383
384 fn getTemporaryDirectory(&self) -> binder::Result<String> {
385 Ok(self.temp_dir.to_string_lossy().to_string())
386 }
387
388 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
389 Err(Status::new_exception_str(
390 ExceptionCode::UNSUPPORTED_OPERATION,
391 Some("Early VM doesn't support setting host console name"),
392 ))
393 }
394}
395
396fn find_partition(path: &Path) -> binder::Result<String> {
397 match path.components().nth(1) {
398 Some(std::path::Component::Normal(partition)) => {
399 Ok(partition.to_string_lossy().into_owned())
400 }
401 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
402 .or_service_specific_exception(-1),
403 }
404}
405
Jiyong Park8611a6c2021-07-09 18:17:44 +0900406impl VirtualizationService {
407 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000408 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900409 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000410
Inseob Kimecde8c02024-09-03 13:11:08 +0900411 fn create_early_vm_context(
412 &self,
413 config: &VirtualMachineConfig,
414 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
415 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
416 let link = fs::read_link(&calling_exe_path)
417 .context(format!("can't read_link '{calling_exe_path}'"))
418 .or_service_specific_exception(-1)?;
419 let partition = find_partition(&link)?;
420
421 let name = match config {
422 VirtualMachineConfig::RawConfig(config) => &config.name,
423 VirtualMachineConfig::AppConfig(config) => &config.name,
424 };
425 let early_vm =
426 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
427 if Path::new(&early_vm.path) != link {
428 return Err(anyhow!(
429 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
430 &early_vm.path,
431 link.display()
432 ))
433 .or_service_specific_exception(-1);
434 }
435
436 let cid = early_vm.cid as Cid;
437 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
438
439 let context = EarlyVmContext::new(cid, temp_dir.clone())
440 .context(format!("Can't create early vm contexts for {cid}"))
441 .or_service_specific_exception(-1)?;
442 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
443
444 // Start VM service listening for connections from the new CID on port=CID.
445 let port = cid;
446 let vm_server = RpcServer::new_vsock(service, cid, port)
447 .context(format!("Could not start RpcServer on port {port}"))
448 .or_service_specific_exception(-1)?;
449 vm_server.start();
450 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
451 }
452
David Brazdil209074a2023-01-12 16:44:51 +0000453 fn create_vm_context(
454 &self,
455 requester_debug_pid: pid_t,
456 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000457 const NUM_ATTEMPTS: usize = 5;
458
459 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000460 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000461 let cid = vm_context.getCid()? as Cid;
462 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000463 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
464
465 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000466 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000467 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000468 Ok(vm_server) => {
469 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000470 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000471 }
472 Err(err) => {
473 warn!("Could not start RpcServer on port {}: {}", port, err);
474 }
475 }
476 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900477 Err(anyhow!("Too many attempts to create VM context failed"))
478 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000479 }
480
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000481 fn create_vm_internal(
482 &self,
483 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900484 console_out_fd: Option<&ParcelFileDescriptor>,
485 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000486 log_fd: Option<&ParcelFileDescriptor>,
487 is_protected: &mut bool,
488 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000489 let requester_uid = get_calling_uid();
490 let requester_debug_pid = get_calling_pid();
491
Nikita Ioffe631717e2023-09-05 13:38:07 +0100492 check_config_features(config)?;
493
Inseob Kimecde8c02024-09-03 13:11:08 +0900494 if cfg!(early) {
495 check_config_allowed_for_early_vms(config)?;
496 }
497
David Brazdil209074a2023-01-12 16:44:51 +0000498 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900499 let (vm_context, cid, temporary_directory) = if cfg!(early) {
500 self.create_early_vm_context(config)?
501 } else {
502 self.create_vm_context(requester_debug_pid)?
503 };
Inseob Kim1119d702022-05-02 18:01:58 +0900504
Alan Stokesfda70842023-12-20 17:50:14 +0000505 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100506 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900507 }
508
Nikita Ioffe5776f082023-02-10 21:38:26 +0000509 let gdb_port = extract_gdb_port(config);
510
511 // Additional permission checks if caller request gdb.
512 if gdb_port.is_some() {
513 check_gdb_allowed(config)?;
514 }
515
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000516 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900517
Jaewan Kimf3143242024-03-15 06:56:31 +0000518 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000519 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900520 Some(prepare_ramdump_file(&temporary_directory)?)
521 } else {
522 None
523 };
524
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000525 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900526 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100527 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900528 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100529 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000530
531 // Counter to generate unique IDs for temporary image files.
532 let mut next_temporary_image_id = 0;
533 // Files which are referred to from composite images. These must be mapped to the crosvm
534 // child process, and not closed before it is started.
535 let mut indirect_files = vec![];
536
Alan Stokes7bc146c2022-10-20 17:10:32 +0100537 let (is_app_config, config) = match config {
538 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
539 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900540 let config = load_app_config(config, &debug_config, &temporary_directory)
541 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900542 *is_protected = config.protectedVm;
543 let message = format!("Failed to load app config: {:?}", e);
544 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900545 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900546 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100547 (true, BorrowedOrOwned::Owned(config))
548 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000549 };
550 let config = config.as_ref();
551 *is_protected = config.protectedVm;
552
553 // Check if partition images are labeled incorrectly. This is to prevent random images
554 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100555 // being loaded in a pVM. This applies to everything but the instance image in the raw
556 // config, and everything but the non-executable, generated partitions in the app
557 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000558 config
559 .disks
560 .iter()
561 .flat_map(|disk| disk.partitions.iter())
562 .filter(|partition| {
563 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100564 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000565 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000566 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000567 }
568 })
569 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900570 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000571
Inseob Kimff48a7c2024-02-26 22:07:21 +0900572 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
573 // have unstable interfaces.
574 // TODO(b/316431494): remove once Treble interfaces are stabilized.
575 check_partitions_for_files(config).or_service_specific_exception(-1)?;
576
Alan Stokes185fe112023-01-10 16:20:55 +0000577 let kernel = maybe_clone_file(&config.kernel)?;
578 let initrd = maybe_clone_file(&config.initrd)?;
579
Alan Stokes185fe112023-01-10 16:20:55 +0000580 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000581 // In a protected VM, we require custom kernels to come from a trusted source
582 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900583 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000584 // Fail fast with a meaningful error message in case device doesn't support pVMs.
585 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000586 }
587
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000588 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900589 write_zero_filler(&zero_filler_path)
590 .context("Failed to make composite image")
591 .with_log()
592 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000593
594 // Assemble disk images if needed.
595 let disks = config
596 .disks
597 .iter()
598 .map(|disk| {
599 assemble_disk_image(
600 disk,
601 &zero_filler_path,
602 &temporary_directory,
603 &mut next_temporary_image_id,
604 &mut indirect_files,
605 )
606 })
607 .collect::<Result<Vec<DiskFile>, _>>()?;
608
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000609 let (cpus, host_cpu_topology) = match config.cpuTopology {
610 CpuTopology::MATCH_HOST => (None, true),
611 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
612 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900613 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
614 .with_log()
615 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000616 }
617 };
618
David Brazdil2dfefd12023-11-17 14:07:36 +0000619 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900620 let mut set = HashSet::new();
621 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900622 let path = canonicalize(device)
623 .with_context(|| format!("can't canonicalize {device}"))
624 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900625 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900626 return Err(anyhow!("duplicated device {device}"))
627 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900628 }
629 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000630 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000631 let dtbo_file = File::from(
632 GLOBAL_SERVICE
633 .getDtboFile()?
634 .as_ref()
635 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900636 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000637 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
638 );
639 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900640 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000641 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900642 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900643 let display_config = if cfg!(paravirtualized_devices) {
644 config
645 .displayConfig
646 .as_ref()
647 .map(DisplayConfig::new)
648 .transpose()
649 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
650 } else {
651 None
652 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700653 let gpu_config = if cfg!(paravirtualized_devices) {
654 config
655 .gpuConfig
656 .as_ref()
657 .map(GpuConfig::new)
658 .transpose()
659 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
660 } else {
661 None
662 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900663
Jeongik Chac181be72024-03-27 00:18:30 +0900664 let input_device_options = if cfg!(paravirtualized_devices) {
665 config
666 .inputDevices
667 .iter()
668 .map(to_input_device_option_from)
669 .collect::<Result<Vec<InputDeviceOption>, _>>()
670 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
671 } else {
672 vec![]
673 };
674
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900675 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900676 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900677 if *is_protected {
678 return Err(anyhow!("Network feature is not supported for pVM yet"))
679 .with_log()
680 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
681 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900682 Some(File::from(
683 GLOBAL_SERVICE
684 .createTapInterface(&get_this_pid().to_string())?
685 .as_ref()
686 .try_clone()
687 .context("Failed to get TAP interface from ParcelFileDescriptor")
688 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
689 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900690 } else {
691 None
692 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800693
694 let audio_config = if cfg!(paravirtualized_devices) {
695 config.audioConfig.as_ref().map(AudioConfig::new)
696 } else {
697 None
698 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900699
Elie Kheirallah29d72912024-08-07 20:17:26 +0000700 let usb_config = config
701 .usbConfig
702 .as_ref()
703 .map(UsbConfig::new)
704 .unwrap_or(Ok(UsbConfig { controller: false }))
705 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
706
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000707 // Actually start the VM.
708 let crosvm_config = CrosvmConfig {
709 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000710 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000711 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000712 kernel,
713 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000714 disks,
715 params: config.params.to_owned(),
716 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900717 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700718 memory_mib: config
719 .memoryMib
720 .try_into()
721 .ok()
722 .and_then(NonZeroU32::new)
723 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000724 cpus,
725 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900726 console_out_fd,
727 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000728 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900729 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000730 indirect_files,
731 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900732 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000733 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900734 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000735 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000736 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900737 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900738 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000739 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900740 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800741 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000742 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700743 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800744 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900745 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000746 usb_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000747 };
748 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100749 VmInstance::new(
750 crosvm_config,
751 temporary_directory,
752 requester_uid,
753 requester_debug_pid,
754 vm_context,
755 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900756 .with_context(|| format!("Failed to create VM with config {:?}", config))
757 .with_log()
758 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000759 );
760 state.add_vm(Arc::downgrade(&instance));
761 Ok(VirtualMachine::create(instance))
762 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900763}
764
Alan Stokesfda70842023-12-20 17:50:14 +0000765/// Returns whether a VM config represents a "custom" virtual machine, which requires the
766/// USE_CUSTOM_VIRTUAL_MACHINE.
767fn is_custom_config(config: &VirtualMachineConfig) -> bool {
768 match config {
769 // Any raw (non-Microdroid) VM is considered custom.
770 VirtualMachineConfig::RawConfig(_) => true,
771 VirtualMachineConfig::AppConfig(config) => {
772 // Some features are reserved for platform apps only, even when using
773 // VirtualMachineAppConfig. Almost all of these features are grouped in the
774 // CustomConfig struct:
775 // - controlling CPUs;
776 // - gdbPort is set, meaning that crosvm will start a gdb server;
777 // - using anything other than the default kernel;
778 // - specifying devices to be assigned.
779 if config.customConfig.is_some() {
780 true
781 } else {
782 // Additional custom features not included in CustomConfig:
783 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000784 // - specifying extra APKs;
785 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900786 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000787 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900788 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
789 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000790 }
791 }
792 }
793}
794
Seungjae Yoo14e60182024-02-21 13:28:31 +0900795fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
796 let VirtualMachineConfig::AppConfig(config) = config else {
797 return Ok(None);
798 };
799 let Some(custom_config) = &config.customConfig else {
800 return Ok(None);
801 };
802 let Some(file) = custom_config.vendorImage.as_ref() else {
803 return Ok(None);
804 };
805
806 let file = clone_file(file)?;
807 let size =
808 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
809 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
810 .context("Failed to get vbmeta from microdroid-vendor.img")?;
811
812 for descriptor in vbmeta.descriptors()?.iter() {
813 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
814 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
815 return Ok(Some(root_digest.as_bytes().to_vec()));
816 }
817 }
818 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
819}
820
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000821fn maybe_create_device_tree_overlay(
822 config: &VirtualMachineConfig,
823 temporary_directory: &Path,
824) -> binder::Result<Option<File>> {
825 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
826 // (e.g. instance-id)
827 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
828 let host_ref_dt = if host_ref_dt.exists()
829 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
830 {
831 Some(host_ref_dt)
832 } else {
833 warn!("VM reference DT doesn't exist in host DT");
834 None
835 };
836
837 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
838 .context("Failed to extract vendor hashtree digest")
839 .or_service_specific_exception(-1)?;
840
841 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
842 info!(
843 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
844 match the trusted digest in the pvmfw config, causing the VM to fail to start."
845 );
846 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
847 } else {
848 vec![]
849 };
850
851 let instance_id;
852 let mut untrusted_props = Vec::with_capacity(2);
853 if cfg!(llpvm_changes) {
854 instance_id = extract_instance_id(config);
855 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
856 let want_updatable = extract_want_updatable(config);
857 if want_updatable && is_secretkeeper_supported() {
858 // Let guest know that it can defer rollback protection to Secretkeeper by setting
859 // an empty property in untrusted node in DT. This enables Updatable VMs.
860 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
861 }
862 }
863
864 let device_tree_overlay = if host_ref_dt.is_some()
865 || !untrusted_props.is_empty()
866 || !trusted_props.is_empty()
867 {
868 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
869 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
870 let fdt =
871 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
872 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
873 .or_service_specific_exception(-1)?;
874 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
875 Some(File::open(dt_output).or_service_specific_exception(-1)?)
876 } else {
877 None
878 };
879 Ok(device_tree_overlay)
880}
881
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000882fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900883 let file = OpenOptions::new()
884 .create_new(true)
885 .read(true)
886 .write(true)
887 .open(zero_filler_path)
888 .with_context(|| "Failed to create zero.img")?;
889 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000890 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900891}
892
David Brazdilf50c7a62023-04-19 14:22:42 +0000893fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
894 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
895 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
896 part.flush()
897}
898
899fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
900 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
901 part.flush()
902}
903
904fn round_up(input: u64, granularity: u64) -> u64 {
905 if granularity == 0 {
906 return input;
907 }
908 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
909 let result = input.checked_add(granularity - 1).unwrap_or(input);
910 (result / granularity) * granularity
911}
912
Jeongik Chac181be72024-03-27 00:18:30 +0900913fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
914 Ok(match input_device {
915 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
916 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
917 height: u32::try_from(single_touch.height)?,
918 width: u32::try_from(single_touch.width)?,
919 name: if !single_touch.name.is_empty() {
920 Some(single_touch.name.clone())
921 } else {
922 None
923 },
924 },
925 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
926 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
927 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900928 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
929 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
930 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900931 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
932 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
933 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900934 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
935 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
936 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900937 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
938 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
939 height: u32::try_from(trackpad.height)?,
940 width: u32::try_from(trackpad.width)?,
941 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
942 },
Jeongik Cha10494912024-07-16 11:19:50 +0900943 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
944 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
945 height: u32::try_from(multi_touch.height)?,
946 width: u32::try_from(multi_touch.width)?,
947 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
948 },
Jeongik Chac181be72024-03-27 00:18:30 +0900949 })
950}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000951/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
952///
953/// This may involve assembling a composite disk from a set of partition images.
954fn assemble_disk_image(
955 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900956 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000957 temporary_directory: &Path,
958 next_temporary_image_id: &mut u64,
959 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000960) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000961 let image = if !disk.partitions.is_empty() {
962 if disk.image.is_some() {
963 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900964 return Err(anyhow!("DiskImage contains both image and partitions"))
965 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000966 }
967
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000968 let composite_image_filenames =
969 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
970 let (image, partition_files) = make_composite_image(
971 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900972 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000973 &composite_image_filenames.composite,
974 &composite_image_filenames.header,
975 &composite_image_filenames.footer,
976 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900977 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
978 .with_log()
979 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000980
981 // Pass the file descriptors for the various partition files to crosvm when it
982 // is run.
983 indirect_files.extend(partition_files);
984
985 image
986 } else if let Some(image) = &disk.image {
987 clone_file(image)?
988 } else {
989 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900990 return Err(anyhow!("DiskImage didn't contain image or partitions."))
991 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000992 };
993
994 Ok(DiskFile { image, writable: disk.writable })
995}
996
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100997fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
998 if let Some(ref mut params) = vm_config.params {
999 params.push(' ');
1000 params.push_str(param)
1001 } else {
1002 vm_config.params = Some(param.to_owned())
1003 }
1004}
1005
Inseob Kim46257382024-01-03 15:41:22 +09001006fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1007 if config.extension()?.to_str()? != "json" {
1008 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001009 }
Inseob Kim46257382024-01-03 15:41:22 +09001010
1011 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1012}
1013
1014fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1015 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1016 let os_names =
1017 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1018
1019 Ok(os_names)
1020}
1021
1022fn get_supported_os_names() -> Result<HashSet<String>> {
1023 if !cfg!(vendor_modules) {
1024 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1025 }
1026
1027 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1028}
1029
1030fn is_valid_os(os_name: &str) -> bool {
1031 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001032}
1033
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001034fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1035 if !cfg!(vendor_modules) {
1036 return false;
1037 }
1038 match config {
1039 VirtualMachineConfig::RawConfig(_) => false,
1040 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1041 }
1042}
1043
Jooyung Han21e9b922021-06-26 04:14:16 +09001044fn load_app_config(
1045 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001046 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001047 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001048) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001049 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1050 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001051 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001052
Shikha Panwar22e70452022-10-10 18:32:55 +00001053 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1054 Some(clone_file(file)?)
1055 } else {
1056 None
1057 };
1058
Alan Stokesfda70842023-12-20 17:50:14 +00001059 let vm_payload_config;
1060 let extra_apk_files: Vec<_>;
1061 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001062 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001063 vm_payload_config =
1064 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1065 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1066 extra_apk_files = vm_payload_config
1067 .extra_apks
1068 .iter()
1069 .enumerate()
1070 .map(|(i, apk)| {
1071 File::open(PathBuf::from(&apk.path))
1072 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1073 })
1074 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001075 }
Alan Stokesfda70842023-12-20 17:50:14 +00001076 Payload::PayloadConfig(payload_config) => {
1077 vm_payload_config = create_vm_payload_config(payload_config)?;
1078 extra_apk_files =
1079 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1080 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001081 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001082
Inseob Kim89b24592024-02-23 18:59:43 +09001083 let payload_config_os = vm_payload_config.os.name.as_str();
1084 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1085 bail!("'os' in payload config is deprecated");
1086 }
1087
Inseob Kim172f9eb2023-11-06 17:02:08 +09001088 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001089 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001090 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001091 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001092 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001093
1094 // It is safe to construct a filename based on the os_name because we've already checked that it
1095 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001096 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1097 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001098 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001099
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001100 if let Some(custom_config) = &config.customConfig {
1101 if let Some(file) = custom_config.customKernelImage.as_ref() {
1102 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1103 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001104 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001105
1106 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001107 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Matt Gilbrideef4c6ec2024-08-30 16:29:42 +00001108 if !cfg!(tpu_assignable_device) {
1109 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config);
1110 }
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001111 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001112
Chris Wailes6177c662024-05-09 14:37:44 -07001113 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001114 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001115
1116 for param in custom_config.extraKernelCmdlineParams.iter() {
1117 append_kernel_param(param, &mut vm_config);
1118 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001119 }
1120
Andrew Walbrancc045902021-07-27 16:06:17 +00001121 if config.memoryMib > 0 {
1122 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001123 }
1124
Chris Wailes6177c662024-05-09 14:37:44 -07001125 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001126 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001127 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001128 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001129 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001130
Shikha Panwar22e70452022-10-10 18:32:55 +00001131 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001132 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001133
1134 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1135 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001136 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001137 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001138 temporary_directory,
1139 apk_file,
1140 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001141 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001142 &vm_payload_config,
1143 &mut vm_config,
1144 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001145
Andrew Walbrancc0db522021-07-12 17:03:42 +00001146 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001147}
1148
Inseob Kimff48a7c2024-02-26 22:07:21 +09001149fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1150 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1151 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1152
1153 // microdroid vendor image is OK
1154 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1155 {
1156 return Ok(());
1157 }
1158
1159 if link.starts_with("/vendor") || link.starts_with("/odm") {
1160 bail!("vendor or odm file {} can't be used for VM", link.display());
1161 }
1162
1163 Ok(())
1164}
1165
1166fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1167 config
1168 .disks
1169 .iter()
1170 .flat_map(|disk| disk.partitions.iter())
1171 .filter_map(|partition| partition.image.as_ref())
1172 .try_for_each(check_partition_for_file)?;
1173
1174 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1175 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1176 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1177
1178 Ok(())
1179}
1180
Alan Stokes0d1ef782022-09-27 13:46:35 +01001181fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1182 let mut apk_zip = ZipArchive::new(apk_file)?;
1183 let config_file = apk_zip.by_name(config_path)?;
1184 Ok(serde_json::from_reader(config_file)?)
1185}
1186
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001187fn create_vm_payload_config(
1188 payload_config: &VirtualMachinePayloadConfig,
1189) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001190 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1191 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1192 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001193
1194 let payload_binary_name = &payload_config.payloadBinaryName;
1195 if payload_binary_name.contains('/') {
1196 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1197 }
1198
1199 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001200
1201 // The VM only cares about how many there are, these names are actually ignored.
1202 let extra_apk_count = payload_config.extraApks.len();
1203 let extra_apks =
1204 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1205
Inseob Kim89b24592024-02-23 18:59:43 +09001206 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001207}
1208
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001209/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001210fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001211 temporary_directory: &Path,
1212 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001213) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001214 let id = *next_temporary_image_id;
1215 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001216 CompositeImageFilenames {
1217 composite: temporary_directory.join(format!("composite-{}.img", id)),
1218 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1219 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1220 }
1221}
1222
1223/// Filenames for a composite disk image, including header and footer partitions.
1224#[derive(Clone, Debug, Eq, PartialEq)]
1225struct CompositeImageFilenames {
1226 /// The composite disk image itself.
1227 composite: PathBuf,
1228 /// The header partition image.
1229 header: PathBuf,
1230 /// The footer partition image.
1231 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001232}
1233
Jiyong Park753553b2021-07-12 21:21:09 +09001234/// Checks whether the caller has a specific permission
1235fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001236 if cfg!(early) {
1237 // Skip permission check for early VMs, in favor of SELinux
1238 return Ok(());
1239 }
David Brazdil1f530702022-10-03 12:18:10 +01001240 let calling_pid = get_calling_pid();
1241 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001242 // Root can do anything
1243 if calling_uid == 0 {
1244 return Ok(());
1245 }
1246 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001247 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001248 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001249 Ok(())
1250 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001251 Err(anyhow!("does not have the {} permission", perm))
1252 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001253 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001254}
1255
Jiyong Park753553b2021-07-12 21:21:09 +09001256/// Check whether the caller of the current Binder method is allowed to manage VMs
1257fn check_manage_access() -> binder::Result<()> {
1258 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1259}
1260
Inseob Kim1119d702022-05-02 18:01:58 +09001261/// Check whether the caller of the current Binder method is allowed to create custom VMs
1262fn check_use_custom_virtual_machine() -> binder::Result<()> {
1263 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1264}
1265
Alan Stokes185fe112023-01-10 16:20:55 +00001266/// Return whether a partition is exempt from selinux label checks, because we know that it does
1267/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001268fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001269 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001270 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001271 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001272 || label == "microdroid-apk-idsig"
1273 || label == "payload-metadata"
1274 || label.starts_with("extra-idsig-")
1275}
1276
Alice Wangc206b9b2023-08-28 14:13:51 +00001277/// Returns whether a partition with the given label is safe for a raw config VM.
1278fn is_safe_raw_partition(label: &str) -> bool {
1279 label == "vm-instance"
1280}
1281
Alan Stokes185fe112023-01-10 16:20:55 +00001282/// Check that a file SELinux label is acceptable.
1283///
1284/// 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 +09001285/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001286///
1287/// Note that sepolicy must also grant read access for these types to both virtualization
1288/// service and crosvm.
1289///
1290/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1291/// user devices (W^X).
1292fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1293 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001294 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001295 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001296 | "staging_data_file" // updated/staged APEX images
1297 | "system_file" // immutable dm-verity protected partition
1298 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001299 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001300 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001301 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001302 }
1303}
1304
Alan Stokes185fe112023-01-10 16:20:55 +00001305fn check_label_for_partition(partition: &Partition) -> Result<()> {
1306 let file = partition.image.as_ref().unwrap().as_ref();
1307 check_label_is_allowed(&getfilecon(file)?)
1308 .with_context(|| format!("Partition {} invalid", &partition.label))
1309}
1310
1311fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1312 if let Some(f) = kernel {
1313 check_label_for_file(f, "kernel")?;
1314 }
1315 if let Some(f) = initrd {
1316 check_label_for_file(f, "initrd")?;
1317 }
1318 Ok(())
1319}
1320fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1321 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1322}
1323
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001324/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1325#[derive(Debug)]
1326struct VirtualMachine {
1327 instance: Arc<VmInstance>,
1328}
1329
1330impl VirtualMachine {
1331 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001332 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001333 }
1334}
1335
1336impl Interface for VirtualMachine {}
1337
1338impl IVirtualMachine for VirtualMachine {
1339 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001340 // Don't check permission. The owner of the VM might have passed this binder object to
1341 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001342 Ok(self.instance.cid as i32)
1343 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001344
Andrew Walbran6b650662021-09-07 13:13:23 +00001345 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001346 // Don't check permission. The owner of the VM might have passed this binder object to
1347 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001348 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001349 }
1350
1351 fn registerCallback(
1352 &self,
1353 callback: &Strong<dyn IVirtualMachineCallback>,
1354 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001355 // Don't check permission. The owner of the VM might have passed this binder object to
1356 // others.
1357 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001358 // TODO: Should this give an error if the VM is already dead?
1359 self.instance.callbacks.add(callback.clone());
1360 Ok(())
1361 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001362
Andrew Walbranf8d94112021-09-07 11:45:36 +00001363 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001364 self.instance
1365 .start()
1366 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1367 .with_log()
1368 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001369 }
1370
Inseob Kima446f802022-07-11 19:46:37 +09001371 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001372 self.instance
1373 .kill()
1374 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1375 .with_log()
1376 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001377 }
1378
Keir Fraser48221ba2024-07-12 14:05:02 +00001379 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1380 let balloon = self
1381 .instance
1382 .get_memory_balloon()
1383 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1384 .with_log()
1385 .or_service_specific_exception(-1)?;
1386 Ok(balloon.try_into().unwrap())
1387 }
1388
1389 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001390 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001391 .set_memory_balloon(num_bytes.try_into().unwrap())
1392 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001393 .with_log()
1394 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001395 }
1396
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001397 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001398 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001399 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001400 }
Alan Stokes10c47672022-12-13 17:17:08 +00001401 let port = port as u32;
1402 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001403 return Err(anyhow!("Can't connect to privileged port {port}"))
1404 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001405 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001406 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1407 .context("Failed to connect")
1408 .or_service_specific_exception(-1)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001409 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001410 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001411
1412 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1413 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1414 }
Jiyong Park23b67392024-07-04 13:51:42 +09001415
1416 fn suspend(&self) -> binder::Result<()> {
1417 self.instance
1418 .suspend()
1419 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1420 .with_log()
1421 .or_service_specific_exception(-1)
1422 }
1423
1424 fn resume(&self) -> binder::Result<()> {
1425 self.instance
1426 .resume()
1427 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1428 .with_log()
1429 .or_service_specific_exception(-1)
1430 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001431}
1432
1433impl Drop for VirtualMachine {
1434 fn drop(&mut self) {
1435 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001436 if let Err(e) = self.instance.kill() {
1437 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1438 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001439 }
1440}
1441
1442/// A set of Binders to be called back in response to various events on the VM, such as when it
1443/// dies.
1444#[derive(Debug, Default)]
1445pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1446
1447impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001448 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001449 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001450 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001451 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001452 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001453 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001454 }
1455 }
1456 }
1457
Inseob Kim14cb8692021-08-31 21:50:39 +09001458 /// Call all registered callbacks to notify that the payload is ready to serve.
1459 pub fn notify_payload_ready(&self, cid: Cid) {
1460 let callbacks = &*self.0.lock().unwrap();
1461 for callback in callbacks {
1462 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001463 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001464 }
1465 }
1466 }
1467
Inseob Kim2444af92021-08-31 01:22:50 +09001468 /// Call all registered callbacks to notify that the payload has finished.
1469 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1470 let callbacks = &*self.0.lock().unwrap();
1471 for callback in callbacks {
1472 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001473 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001474 }
1475 }
1476 }
1477
Jooyung Handd0a1732021-11-23 15:26:20 +09001478 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001479 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001480 let callbacks = &*self.0.lock().unwrap();
1481 for callback in callbacks {
1482 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001483 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001484 }
1485 }
1486 }
1487
Andrew Walbrandae07162021-03-12 17:05:20 +00001488 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001489 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001490 let callbacks = &*self.0.lock().unwrap();
1491 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001492 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001493 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001494 }
1495 }
1496 }
1497
1498 /// Add a new callback to the set.
1499 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1500 self.0.lock().unwrap().push(callback);
1501 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001502}
1503
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001504/// The mutable state of the VirtualizationService. There should only be one instance of this
1505/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001506#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001507struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001508 /// The VMs which have been started. When VMs are started a weak reference is added to this
1509 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1510 /// the Binder client are dropped the weak reference here will become invalid, and will be
1511 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001512 vms: Vec<Weak<VmInstance>>,
1513}
1514
1515impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001516 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001517 fn vms(&self) -> Vec<Arc<VmInstance>> {
1518 // Attempt to upgrade the weak pointers to strong pointers.
1519 self.vms.iter().filter_map(Weak::upgrade).collect()
1520 }
1521
1522 /// Add a new VM to the list.
1523 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1524 // Garbage collect any entries from the stored list which no longer exist.
1525 self.vms.retain(|vm| vm.strong_count() > 0);
1526
1527 // Actually add the new VM.
1528 self.vms.push(vm);
1529 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001530
Jiyong Park8611a6c2021-07-09 18:17:44 +09001531 /// Get a VM that corresponds to the given cid
1532 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1533 self.vms().into_iter().find(|vm| vm.cid == cid)
1534 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001535}
1536
Andrew Walbran6b650662021-09-07 13:13:23 +00001537/// Gets the `VirtualMachineState` of the given `VmInstance`.
1538fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001539 match &*instance.vm_state.lock().unwrap() {
1540 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1541 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001542 PayloadState::Starting => VirtualMachineState::STARTING,
1543 PayloadState::Started => VirtualMachineState::STARTED,
1544 PayloadState::Ready => VirtualMachineState::READY,
1545 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001546 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001547 },
1548 VmState::Dead => VirtualMachineState::DEAD,
1549 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001550 }
1551}
1552
David Brazdilf50c7a62023-04-19 14:22:42 +00001553/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001554pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1555 file.as_ref()
1556 .try_clone()
1557 .context("Failed to clone File from ParcelFileDescriptor")
1558 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001559 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001560}
1561
Andrew Walbrand3a84182021-09-07 14:48:52 +00001562/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001563fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001564 file.as_ref().map(clone_file).transpose()
1565}
1566
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001567/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001568fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1569 // SAFETY: ownership is transferred from stream to f
1570 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1571 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001572}
1573
Jiyong Parkdcf17412022-02-08 15:07:23 +09001574/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001575fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1576 VersionReq::parse(s)
1577 .with_context(|| format!("Invalid platform version requirement {}", s))
1578 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001579}
1580
Jiyong Parked180932023-02-24 19:55:41 +09001581/// Create the empty ramdump file
1582fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1583 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1584 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1585 // owner) for readout.
1586 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001587 let ramdump = File::create(ramdump_path)
1588 .context("Failed to prepare ramdump file")
1589 .with_log()
1590 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001591 Ok(ramdump)
1592}
1593
Nikita Ioffe5776f082023-02-10 21:38:26 +00001594fn is_protected(config: &VirtualMachineConfig) -> bool {
1595 match config {
1596 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1597 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1598 }
1599}
1600
1601fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1602 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001603 return Err(anyhow!("Can't use gdb with protected VMs"))
1604 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001605 }
1606
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001607 if get_debug_level(config) == Some(DebugLevel::NONE) {
1608 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1609 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001610 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001611
1612 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001613}
1614
Shikha Panwar61a74b52024-02-16 13:17:01 +00001615fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1616 match config {
1617 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1618 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1619 }
1620}
1621
Alan Stokesc96b35e2024-05-03 13:21:20 +01001622fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1623 match config {
1624 VirtualMachineConfig::RawConfig(_) => true,
1625 VirtualMachineConfig::AppConfig(config) => {
1626 let Some(custom) = &config.customConfig else { return true };
1627 custom.wantUpdatable
1628 }
1629 }
1630}
1631
Nikita Ioffe5776f082023-02-10 21:38:26 +00001632fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1633 match config {
1634 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001635 VirtualMachineConfig::AppConfig(config) => {
1636 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1637 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001638 }
1639}
1640
Nikita Ioffe631717e2023-09-05 13:38:07 +01001641fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1642 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1643 if let Some(custom_config) = &config.customConfig {
1644 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1645 return Err(anyhow!("vendor modules feature is disabled"))
1646 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1647 }
1648 }
1649 Ok(())
1650}
1651
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001652fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1653 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1654 if let Some(custom_config) = &config.customConfig {
1655 if !custom_config.devices.is_empty() {
1656 return Err(anyhow!("device assignment feature is disabled"))
1657 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1658 }
1659 }
1660 Ok(())
1661}
1662
Alan Stokesfda70842023-12-20 17:50:14 +00001663fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1664 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1665 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1666 if !payload_config.extraApks.is_empty() {
1667 return Err(anyhow!("multi-tenant feature is disabled"))
1668 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1669 }
1670 Ok(())
1671}
1672
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001673fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1674 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1675 if let Some(custom_config) = &config.customConfig {
1676 if !custom_config.extraKernelCmdlineParams.is_empty() {
1677 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1678 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1679 }
1680 }
1681 Ok(())
1682}
1683
Nikita Ioffef934e812024-07-05 15:44:41 +00001684fn check_protected_vm_is_supported() -> binder::Result<()> {
1685 let is_pvm_supported =
1686 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1687 if is_pvm_supported {
1688 Ok(())
1689 } else {
1690 Err(anyhow!("pVM is not supported"))
1691 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1692 }
1693}
1694
Nikita Ioffe631717e2023-09-05 13:38:07 +01001695fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1696 if !cfg!(vendor_modules) {
1697 check_no_vendor_modules(config)?;
1698 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001699 if !cfg!(device_assignment) {
1700 check_no_devices(config)?;
1701 }
Alan Stokesfda70842023-12-20 17:50:14 +00001702 if !cfg!(multi_tenant) {
1703 check_no_extra_apks(config)?;
1704 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001705 if !cfg!(debuggable_vms_improvements) {
1706 check_no_extra_kernel_cmdline_params(config)?;
1707 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001708 Ok(())
1709}
1710
Inseob Kimecde8c02024-09-03 13:11:08 +09001711fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1712 check_no_vendor_modules(config)?;
1713 check_no_devices(config)?;
1714
1715 Ok(())
1716}
1717
Inseob Kim0168b462022-12-27 14:54:35 +09001718fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001719 fd: Option<&ParcelFileDescriptor>,
1720 tag: String,
1721) -> Result<Option<File>, Status> {
1722 if let Some(fd) = fd {
1723 return Ok(Some(clone_file(fd)?));
1724 }
1725
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001726 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001727 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001728
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001729 let mut reader = BufReader::new(File::from(read_fd));
1730 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001731
1732 std::thread::spawn(move || loop {
1733 let mut buf = vec![];
1734 match reader.read_until(b'\n', &mut buf) {
1735 Ok(0) => {
1736 // EOF
1737 return;
1738 }
1739 Ok(size) => {
1740 if buf[size - 1] == b'\n' {
1741 buf.pop();
1742 }
1743 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1744 }
1745 Err(e) => {
1746 error!("Could not read console pipe: {:?}", e);
1747 return;
1748 }
1749 };
1750 });
1751
1752 Ok(Some(write_fd))
1753}
1754
Jooyung Han35edb8f2021-07-01 16:17:16 +09001755/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1756/// it doesn't require that T implements Clone.
1757enum BorrowedOrOwned<'a, T> {
1758 Borrowed(&'a T),
1759 Owned(T),
1760}
1761
1762impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1763 fn as_ref(&self) -> &T {
1764 match self {
1765 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001766 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001767 }
1768 }
1769}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001770
1771/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1772#[derive(Debug, Default)]
1773struct VirtualMachineService {
1774 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001775 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001776}
1777
1778impl Interface for VirtualMachineService {}
1779
1780impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001781 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1782 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001783 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001784 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001785 vm.update_payload_state(PayloadState::Started)
1786 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001787 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001788
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001789 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1790 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001791 Ok(())
1792 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001793 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001794 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001795 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001796 }
Inseob Kim2444af92021-08-31 01:22:50 +09001797
Inseob Kimc7d28c72021-10-25 14:28:10 +00001798 fn notifyPayloadReady(&self) -> binder::Result<()> {
1799 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001800 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001801 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001802 vm.update_payload_state(PayloadState::Ready)
1803 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001804 vm.callbacks.notify_payload_ready(cid);
1805 Ok(())
1806 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001807 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001808 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001809 }
1810 }
1811
Inseob Kimc7d28c72021-10-25 14:28:10 +00001812 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1813 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001814 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001815 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001816 vm.update_payload_state(PayloadState::Finished)
1817 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001818 vm.callbacks.notify_payload_finished(cid, exit_code);
1819 Ok(())
1820 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001821 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001822 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001823 }
1824 }
1825
Alan Stokes2bead0d2022-09-05 16:58:34 +01001826 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001827 let cid = self.cid;
1828 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001829 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001830 vm.update_payload_state(PayloadState::Finished)
1831 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001832 vm.callbacks.notify_error(cid, error_code, message);
1833 Ok(())
1834 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001835 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001836 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001837 }
1838 }
Alice Wangc2fec932023-02-23 16:24:02 +00001839
Shikha Panware45e9422024-02-28 21:18:10 +00001840 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1841 if !is_secretkeeper_supported() {
1842 return Err(StatusCode::NAME_NOT_FOUND)?;
1843 }
1844 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1845 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001846 }
1847
Alice Wange64dd182024-01-17 15:57:55 +00001848 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1849 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001850 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001851}
1852
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001853fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001854 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1855 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001856}
1857
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001858impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001859 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001860 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001861 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001862 BinderFeatures::default(),
1863 )
1864 }
1865}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001866
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001867struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1868
1869impl Interface for SecretkeeperProxy {}
1870
1871impl ISecretkeeper for SecretkeeperProxy {
1872 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1873 // Pass the request to the channel, and read the response.
1874 self.0.processSecretManagementRequest(req)
1875 }
1876
1877 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1878 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1879 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1880 }
1881
1882 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1883 self.0.deleteIds(ids)
1884 }
1885
1886 fn deleteAll(&self) -> binder::Result<()> {
1887 self.0.deleteAll()
1888 }
1889}
1890
1891struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1892
1893impl Interface for AuthGraphKeyExchangeProxy {}
1894
1895impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1896 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1897 self.0.create()
1898 }
1899
1900 fn init(
1901 &self,
1902 peer_pub_key: &PubKey,
1903 peer_id: &Identity,
1904 peer_nonce: &[u8],
1905 peer_version: i32,
1906 ) -> binder::Result<KeInitResult> {
1907 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1908 }
1909
1910 fn finish(
1911 &self,
1912 peer_pub_key: &PubKey,
1913 peer_id: &Identity,
1914 peer_signature: &SessionIdSignature,
1915 peer_nonce: &[u8],
1916 peer_version: i32,
1917 own_key: &Key,
1918 ) -> binder::Result<SessionInfo> {
1919 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1920 }
1921
1922 fn authenticationComplete(
1923 &self,
1924 peer_signature: &SessionIdSignature,
1925 shared_keys: &[AuthgraphArc; 2],
1926 ) -> binder::Result<[AuthgraphArc; 2]> {
1927 self.0.authenticationComplete(peer_signature, shared_keys)
1928 }
1929}
1930
Inseob Kimecde8c02024-09-03 13:11:08 +09001931// KEEP IN SYNC WITH early_vms.xsd
1932#[derive(Debug, Deserialize, PartialEq)]
1933struct EarlyVm {
1934 #[allow(dead_code)]
1935 name: String,
1936 #[allow(dead_code)]
1937 cid: i32,
1938 #[allow(dead_code)]
1939 path: String,
1940}
1941
1942#[derive(Debug, Default, Deserialize)]
1943struct EarlyVms {
1944 #[allow(dead_code)]
1945 early_vm: Vec<EarlyVm>,
1946}
1947
1948fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1949 match partition {
1950 "system" => Ok(100..200),
1951 "system_ext" | "product" => Ok(200..300),
1952 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1953 }
1954}
1955
1956fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1957 if !xml_path.exists() {
1958 bail!("{} doesn't exist", xml_path.display());
1959 }
1960
1961 let xml =
1962 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
1963 let xml = String::from_utf8(xml)
1964 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
1965 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
1966 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
1967
1968 let mut found_vm: Option<EarlyVm> = None;
1969
1970 for early_vm in early_vms.early_vm {
1971 if early_vm.name != name {
1972 continue;
1973 }
1974
1975 let cid = early_vm
1976 .cid
1977 .try_into()
1978 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
1979
1980 if !cid_range.contains(&cid) {
1981 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
1982 }
1983
1984 if found_vm.is_some() {
1985 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
1986 }
1987
1988 found_vm = Some(early_vm);
1989 }
1990
1991 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
1992}
1993
1994fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
1995 let cid_range = range_for_partition(partition)?;
1996 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
1997}
1998
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001999#[cfg(test)]
2000mod tests {
2001 use super::*;
2002
2003 #[test]
2004 fn test_is_allowed_label_for_partition() -> Result<()> {
2005 let expected_results = vec![
2006 ("u:object_r:system_file:s0", true),
2007 ("u:object_r:apk_data_file:s0", true),
2008 ("u:object_r:app_data_file:s0", false),
2009 ("u:object_r:app_data_file:s0:c512,c768", false),
2010 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2011 ("invalid", false),
2012 ("user:role:apk_data_file:severity:categories", true),
2013 ("user:role:apk_data_file:severity:categories:extraneous", false),
2014 ];
2015
2016 for (label, expected_valid) in expected_results {
2017 let context = SeContext::new(label)?;
2018 let result = check_label_is_allowed(&context);
2019 if expected_valid {
2020 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2021 } else if result.is_ok() {
2022 bail!("Expected label {} to be disallowed", label);
2023 }
2024 }
2025 Ok(())
2026 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002027
2028 #[test]
2029 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2030 let apk = tempfile::tempfile().unwrap();
2031 let idsig = tempfile::tempfile().unwrap();
2032
2033 let ret = create_or_update_idsig_file(
2034 &ParcelFileDescriptor::new(apk),
2035 &ParcelFileDescriptor::new(idsig),
2036 );
2037 assert!(ret.is_err(), "should fail");
2038 Ok(())
2039 }
2040
2041 #[test]
2042 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2043 let tmp_dir = tempfile::TempDir::new().unwrap();
2044 let apk = File::open(tmp_dir.path()).unwrap();
2045 let idsig = tempfile::tempfile().unwrap();
2046
2047 let ret = create_or_update_idsig_file(
2048 &ParcelFileDescriptor::new(apk),
2049 &ParcelFileDescriptor::new(idsig),
2050 );
2051 assert!(ret.is_err(), "should fail");
2052 Ok(())
2053 }
2054
2055 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2056 /// on ext4 filesystem is passed.
2057 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2058 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2059 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2060 #[test]
2061 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2062 // APEXes are backed by the ext4.
2063 let apk = File::open("/apex/com.android.virt/").unwrap();
2064 let idsig = tempfile::tempfile().unwrap();
2065
2066 let ret = create_or_update_idsig_file(
2067 &ParcelFileDescriptor::new(apk),
2068 &ParcelFileDescriptor::new(idsig),
2069 );
2070 assert!(ret.is_err(), "should fail");
2071 Ok(())
2072 }
Jiyong Park8d192952023-06-26 14:29:51 +09002073
2074 #[test]
2075 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2076 use std::io::Seek;
2077
2078 // Pick any APK
2079 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2080 let mut idsig = tempfile::tempfile().unwrap();
2081
2082 create_or_update_idsig_file(
2083 &ParcelFileDescriptor::new(apk.try_clone()?),
2084 &ParcelFileDescriptor::new(idsig.try_clone()?),
2085 )?;
2086 let modified_orig = idsig.metadata()?.modified()?;
2087 apk.rewind()?;
2088 idsig.rewind()?;
2089
2090 // Call the function again
2091 create_or_update_idsig_file(
2092 &ParcelFileDescriptor::new(apk.try_clone()?),
2093 &ParcelFileDescriptor::new(idsig.try_clone()?),
2094 )?;
2095 let modified_new = idsig.metadata()?.modified()?;
2096 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2097 Ok(())
2098 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002099
2100 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002101 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2102 use std::io::Read;
2103
2104 // Pick any APK
2105 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2106 let idsig_empty = tempfile::tempfile().unwrap();
2107 let mut idsig_invalid = tempfile::tempfile().unwrap();
2108 idsig_invalid.write_all(b"Oops")?;
2109
2110 // Create new idsig
2111 create_or_update_idsig_file(
2112 &ParcelFileDescriptor::new(apk.try_clone()?),
2113 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2114 )?;
2115 apk.rewind()?;
2116
2117 // Update idsig_invalid
2118 create_or_update_idsig_file(
2119 &ParcelFileDescriptor::new(apk.try_clone()?),
2120 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2121 )?;
2122
2123 // Ensure the 2 idsig files have same size!
2124 assert!(
2125 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2126 "idsig files differ in size"
2127 );
2128 // Ensure the 2 idsig files have same content!
2129 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2130 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2131 }
2132 Ok(())
2133 }
2134 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002135 fn test_append_kernel_param_first_param() {
2136 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2137 append_kernel_param("foo=1", &mut vm_config);
2138 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2139 }
2140
2141 #[test]
2142 fn test_append_kernel_param() {
2143 let mut vm_config =
2144 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2145 append_kernel_param("bar=42", &mut vm_config);
2146 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2147 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002148
Inseob Kim46257382024-01-03 15:41:22 +09002149 fn test_extract_os_name_from_config_path(
2150 path: &Path,
2151 expected_result: Option<&str>,
2152 ) -> Result<()> {
2153 let result = extract_os_name_from_config_path(path);
2154 if result.as_deref() != expected_result {
2155 bail!("Expected {:?} but was {:?}", expected_result, &result)
2156 }
2157 Ok(())
2158 }
2159
2160 #[test]
2161 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2162 test_extract_os_name_from_config_path(
2163 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2164 Some("microdroid"),
2165 )
2166 }
2167
2168 #[test]
2169 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2170 test_extract_os_name_from_config_path(
2171 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2172 Some("microdroid_gki-android14-6.1"),
2173 )
2174 }
2175
2176 #[test]
2177 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2178 test_extract_os_name_from_config_path(
2179 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2180 None,
2181 )
2182 }
2183
2184 #[test]
2185 fn test_extract_os_name_from_configs() -> Result<()> {
2186 let tmp_dir = tempfile::TempDir::new()?;
2187 let tmp_dir_path = tmp_dir.path().to_owned();
2188
2189 let mut os_names: HashSet<String> = HashSet::new();
2190 os_names.insert("microdroid".to_owned());
2191 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2192 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2193
2194 // config files
2195 for os_name in &os_names {
2196 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2197 }
2198
2199 // fake files not related to configs
2200 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2201 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2202
2203 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2204 Some(s) => s.to_owned(),
2205 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2206 };
2207
2208 let result = extract_os_names_from_configs(&glob_pattern)?;
2209 if result != os_names {
2210 bail!("Expected {:?} but was {:?}", os_names, result);
2211 }
2212 Ok(())
2213 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002214
2215 #[test]
2216 fn test_find_early_vms_from_xml() -> Result<()> {
2217 let tmp_dir = tempfile::TempDir::new()?;
2218 let tmp_dir_path = tmp_dir.path().to_owned();
2219 let xml_path = tmp_dir_path.join("early_vms.xml");
2220
2221 std::fs::write(
2222 &xml_path,
2223 br#"<?xml version="1.0" encoding="utf-8"?>
2224 <early_vms>
2225 <early_vm>
2226 <name>vm_demo_native_early</name>
2227 <cid>123</cid>
2228 <path>/system/bin/vm_demo_native_early</path>
2229 </early_vm>
2230 <early_vm>
2231 <name>vm_demo_duplicated_name</name>
2232 <cid>456</cid>
2233 <path>/system/bin/vm_demo_duplicated_name_1</path>
2234 </early_vm>
2235 <early_vm>
2236 <name>vm_demo_duplicated_name</name>
2237 <cid>789</cid>
2238 <path>/system/bin/vm_demo_duplicated_name_2</path>
2239 </early_vm>
2240 <early_vm>
2241 <name>vm_demo_invalid_cid_1</name>
2242 <cid>-1</cid>
2243 <path>/system/bin/vm_demo_invalid_cid_1</path>
2244 </early_vm>
2245 <early_vm>
2246 <name>vm_demo_invalid_cid_2</name>
2247 <cid>999999</cid>
2248 <path>/system/bin/vm_demo_invalid_cid_2</path>
2249 </early_vm>
2250 </early_vms>
2251 "#,
2252 )?;
2253
2254 let cid_range = 100..1000;
2255
2256 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2257 let expected = EarlyVm {
2258 name: "vm_demo_native_early".to_owned(),
2259 cid: 123,
2260 path: "/system/bin/vm_demo_native_early".to_owned(),
2261 };
2262 assert_eq!(result, expected);
2263
2264 assert!(
2265 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2266 "should fail"
2267 );
2268 assert!(
2269 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2270 "should fail"
2271 );
2272 assert!(
2273 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2274 "should fail"
2275 );
2276
2277 Ok(())
2278 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002279}