blob: 87fb611a4bd22bf28d2bee0dccdfe00a0a3f84ea [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);
1108 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001109 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001110
Chris Wailes6177c662024-05-09 14:37:44 -07001111 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001112 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001113
1114 for param in custom_config.extraKernelCmdlineParams.iter() {
1115 append_kernel_param(param, &mut vm_config);
1116 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001117 }
1118
Andrew Walbrancc045902021-07-27 16:06:17 +00001119 if config.memoryMib > 0 {
1120 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001121 }
1122
Chris Wailes6177c662024-05-09 14:37:44 -07001123 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001124 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001125 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001126 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001127 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001128
Shikha Panwar22e70452022-10-10 18:32:55 +00001129 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001130 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001131
1132 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1133 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001134 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001135 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001136 temporary_directory,
1137 apk_file,
1138 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001139 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001140 &vm_payload_config,
1141 &mut vm_config,
1142 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001143
Andrew Walbrancc0db522021-07-12 17:03:42 +00001144 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001145}
1146
Inseob Kimff48a7c2024-02-26 22:07:21 +09001147fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1148 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1149 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1150
1151 // microdroid vendor image is OK
1152 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1153 {
1154 return Ok(());
1155 }
1156
1157 if link.starts_with("/vendor") || link.starts_with("/odm") {
1158 bail!("vendor or odm file {} can't be used for VM", link.display());
1159 }
1160
1161 Ok(())
1162}
1163
1164fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1165 config
1166 .disks
1167 .iter()
1168 .flat_map(|disk| disk.partitions.iter())
1169 .filter_map(|partition| partition.image.as_ref())
1170 .try_for_each(check_partition_for_file)?;
1171
1172 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1173 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1174 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1175
1176 Ok(())
1177}
1178
Alan Stokes0d1ef782022-09-27 13:46:35 +01001179fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1180 let mut apk_zip = ZipArchive::new(apk_file)?;
1181 let config_file = apk_zip.by_name(config_path)?;
1182 Ok(serde_json::from_reader(config_file)?)
1183}
1184
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001185fn create_vm_payload_config(
1186 payload_config: &VirtualMachinePayloadConfig,
1187) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001188 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1189 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1190 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001191
1192 let payload_binary_name = &payload_config.payloadBinaryName;
1193 if payload_binary_name.contains('/') {
1194 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1195 }
1196
1197 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001198
1199 // The VM only cares about how many there are, these names are actually ignored.
1200 let extra_apk_count = payload_config.extraApks.len();
1201 let extra_apks =
1202 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1203
Inseob Kim89b24592024-02-23 18:59:43 +09001204 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001205}
1206
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001207/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001208fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001209 temporary_directory: &Path,
1210 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001211) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001212 let id = *next_temporary_image_id;
1213 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001214 CompositeImageFilenames {
1215 composite: temporary_directory.join(format!("composite-{}.img", id)),
1216 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1217 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1218 }
1219}
1220
1221/// Filenames for a composite disk image, including header and footer partitions.
1222#[derive(Clone, Debug, Eq, PartialEq)]
1223struct CompositeImageFilenames {
1224 /// The composite disk image itself.
1225 composite: PathBuf,
1226 /// The header partition image.
1227 header: PathBuf,
1228 /// The footer partition image.
1229 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001230}
1231
Jiyong Park753553b2021-07-12 21:21:09 +09001232/// Checks whether the caller has a specific permission
1233fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001234 if cfg!(early) {
1235 // Skip permission check for early VMs, in favor of SELinux
1236 return Ok(());
1237 }
David Brazdil1f530702022-10-03 12:18:10 +01001238 let calling_pid = get_calling_pid();
1239 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001240 // Root can do anything
1241 if calling_uid == 0 {
1242 return Ok(());
1243 }
1244 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001245 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001246 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001247 Ok(())
1248 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001249 Err(anyhow!("does not have the {} permission", perm))
1250 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001251 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001252}
1253
Jiyong Park753553b2021-07-12 21:21:09 +09001254/// Check whether the caller of the current Binder method is allowed to manage VMs
1255fn check_manage_access() -> binder::Result<()> {
1256 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1257}
1258
Inseob Kim1119d702022-05-02 18:01:58 +09001259/// Check whether the caller of the current Binder method is allowed to create custom VMs
1260fn check_use_custom_virtual_machine() -> binder::Result<()> {
1261 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1262}
1263
Alan Stokes185fe112023-01-10 16:20:55 +00001264/// Return whether a partition is exempt from selinux label checks, because we know that it does
1265/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001266fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001267 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001268 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001269 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001270 || label == "microdroid-apk-idsig"
1271 || label == "payload-metadata"
1272 || label.starts_with("extra-idsig-")
1273}
1274
Alice Wangc206b9b2023-08-28 14:13:51 +00001275/// Returns whether a partition with the given label is safe for a raw config VM.
1276fn is_safe_raw_partition(label: &str) -> bool {
1277 label == "vm-instance"
1278}
1279
Alan Stokes185fe112023-01-10 16:20:55 +00001280/// Check that a file SELinux label is acceptable.
1281///
1282/// 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 +09001283/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001284///
1285/// Note that sepolicy must also grant read access for these types to both virtualization
1286/// service and crosvm.
1287///
1288/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1289/// user devices (W^X).
1290fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1291 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001292 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001293 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001294 | "staging_data_file" // updated/staged APEX images
1295 | "system_file" // immutable dm-verity protected partition
1296 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001297 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001298 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001299 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001300 }
1301}
1302
Alan Stokes185fe112023-01-10 16:20:55 +00001303fn check_label_for_partition(partition: &Partition) -> Result<()> {
1304 let file = partition.image.as_ref().unwrap().as_ref();
1305 check_label_is_allowed(&getfilecon(file)?)
1306 .with_context(|| format!("Partition {} invalid", &partition.label))
1307}
1308
1309fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1310 if let Some(f) = kernel {
1311 check_label_for_file(f, "kernel")?;
1312 }
1313 if let Some(f) = initrd {
1314 check_label_for_file(f, "initrd")?;
1315 }
1316 Ok(())
1317}
1318fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1319 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1320}
1321
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001322/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1323#[derive(Debug)]
1324struct VirtualMachine {
1325 instance: Arc<VmInstance>,
1326}
1327
1328impl VirtualMachine {
1329 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001330 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001331 }
1332}
1333
1334impl Interface for VirtualMachine {}
1335
1336impl IVirtualMachine for VirtualMachine {
1337 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001338 // Don't check permission. The owner of the VM might have passed this binder object to
1339 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001340 Ok(self.instance.cid as i32)
1341 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001342
Andrew Walbran6b650662021-09-07 13:13:23 +00001343 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001344 // Don't check permission. The owner of the VM might have passed this binder object to
1345 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001346 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001347 }
1348
1349 fn registerCallback(
1350 &self,
1351 callback: &Strong<dyn IVirtualMachineCallback>,
1352 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001353 // Don't check permission. The owner of the VM might have passed this binder object to
1354 // others.
1355 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001356 // TODO: Should this give an error if the VM is already dead?
1357 self.instance.callbacks.add(callback.clone());
1358 Ok(())
1359 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001360
Andrew Walbranf8d94112021-09-07 11:45:36 +00001361 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001362 self.instance
1363 .start()
1364 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1365 .with_log()
1366 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001367 }
1368
Inseob Kima446f802022-07-11 19:46:37 +09001369 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001370 self.instance
1371 .kill()
1372 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1373 .with_log()
1374 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001375 }
1376
Keir Fraser48221ba2024-07-12 14:05:02 +00001377 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1378 let balloon = self
1379 .instance
1380 .get_memory_balloon()
1381 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1382 .with_log()
1383 .or_service_specific_exception(-1)?;
1384 Ok(balloon.try_into().unwrap())
1385 }
1386
1387 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001388 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001389 .set_memory_balloon(num_bytes.try_into().unwrap())
1390 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001391 .with_log()
1392 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001393 }
1394
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001395 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001396 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001397 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001398 }
Alan Stokes10c47672022-12-13 17:17:08 +00001399 let port = port as u32;
1400 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001401 return Err(anyhow!("Can't connect to privileged port {port}"))
1402 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001403 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001404 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1405 .context("Failed to connect")
1406 .or_service_specific_exception(-1)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001407 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001408 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001409
1410 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1411 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1412 }
Jiyong Park23b67392024-07-04 13:51:42 +09001413
1414 fn suspend(&self) -> binder::Result<()> {
1415 self.instance
1416 .suspend()
1417 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1418 .with_log()
1419 .or_service_specific_exception(-1)
1420 }
1421
1422 fn resume(&self) -> binder::Result<()> {
1423 self.instance
1424 .resume()
1425 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1426 .with_log()
1427 .or_service_specific_exception(-1)
1428 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001429}
1430
1431impl Drop for VirtualMachine {
1432 fn drop(&mut self) {
1433 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001434 if let Err(e) = self.instance.kill() {
1435 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1436 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001437 }
1438}
1439
1440/// A set of Binders to be called back in response to various events on the VM, such as when it
1441/// dies.
1442#[derive(Debug, Default)]
1443pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1444
1445impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001446 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001447 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001448 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001449 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001450 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001451 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001452 }
1453 }
1454 }
1455
Inseob Kim14cb8692021-08-31 21:50:39 +09001456 /// Call all registered callbacks to notify that the payload is ready to serve.
1457 pub fn notify_payload_ready(&self, cid: Cid) {
1458 let callbacks = &*self.0.lock().unwrap();
1459 for callback in callbacks {
1460 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001461 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001462 }
1463 }
1464 }
1465
Inseob Kim2444af92021-08-31 01:22:50 +09001466 /// Call all registered callbacks to notify that the payload has finished.
1467 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1468 let callbacks = &*self.0.lock().unwrap();
1469 for callback in callbacks {
1470 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001471 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001472 }
1473 }
1474 }
1475
Jooyung Handd0a1732021-11-23 15:26:20 +09001476 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001477 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001478 let callbacks = &*self.0.lock().unwrap();
1479 for callback in callbacks {
1480 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001481 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001482 }
1483 }
1484 }
1485
Andrew Walbrandae07162021-03-12 17:05:20 +00001486 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001487 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001488 let callbacks = &*self.0.lock().unwrap();
1489 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001490 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001491 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001492 }
1493 }
1494 }
1495
1496 /// Add a new callback to the set.
1497 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1498 self.0.lock().unwrap().push(callback);
1499 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001500}
1501
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001502/// The mutable state of the VirtualizationService. There should only be one instance of this
1503/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001504#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001505struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001506 /// The VMs which have been started. When VMs are started a weak reference is added to this
1507 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1508 /// the Binder client are dropped the weak reference here will become invalid, and will be
1509 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001510 vms: Vec<Weak<VmInstance>>,
1511}
1512
1513impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001514 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001515 fn vms(&self) -> Vec<Arc<VmInstance>> {
1516 // Attempt to upgrade the weak pointers to strong pointers.
1517 self.vms.iter().filter_map(Weak::upgrade).collect()
1518 }
1519
1520 /// Add a new VM to the list.
1521 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1522 // Garbage collect any entries from the stored list which no longer exist.
1523 self.vms.retain(|vm| vm.strong_count() > 0);
1524
1525 // Actually add the new VM.
1526 self.vms.push(vm);
1527 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001528
Jiyong Park8611a6c2021-07-09 18:17:44 +09001529 /// Get a VM that corresponds to the given cid
1530 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1531 self.vms().into_iter().find(|vm| vm.cid == cid)
1532 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001533}
1534
Andrew Walbran6b650662021-09-07 13:13:23 +00001535/// Gets the `VirtualMachineState` of the given `VmInstance`.
1536fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001537 match &*instance.vm_state.lock().unwrap() {
1538 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1539 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001540 PayloadState::Starting => VirtualMachineState::STARTING,
1541 PayloadState::Started => VirtualMachineState::STARTED,
1542 PayloadState::Ready => VirtualMachineState::READY,
1543 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001544 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001545 },
1546 VmState::Dead => VirtualMachineState::DEAD,
1547 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001548 }
1549}
1550
David Brazdilf50c7a62023-04-19 14:22:42 +00001551/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001552pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1553 file.as_ref()
1554 .try_clone()
1555 .context("Failed to clone File from ParcelFileDescriptor")
1556 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001557 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001558}
1559
Andrew Walbrand3a84182021-09-07 14:48:52 +00001560/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001561fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001562 file.as_ref().map(clone_file).transpose()
1563}
1564
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001565/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001566fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1567 // SAFETY: ownership is transferred from stream to f
1568 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1569 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001570}
1571
Jiyong Parkdcf17412022-02-08 15:07:23 +09001572/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001573fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1574 VersionReq::parse(s)
1575 .with_context(|| format!("Invalid platform version requirement {}", s))
1576 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001577}
1578
Jiyong Parked180932023-02-24 19:55:41 +09001579/// Create the empty ramdump file
1580fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1581 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1582 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1583 // owner) for readout.
1584 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001585 let ramdump = File::create(ramdump_path)
1586 .context("Failed to prepare ramdump file")
1587 .with_log()
1588 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001589 Ok(ramdump)
1590}
1591
Nikita Ioffe5776f082023-02-10 21:38:26 +00001592fn is_protected(config: &VirtualMachineConfig) -> bool {
1593 match config {
1594 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1595 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1596 }
1597}
1598
1599fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1600 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001601 return Err(anyhow!("Can't use gdb with protected VMs"))
1602 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001603 }
1604
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001605 if get_debug_level(config) == Some(DebugLevel::NONE) {
1606 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1607 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001608 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001609
1610 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001611}
1612
Shikha Panwar61a74b52024-02-16 13:17:01 +00001613fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1614 match config {
1615 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1616 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1617 }
1618}
1619
Alan Stokesc96b35e2024-05-03 13:21:20 +01001620fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1621 match config {
1622 VirtualMachineConfig::RawConfig(_) => true,
1623 VirtualMachineConfig::AppConfig(config) => {
1624 let Some(custom) = &config.customConfig else { return true };
1625 custom.wantUpdatable
1626 }
1627 }
1628}
1629
Nikita Ioffe5776f082023-02-10 21:38:26 +00001630fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1631 match config {
1632 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001633 VirtualMachineConfig::AppConfig(config) => {
1634 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1635 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001636 }
1637}
1638
Nikita Ioffe631717e2023-09-05 13:38:07 +01001639fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1640 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1641 if let Some(custom_config) = &config.customConfig {
1642 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1643 return Err(anyhow!("vendor modules feature is disabled"))
1644 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1645 }
1646 }
1647 Ok(())
1648}
1649
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001650fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1651 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1652 if let Some(custom_config) = &config.customConfig {
1653 if !custom_config.devices.is_empty() {
1654 return Err(anyhow!("device assignment feature is disabled"))
1655 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1656 }
1657 }
1658 Ok(())
1659}
1660
Alan Stokesfda70842023-12-20 17:50:14 +00001661fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1662 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1663 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1664 if !payload_config.extraApks.is_empty() {
1665 return Err(anyhow!("multi-tenant feature is disabled"))
1666 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1667 }
1668 Ok(())
1669}
1670
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001671fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1672 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1673 if let Some(custom_config) = &config.customConfig {
1674 if !custom_config.extraKernelCmdlineParams.is_empty() {
1675 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1676 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1677 }
1678 }
1679 Ok(())
1680}
1681
Nikita Ioffef934e812024-07-05 15:44:41 +00001682fn check_protected_vm_is_supported() -> binder::Result<()> {
1683 let is_pvm_supported =
1684 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1685 if is_pvm_supported {
1686 Ok(())
1687 } else {
1688 Err(anyhow!("pVM is not supported"))
1689 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1690 }
1691}
1692
Nikita Ioffe631717e2023-09-05 13:38:07 +01001693fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1694 if !cfg!(vendor_modules) {
1695 check_no_vendor_modules(config)?;
1696 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001697 if !cfg!(device_assignment) {
1698 check_no_devices(config)?;
1699 }
Alan Stokesfda70842023-12-20 17:50:14 +00001700 if !cfg!(multi_tenant) {
1701 check_no_extra_apks(config)?;
1702 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001703 if !cfg!(debuggable_vms_improvements) {
1704 check_no_extra_kernel_cmdline_params(config)?;
1705 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001706 Ok(())
1707}
1708
Inseob Kimecde8c02024-09-03 13:11:08 +09001709fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1710 check_no_vendor_modules(config)?;
1711 check_no_devices(config)?;
1712
1713 Ok(())
1714}
1715
Inseob Kim0168b462022-12-27 14:54:35 +09001716fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001717 fd: Option<&ParcelFileDescriptor>,
1718 tag: String,
1719) -> Result<Option<File>, Status> {
1720 if let Some(fd) = fd {
1721 return Ok(Some(clone_file(fd)?));
1722 }
1723
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001724 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001725 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001726
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001727 let mut reader = BufReader::new(File::from(read_fd));
1728 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001729
1730 std::thread::spawn(move || loop {
1731 let mut buf = vec![];
1732 match reader.read_until(b'\n', &mut buf) {
1733 Ok(0) => {
1734 // EOF
1735 return;
1736 }
1737 Ok(size) => {
1738 if buf[size - 1] == b'\n' {
1739 buf.pop();
1740 }
1741 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1742 }
1743 Err(e) => {
1744 error!("Could not read console pipe: {:?}", e);
1745 return;
1746 }
1747 };
1748 });
1749
1750 Ok(Some(write_fd))
1751}
1752
Jooyung Han35edb8f2021-07-01 16:17:16 +09001753/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1754/// it doesn't require that T implements Clone.
1755enum BorrowedOrOwned<'a, T> {
1756 Borrowed(&'a T),
1757 Owned(T),
1758}
1759
1760impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1761 fn as_ref(&self) -> &T {
1762 match self {
1763 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001764 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001765 }
1766 }
1767}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001768
1769/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1770#[derive(Debug, Default)]
1771struct VirtualMachineService {
1772 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001773 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001774}
1775
1776impl Interface for VirtualMachineService {}
1777
1778impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001779 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1780 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001781 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001782 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001783 vm.update_payload_state(PayloadState::Started)
1784 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001785 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001786
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001787 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1788 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001789 Ok(())
1790 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001791 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001792 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001793 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001794 }
Inseob Kim2444af92021-08-31 01:22:50 +09001795
Inseob Kimc7d28c72021-10-25 14:28:10 +00001796 fn notifyPayloadReady(&self) -> binder::Result<()> {
1797 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001798 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001799 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001800 vm.update_payload_state(PayloadState::Ready)
1801 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001802 vm.callbacks.notify_payload_ready(cid);
1803 Ok(())
1804 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001805 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001806 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001807 }
1808 }
1809
Inseob Kimc7d28c72021-10-25 14:28:10 +00001810 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1811 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001812 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001813 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001814 vm.update_payload_state(PayloadState::Finished)
1815 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001816 vm.callbacks.notify_payload_finished(cid, exit_code);
1817 Ok(())
1818 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001819 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001820 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001821 }
1822 }
1823
Alan Stokes2bead0d2022-09-05 16:58:34 +01001824 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001825 let cid = self.cid;
1826 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001827 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001828 vm.update_payload_state(PayloadState::Finished)
1829 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001830 vm.callbacks.notify_error(cid, error_code, message);
1831 Ok(())
1832 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001833 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001834 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001835 }
1836 }
Alice Wangc2fec932023-02-23 16:24:02 +00001837
Shikha Panware45e9422024-02-28 21:18:10 +00001838 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1839 if !is_secretkeeper_supported() {
1840 return Err(StatusCode::NAME_NOT_FOUND)?;
1841 }
1842 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1843 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001844 }
1845
Alice Wange64dd182024-01-17 15:57:55 +00001846 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1847 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001848 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001849}
1850
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001851fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001852 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1853 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001854}
1855
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001856impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001857 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001858 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001859 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001860 BinderFeatures::default(),
1861 )
1862 }
1863}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001864
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001865struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1866
1867impl Interface for SecretkeeperProxy {}
1868
1869impl ISecretkeeper for SecretkeeperProxy {
1870 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1871 // Pass the request to the channel, and read the response.
1872 self.0.processSecretManagementRequest(req)
1873 }
1874
1875 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1876 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1877 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1878 }
1879
1880 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1881 self.0.deleteIds(ids)
1882 }
1883
1884 fn deleteAll(&self) -> binder::Result<()> {
1885 self.0.deleteAll()
1886 }
1887}
1888
1889struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1890
1891impl Interface for AuthGraphKeyExchangeProxy {}
1892
1893impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1894 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1895 self.0.create()
1896 }
1897
1898 fn init(
1899 &self,
1900 peer_pub_key: &PubKey,
1901 peer_id: &Identity,
1902 peer_nonce: &[u8],
1903 peer_version: i32,
1904 ) -> binder::Result<KeInitResult> {
1905 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1906 }
1907
1908 fn finish(
1909 &self,
1910 peer_pub_key: &PubKey,
1911 peer_id: &Identity,
1912 peer_signature: &SessionIdSignature,
1913 peer_nonce: &[u8],
1914 peer_version: i32,
1915 own_key: &Key,
1916 ) -> binder::Result<SessionInfo> {
1917 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1918 }
1919
1920 fn authenticationComplete(
1921 &self,
1922 peer_signature: &SessionIdSignature,
1923 shared_keys: &[AuthgraphArc; 2],
1924 ) -> binder::Result<[AuthgraphArc; 2]> {
1925 self.0.authenticationComplete(peer_signature, shared_keys)
1926 }
1927}
1928
Inseob Kimecde8c02024-09-03 13:11:08 +09001929// KEEP IN SYNC WITH early_vms.xsd
1930#[derive(Debug, Deserialize, PartialEq)]
1931struct EarlyVm {
1932 #[allow(dead_code)]
1933 name: String,
1934 #[allow(dead_code)]
1935 cid: i32,
1936 #[allow(dead_code)]
1937 path: String,
1938}
1939
1940#[derive(Debug, Default, Deserialize)]
1941struct EarlyVms {
1942 #[allow(dead_code)]
1943 early_vm: Vec<EarlyVm>,
1944}
1945
1946fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1947 match partition {
1948 "system" => Ok(100..200),
1949 "system_ext" | "product" => Ok(200..300),
1950 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1951 }
1952}
1953
1954fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1955 if !xml_path.exists() {
1956 bail!("{} doesn't exist", xml_path.display());
1957 }
1958
1959 let xml =
1960 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
1961 let xml = String::from_utf8(xml)
1962 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
1963 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
1964 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
1965
1966 let mut found_vm: Option<EarlyVm> = None;
1967
1968 for early_vm in early_vms.early_vm {
1969 if early_vm.name != name {
1970 continue;
1971 }
1972
1973 let cid = early_vm
1974 .cid
1975 .try_into()
1976 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
1977
1978 if !cid_range.contains(&cid) {
1979 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
1980 }
1981
1982 if found_vm.is_some() {
1983 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
1984 }
1985
1986 found_vm = Some(early_vm);
1987 }
1988
1989 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
1990}
1991
1992fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
1993 let cid_range = range_for_partition(partition)?;
1994 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
1995}
1996
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001997#[cfg(test)]
1998mod tests {
1999 use super::*;
2000
2001 #[test]
2002 fn test_is_allowed_label_for_partition() -> Result<()> {
2003 let expected_results = vec![
2004 ("u:object_r:system_file:s0", true),
2005 ("u:object_r:apk_data_file:s0", true),
2006 ("u:object_r:app_data_file:s0", false),
2007 ("u:object_r:app_data_file:s0:c512,c768", false),
2008 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2009 ("invalid", false),
2010 ("user:role:apk_data_file:severity:categories", true),
2011 ("user:role:apk_data_file:severity:categories:extraneous", false),
2012 ];
2013
2014 for (label, expected_valid) in expected_results {
2015 let context = SeContext::new(label)?;
2016 let result = check_label_is_allowed(&context);
2017 if expected_valid {
2018 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2019 } else if result.is_ok() {
2020 bail!("Expected label {} to be disallowed", label);
2021 }
2022 }
2023 Ok(())
2024 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002025
2026 #[test]
2027 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2028 let apk = tempfile::tempfile().unwrap();
2029 let idsig = tempfile::tempfile().unwrap();
2030
2031 let ret = create_or_update_idsig_file(
2032 &ParcelFileDescriptor::new(apk),
2033 &ParcelFileDescriptor::new(idsig),
2034 );
2035 assert!(ret.is_err(), "should fail");
2036 Ok(())
2037 }
2038
2039 #[test]
2040 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2041 let tmp_dir = tempfile::TempDir::new().unwrap();
2042 let apk = File::open(tmp_dir.path()).unwrap();
2043 let idsig = tempfile::tempfile().unwrap();
2044
2045 let ret = create_or_update_idsig_file(
2046 &ParcelFileDescriptor::new(apk),
2047 &ParcelFileDescriptor::new(idsig),
2048 );
2049 assert!(ret.is_err(), "should fail");
2050 Ok(())
2051 }
2052
2053 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2054 /// on ext4 filesystem is passed.
2055 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2056 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2057 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2058 #[test]
2059 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2060 // APEXes are backed by the ext4.
2061 let apk = File::open("/apex/com.android.virt/").unwrap();
2062 let idsig = tempfile::tempfile().unwrap();
2063
2064 let ret = create_or_update_idsig_file(
2065 &ParcelFileDescriptor::new(apk),
2066 &ParcelFileDescriptor::new(idsig),
2067 );
2068 assert!(ret.is_err(), "should fail");
2069 Ok(())
2070 }
Jiyong Park8d192952023-06-26 14:29:51 +09002071
2072 #[test]
2073 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2074 use std::io::Seek;
2075
2076 // Pick any APK
2077 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2078 let mut idsig = tempfile::tempfile().unwrap();
2079
2080 create_or_update_idsig_file(
2081 &ParcelFileDescriptor::new(apk.try_clone()?),
2082 &ParcelFileDescriptor::new(idsig.try_clone()?),
2083 )?;
2084 let modified_orig = idsig.metadata()?.modified()?;
2085 apk.rewind()?;
2086 idsig.rewind()?;
2087
2088 // Call the function again
2089 create_or_update_idsig_file(
2090 &ParcelFileDescriptor::new(apk.try_clone()?),
2091 &ParcelFileDescriptor::new(idsig.try_clone()?),
2092 )?;
2093 let modified_new = idsig.metadata()?.modified()?;
2094 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2095 Ok(())
2096 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002097
2098 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002099 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2100 use std::io::Read;
2101
2102 // Pick any APK
2103 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2104 let idsig_empty = tempfile::tempfile().unwrap();
2105 let mut idsig_invalid = tempfile::tempfile().unwrap();
2106 idsig_invalid.write_all(b"Oops")?;
2107
2108 // Create new idsig
2109 create_or_update_idsig_file(
2110 &ParcelFileDescriptor::new(apk.try_clone()?),
2111 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2112 )?;
2113 apk.rewind()?;
2114
2115 // Update idsig_invalid
2116 create_or_update_idsig_file(
2117 &ParcelFileDescriptor::new(apk.try_clone()?),
2118 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2119 )?;
2120
2121 // Ensure the 2 idsig files have same size!
2122 assert!(
2123 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2124 "idsig files differ in size"
2125 );
2126 // Ensure the 2 idsig files have same content!
2127 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2128 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2129 }
2130 Ok(())
2131 }
2132 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002133 fn test_append_kernel_param_first_param() {
2134 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2135 append_kernel_param("foo=1", &mut vm_config);
2136 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2137 }
2138
2139 #[test]
2140 fn test_append_kernel_param() {
2141 let mut vm_config =
2142 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2143 append_kernel_param("bar=42", &mut vm_config);
2144 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2145 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002146
Inseob Kim46257382024-01-03 15:41:22 +09002147 fn test_extract_os_name_from_config_path(
2148 path: &Path,
2149 expected_result: Option<&str>,
2150 ) -> Result<()> {
2151 let result = extract_os_name_from_config_path(path);
2152 if result.as_deref() != expected_result {
2153 bail!("Expected {:?} but was {:?}", expected_result, &result)
2154 }
2155 Ok(())
2156 }
2157
2158 #[test]
2159 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2160 test_extract_os_name_from_config_path(
2161 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2162 Some("microdroid"),
2163 )
2164 }
2165
2166 #[test]
2167 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2168 test_extract_os_name_from_config_path(
2169 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2170 Some("microdroid_gki-android14-6.1"),
2171 )
2172 }
2173
2174 #[test]
2175 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2176 test_extract_os_name_from_config_path(
2177 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2178 None,
2179 )
2180 }
2181
2182 #[test]
2183 fn test_extract_os_name_from_configs() -> Result<()> {
2184 let tmp_dir = tempfile::TempDir::new()?;
2185 let tmp_dir_path = tmp_dir.path().to_owned();
2186
2187 let mut os_names: HashSet<String> = HashSet::new();
2188 os_names.insert("microdroid".to_owned());
2189 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2190 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2191
2192 // config files
2193 for os_name in &os_names {
2194 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2195 }
2196
2197 // fake files not related to configs
2198 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2199 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2200
2201 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2202 Some(s) => s.to_owned(),
2203 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2204 };
2205
2206 let result = extract_os_names_from_configs(&glob_pattern)?;
2207 if result != os_names {
2208 bail!("Expected {:?} but was {:?}", os_names, result);
2209 }
2210 Ok(())
2211 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002212
2213 #[test]
2214 fn test_find_early_vms_from_xml() -> Result<()> {
2215 let tmp_dir = tempfile::TempDir::new()?;
2216 let tmp_dir_path = tmp_dir.path().to_owned();
2217 let xml_path = tmp_dir_path.join("early_vms.xml");
2218
2219 std::fs::write(
2220 &xml_path,
2221 br#"<?xml version="1.0" encoding="utf-8"?>
2222 <early_vms>
2223 <early_vm>
2224 <name>vm_demo_native_early</name>
2225 <cid>123</cid>
2226 <path>/system/bin/vm_demo_native_early</path>
2227 </early_vm>
2228 <early_vm>
2229 <name>vm_demo_duplicated_name</name>
2230 <cid>456</cid>
2231 <path>/system/bin/vm_demo_duplicated_name_1</path>
2232 </early_vm>
2233 <early_vm>
2234 <name>vm_demo_duplicated_name</name>
2235 <cid>789</cid>
2236 <path>/system/bin/vm_demo_duplicated_name_2</path>
2237 </early_vm>
2238 <early_vm>
2239 <name>vm_demo_invalid_cid_1</name>
2240 <cid>-1</cid>
2241 <path>/system/bin/vm_demo_invalid_cid_1</path>
2242 </early_vm>
2243 <early_vm>
2244 <name>vm_demo_invalid_cid_2</name>
2245 <cid>999999</cid>
2246 <path>/system/bin/vm_demo_invalid_cid_2</path>
2247 </early_vm>
2248 </early_vms>
2249 "#,
2250 )?;
2251
2252 let cid_range = 100..1000;
2253
2254 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2255 let expected = EarlyVm {
2256 name: "vm_demo_native_early".to_owned(),
2257 cid: 123,
2258 path: "/system/bin/vm_demo_native_early".to_owned(),
2259 };
2260 assert_eq!(result, expected);
2261
2262 assert!(
2263 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2264 "should fail"
2265 );
2266 assert!(
2267 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2268 "should fail"
2269 );
2270 assert!(
2271 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2272 "should fail"
2273 );
2274
2275 Ok(())
2276 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002277}