blob: 7f98fe87ff691a510838d5d905de61521d2ebe71 [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
David Brazdil1f530702022-10-03 12:18:10 +010017use crate::{get_calling_pid, get_calling_uid};
David Brazdil49f96f52022-12-16 21:29:13 +000018use crate::atom::{
David Brazdil49f96f52022-12-16 21:29:13 +000019 write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020use crate::composite::make_composite_image;
Inseob Kim7307a892023-09-14 13:37:58 +090021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VfioDevice, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090022use crate::debug_config::DebugConfig;
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,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010035 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000036 IVirtualMachineCallback::IVirtualMachineCallback,
37 IVirtualizationService::IVirtualizationService,
Alan Stokes27f3ef02023-09-29 15:09:35 +010038 IVirtualizationService::FEATURE_MULTI_TENANT,
Nikita Ioffe631717e2023-09-05 13:38:07 +010039 IVirtualizationService::FEATURE_VENDOR_MODULES,
Alan Stokes7f27c0d2023-09-07 16:22:58 +010040 IVirtualizationService::FEATURE_DICE_CHANGES,
Keir Frasercdd4b112022-11-24 14:02:25 +000041 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090042 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090044 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010047 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090048 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000049 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090050};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
Alan Stokes25f69362023-03-06 16:51:54 +000055use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090056use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090057use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010058use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000059 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
60 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090061 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000062};
David Brazdilf50c7a62023-04-19 14:22:42 +000063use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000064use lazy_static::lazy_static;
Seungjae Yooec3bc522023-11-09 10:14:30 +090065use libfdt::Fdt;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000066use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090067use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090068use nix::unistd::pipe;
Inseob Kim7a1fc8f2023-11-22 18:45:28 +090069use regex::Regex;
David Brazdil73988ea2022-11-11 15:10:32 +000070use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000071use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090072use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090073use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000074use std::convert::TryInto;
Seungjae Yooec3bc522023-11-09 10:14:30 +090075use std::ffi::{CStr, CString};
Inseob Kim6ef80972023-07-20 17:23:36 +090076use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000077use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000078use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000079use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000080use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000082use std::sync::{Arc, Mutex, Weak};
Seungjae Yooec3bc522023-11-09 10:14:30 +090083use vbmeta::VbMetaImage;
Andrew Walbrancc0db522021-07-12 17:03:42 +000084use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000085use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090086use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087
David Brazdil41d1a872022-10-05 14:44:19 +010088/// The unique ID of a VM used (together with a port number) for vsock communication.
89pub type Cid = u32;
90
David Brazdil4b4c5102022-12-19 22:56:20 +000091pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
92
Jooyung Han95884632021-07-06 22:27:54 +090093/// The size of zero.img.
94/// Gaps in composite disk images are filled with a shared zero.img.
95const ZERO_FILLER_SIZE: u64 = 4096;
96
David Brazdilf50c7a62023-04-19 14:22:42 +000097/// Magic string for the instance image
98const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
99
100/// Version of the instance image format
101const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
102
Alan Stokes0d1ef782022-09-27 13:46:35 +0100103const MICRODROID_OS_NAME: &str = "microdroid";
104
David Brazdilf50c7a62023-04-19 14:22:42 +0000105const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
106
Seungjae Yooec3bc522023-11-09 10:14:30 +0900107/// Roughly estimated sufficient size for storing vendor public key into DTBO.
108const EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE: usize = 10000;
109
David Brazdilf50c7a62023-04-19 14:22:42 +0000110/// crosvm requires all partitions to be a multiple of 4KiB.
111const PARTITION_GRANULARITY_BYTES: u64 = 4096;
112
David Brazdil49f96f52022-12-16 21:29:13 +0000113lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000114 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
115 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
116 .expect("Could not connect to VirtualizationServiceInternal");
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900117 static ref MICRODROID_GKI_OS_NAME_PATTERN: Regex =
Inseob Kim0276f612023-12-07 17:25:18 +0900118 Regex::new(r"^microdroid_gki-android\d+-\d+\.\d+$").expect("Failed to construct Regex");
David Brazdil49f96f52022-12-16 21:29:13 +0000119}
120
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000121fn create_or_update_idsig_file(
122 input_fd: &ParcelFileDescriptor,
123 idsig_fd: &ParcelFileDescriptor,
124) -> Result<()> {
125 let mut input = clone_file(input_fd)?;
126 let metadata = input.metadata().context("failed to get input metadata")?;
127 if !metadata.is_file() {
128 bail!("input is not a regular file");
129 }
Alan Stokes25f69362023-03-06 16:51:54 +0000130 let mut sig =
131 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
132 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000133
134 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900135
136 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
137 // if the idsig file already has the same APK digest.
138 if output.metadata()?.len() > 0 {
139 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
140 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
141 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
142 return Ok(());
143 }
144 }
145 // if we fail to read v4signature from output, that's fine. User can pass a random file.
146 // We will anyway overwrite the file to the v4signature generated from input_fd.
147 }
148
Nikita Ioffec09b0492022-12-14 20:18:33 +0000149 output.set_len(0).context("failed to set_len on the idsig output")?;
150 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000151 Ok(())
152}
153
Alan Stokes25f69362023-03-06 16:51:54 +0000154fn get_current_sdk() -> Result<u32> {
155 let current_sdk = system_properties::read("ro.build.version.sdk")?;
156 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
157 current_sdk.parse().context("Malformed SDK version")
158}
159
David Brazdil4b4c5102022-12-19 22:56:20 +0000160pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
161 for dir_entry in read_dir(path)? {
162 remove_file(dir_entry?.path())?;
163 }
164 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100165}
166
David Brazdil528e0472022-10-10 15:06:02 +0100167/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000168#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000169pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900170 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000171}
172
Shikha Panward8e35422021-10-11 13:51:27 +0000173impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000174 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000175 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
176 let state = &mut *self.state.lock().unwrap();
177 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000178 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000179 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000180 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
181 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000182 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000183 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000184 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000185 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
186 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000187 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000188 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000189 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000190 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000191 .or(Err(StatusCode::UNKNOWN_ERROR))?;
192 }
193 Ok(())
194 }
195}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000196impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000197 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
198 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000199 ///
200 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000201 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000202 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000203 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900204 console_out_fd: Option<&ParcelFileDescriptor>,
205 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000206 log_fd: Option<&ParcelFileDescriptor>,
207 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000208 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900209 let ret = self.create_vm_internal(
210 config,
211 console_out_fd,
212 console_in_fd,
213 log_fd,
214 &mut is_protected,
215 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000216 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000217 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000218 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000219
Andrew Walbrandff3b942021-06-09 15:20:36 +0000220 /// Initialise an empty partition image of the given size to be used as a writable partition.
221 fn initializeWritablePartition(
222 &self,
223 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000224 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900225 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000226 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900227 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900228 let size_bytes = size_bytes
229 .try_into()
230 .with_context(|| format!("Invalid size: {}", size_bytes))
231 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000232 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
233 let image = clone_file(image_fd)?;
234 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900235 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
236 let mut part = QcowFile::new(image, size_bytes)
237 .context("Failed to create QCOW2 image")
238 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000239
240 match partition_type {
241 PartitionType::RAW => Ok(()),
242 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
243 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
244 _ => Err(Error::new(
245 ErrorKind::Unsupported,
246 format!("Unsupported partition type {:?}", partition_type),
247 )),
248 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900249 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
250 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000251
252 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000253 }
254
Jiyong Park0a248432021-08-20 23:32:39 +0900255 /// Creates or update the idsig file by digesting the input APK file.
256 fn createOrUpdateIdsigFile(
257 &self,
258 input_fd: &ParcelFileDescriptor,
259 idsig_fd: &ParcelFileDescriptor,
260 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900261 check_manage_access()?;
262
Jiyong Park2227eaa2023-08-04 11:59:18 +0900263 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900264 Ok(())
265 }
266
Andrew Walbran320b5602021-03-04 16:11:12 +0000267 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
268 /// and as such is only permitted from the shell user.
269 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000270 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000271 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000272 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900273
274 /// Get a list of assignable device types.
275 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
276 // Delegate to the global service, including checking the permission.
277 GLOBAL_SERVICE.getAssignableDevices()
278 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100279
280 /// Returns whether given feature is enabled
281 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
282 check_manage_access()?;
283
284 // This approach is quite cumbersome, but will do the work for the short term.
285 // TODO(b/298012279): make this scalable.
286 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100287 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100288 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100289 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100290 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100291 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100292 Ok(false)
293 }
294 }
295 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000296}
297
Jiyong Park8611a6c2021-07-09 18:17:44 +0900298impl VirtualizationService {
299 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000300 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900301 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000302
David Brazdil209074a2023-01-12 16:44:51 +0000303 fn create_vm_context(
304 &self,
305 requester_debug_pid: pid_t,
306 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000307 const NUM_ATTEMPTS: usize = 5;
308
309 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000310 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000311 let cid = vm_context.getCid()? as Cid;
312 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000313 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
314
315 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000316 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000317 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000318 Ok(vm_server) => {
319 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000320 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000321 }
322 Err(err) => {
323 warn!("Could not start RpcServer on port {}: {}", port, err);
324 }
325 }
326 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900327 Err(anyhow!("Too many attempts to create VM context failed"))
328 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000329 }
330
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000331 fn create_vm_internal(
332 &self,
333 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900334 console_out_fd: Option<&ParcelFileDescriptor>,
335 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000336 log_fd: Option<&ParcelFileDescriptor>,
337 is_protected: &mut bool,
338 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000339 let requester_uid = get_calling_uid();
340 let requester_debug_pid = get_calling_pid();
341
Nikita Ioffe631717e2023-09-05 13:38:07 +0100342 check_config_features(config)?;
343
David Brazdil209074a2023-01-12 16:44:51 +0000344 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
345 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900346
Alan Stokes7bc146c2022-10-20 17:10:32 +0100347 let is_custom = match config {
348 VirtualMachineConfig::RawConfig(_) => true,
349 VirtualMachineConfig::AppConfig(config) => {
350 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100351 // VirtualMachineAppConfig. Almost all of these features are grouped in the
352 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100353 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100354 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100355 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900356 // - using anything other than the default kernel;
357 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100358 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900359 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100360 };
361 if is_custom {
362 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900363 }
364
Nikita Ioffe5776f082023-02-10 21:38:26 +0000365 let gdb_port = extract_gdb_port(config);
366
367 // Additional permission checks if caller request gdb.
368 if gdb_port.is_some() {
369 check_gdb_allowed(config)?;
370 }
371
Seungjae Yooec3bc522023-11-09 10:14:30 +0900372 let vendor_public_key = extract_vendor_public_key(config)
373 .context("Failed to extract vendor public key")
374 .or_service_specific_exception(-1)?;
375 let dtbo_vendor = if let Some(vendor_public_key) = vendor_public_key {
376 let dtbo_for_vendor_image = temporary_directory.join("dtbo_vendor");
377 create_dtbo_for_vendor_image(&vendor_public_key, &dtbo_for_vendor_image)
378 .context("Failed to write vendor_public_key")
379 .or_service_specific_exception(-1)?;
380 let file = File::open(dtbo_for_vendor_image)
381 .context("Failed to open dtbo_vendor")
382 .or_service_specific_exception(-1)?;
383 Some(file)
384 } else {
385 None
386 };
387
Jaewan Kim61f86142023-03-28 15:12:52 +0900388 let debug_level = match config {
389 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
390 _ => DebugLevel::NONE,
391 };
392 let debug_config = DebugConfig::new(debug_level);
393
394 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900395 Some(prepare_ramdump_file(&temporary_directory)?)
396 } else {
397 None
398 };
399
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000400 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900401 let console_out_fd =
402 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
403 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900404 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000405
406 // Counter to generate unique IDs for temporary image files.
407 let mut next_temporary_image_id = 0;
408 // Files which are referred to from composite images. These must be mapped to the crosvm
409 // child process, and not closed before it is started.
410 let mut indirect_files = vec![];
411
Alan Stokes7bc146c2022-10-20 17:10:32 +0100412 let (is_app_config, config) = match config {
413 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
414 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900415 let config = load_app_config(config, &debug_config, &temporary_directory)
416 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900417 *is_protected = config.protectedVm;
418 let message = format!("Failed to load app config: {:?}", e);
419 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900420 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900421 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100422 (true, BorrowedOrOwned::Owned(config))
423 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000424 };
425 let config = config.as_ref();
426 *is_protected = config.protectedVm;
427
428 // Check if partition images are labeled incorrectly. This is to prevent random images
429 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100430 // being loaded in a pVM. This applies to everything but the instance image in the raw
431 // config, and everything but the non-executable, generated partitions in the app
432 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000433 config
434 .disks
435 .iter()
436 .flat_map(|disk| disk.partitions.iter())
437 .filter(|partition| {
438 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100439 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000440 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000441 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000442 }
443 })
444 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900445 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000446
Alan Stokes185fe112023-01-10 16:20:55 +0000447 let kernel = maybe_clone_file(&config.kernel)?;
448 let initrd = maybe_clone_file(&config.initrd)?;
449
450 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
451 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900452 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000453 }
454
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000455 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900456 write_zero_filler(&zero_filler_path)
457 .context("Failed to make composite image")
458 .with_log()
459 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000460
461 // Assemble disk images if needed.
462 let disks = config
463 .disks
464 .iter()
465 .map(|disk| {
466 assemble_disk_image(
467 disk,
468 &zero_filler_path,
469 &temporary_directory,
470 &mut next_temporary_image_id,
471 &mut indirect_files,
472 )
473 })
474 .collect::<Result<Vec<DiskFile>, _>>()?;
475
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000476 let (cpus, host_cpu_topology) = match config.cpuTopology {
477 CpuTopology::MATCH_HOST => (None, true),
478 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
479 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900480 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
481 .with_log()
482 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000483 }
484 };
485
David Brazdil2dfefd12023-11-17 14:07:36 +0000486 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900487 let mut set = HashSet::new();
488 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900489 let path = canonicalize(device)
490 .with_context(|| format!("can't canonicalize {device}"))
491 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900492 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900493 return Err(anyhow!("duplicated device {device}"))
494 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900495 }
496 }
David Brazdil2dfefd12023-11-17 14:07:36 +0000497 let devices = GLOBAL_SERVICE
Inseob Kim7307a892023-09-14 13:37:58 +0900498 .bindDevicesToVfioDriver(&config.devices)?
499 .into_iter()
500 .map(|x| VfioDevice {
501 sysfs_path: PathBuf::from(&x.sysfsPath),
Jaewan Kim35e818d2023-10-18 05:36:38 +0000502 dtbo_label: x.dtboLabel,
Inseob Kim7307a892023-09-14 13:37:58 +0900503 })
David Brazdil2dfefd12023-11-17 14:07:36 +0000504 .collect::<Vec<_>>();
505 let dtbo_file = File::from(
506 GLOBAL_SERVICE
507 .getDtboFile()?
508 .as_ref()
509 .try_clone()
510 .context("Failed to create File from ParcelFileDescriptor")
511 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
512 );
513 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900514 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000515 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900516 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900517
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000518 // Actually start the VM.
519 let crosvm_config = CrosvmConfig {
520 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000521 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000522 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000523 kernel,
524 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000525 disks,
526 params: config.params.to_owned(),
527 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900528 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000529 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000530 cpus,
531 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900532 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900533 console_out_fd,
534 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000535 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900536 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000537 indirect_files,
538 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900539 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000540 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900541 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000542 dtbo,
Seungjae Yooec3bc522023-11-09 10:14:30 +0900543 dtbo_vendor,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000544 };
545 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100546 VmInstance::new(
547 crosvm_config,
548 temporary_directory,
549 requester_uid,
550 requester_debug_pid,
551 vm_context,
552 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900553 .with_context(|| format!("Failed to create VM with config {:?}", config))
554 .with_log()
555 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000556 );
557 state.add_vm(Arc::downgrade(&instance));
558 Ok(VirtualMachine::create(instance))
559 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900560}
561
Seungjae Yooec3bc522023-11-09 10:14:30 +0900562fn extract_vendor_public_key(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
563 let VirtualMachineConfig::AppConfig(config) = config else {
564 return Ok(None);
565 };
566 let Some(custom_config) = &config.customConfig else {
567 return Ok(None);
568 };
569 let Some(file) = custom_config.vendorImage.as_ref() else {
570 return Ok(None);
571 };
572
573 let file = clone_file(file)?;
574 let size = file.metadata().context("Failed to get metadata from microdroid-vendor.img")?.len();
575 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
576 .context("Failed to get vbmeta from microdroid-vendor.img")?;
577 let vendor_public_key = vbmeta
578 .public_key()
579 .ok_or(anyhow!("No public key is extracted from microdroid-vendor.img"))?
580 .to_vec();
581
582 Ok(Some(vendor_public_key))
583}
584
585fn create_dtbo_for_vendor_image(vendor_public_key: &[u8], dtbo: &PathBuf) -> Result<()> {
586 if dtbo.exists() {
587 return Err(anyhow!("DTBO file already exists"));
588 }
589
590 let mut buf = vec![0; EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE];
591 let fdt = Fdt::create_empty_tree(buf.as_mut_slice())
592 .map_err(|e| anyhow!("Failed to create FDT: {:?}", e))?;
593 let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to get root node: {:?}", e))?;
594
595 let fragment_node_name = CString::new("fragment@0")?;
596 let mut fragment_node = root
597 .add_subnode(fragment_node_name.as_c_str())
598 .map_err(|e| anyhow!("Failed to create fragment node: {:?}", e))?;
599 let target_path_prop_name = CString::new("target-path")?;
600 let target_path = CString::new("/")?;
601 fragment_node
602 .setprop(target_path_prop_name.as_c_str(), target_path.to_bytes_with_nul())
603 .map_err(|e| anyhow!("Failed to set target-path: {:?}", e))?;
604 let overlay_node_name = CString::new("__overlay__")?;
605 let mut overlay_node = fragment_node
606 .add_subnode(overlay_node_name.as_c_str())
607 .map_err(|e| anyhow!("Failed to create overlay node: {:?}", e))?;
608
609 let avf_node_name = CString::new("avf")?;
610 let mut avf_node = overlay_node
611 .add_subnode(avf_node_name.as_c_str())
612 .map_err(|e| anyhow!("Failed to create avf node: {:?}", e))?;
613 let vendor_public_key_name = CString::new("vendor_public_key")?;
614 avf_node
615 .setprop(vendor_public_key_name.as_c_str(), vendor_public_key)
616 .map_err(|e| anyhow!("Failed to set avf/vendor_public_key: {:?}", e))?;
617
618 fdt.pack().map_err(|e| anyhow!("Failed to pack fdt: {:?}", e))?;
619 let mut file = File::create(dtbo)?;
620 file.write_all(fdt.as_slice())?;
621 Ok(file.flush()?)
622}
623
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000624fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900625 let file = OpenOptions::new()
626 .create_new(true)
627 .read(true)
628 .write(true)
629 .open(zero_filler_path)
630 .with_context(|| "Failed to create zero.img")?;
631 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000632 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900633}
634
David Brazdilf50c7a62023-04-19 14:22:42 +0000635fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
636 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
637 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
638 part.flush()
639}
640
641fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
642 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
643 part.flush()
644}
645
646fn round_up(input: u64, granularity: u64) -> u64 {
647 if granularity == 0 {
648 return input;
649 }
650 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
651 let result = input.checked_add(granularity - 1).unwrap_or(input);
652 (result / granularity) * granularity
653}
654
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000655/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
656///
657/// This may involve assembling a composite disk from a set of partition images.
658fn assemble_disk_image(
659 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900660 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000661 temporary_directory: &Path,
662 next_temporary_image_id: &mut u64,
663 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000664) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000665 let image = if !disk.partitions.is_empty() {
666 if disk.image.is_some() {
667 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900668 return Err(anyhow!("DiskImage contains both image and partitions"))
669 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000670 }
671
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000672 let composite_image_filenames =
673 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
674 let (image, partition_files) = make_composite_image(
675 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900676 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000677 &composite_image_filenames.composite,
678 &composite_image_filenames.header,
679 &composite_image_filenames.footer,
680 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900681 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
682 .with_log()
683 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000684
685 // Pass the file descriptors for the various partition files to crosvm when it
686 // is run.
687 indirect_files.extend(partition_files);
688
689 image
690 } else if let Some(image) = &disk.image {
691 clone_file(image)?
692 } else {
693 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900694 return Err(anyhow!("DiskImage didn't contain image or partitions."))
695 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696 };
697
698 Ok(DiskFile { image, writable: disk.writable })
699}
700
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100701fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
702 if let Some(ref mut params) = vm_config.params {
703 params.push(' ');
704 params.push_str(param)
705 } else {
706 vm_config.params = Some(param.to_owned())
707 }
708}
709
Inseob Kim172f9eb2023-11-06 17:02:08 +0900710fn is_valid_os(os_name: &str) -> bool {
711 if os_name == MICRODROID_OS_NAME {
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900712 true
713 } else if cfg!(vendor_modules) && MICRODROID_GKI_OS_NAME_PATTERN.is_match(os_name) {
714 PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)).exists()
715 } else {
716 false
Inseob Kim172f9eb2023-11-06 17:02:08 +0900717 }
Inseob Kim172f9eb2023-11-06 17:02:08 +0900718}
719
Jooyung Han21e9b922021-06-26 04:14:16 +0900720fn load_app_config(
721 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900722 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900723 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900724) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000725 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
726 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900727 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900728
Shikha Panwar22e70452022-10-10 18:32:55 +0000729 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
730 Some(clone_file(file)?)
731 } else {
732 None
733 };
734
Alan Stokes0d1ef782022-09-27 13:46:35 +0100735 let vm_payload_config = match &config.payload {
736 Payload::ConfigPath(config_path) => {
737 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
738 .with_context(|| format!("Couldn't read config from {}", config_path))?
739 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000740 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100741 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900742
Inseob Kim172f9eb2023-11-06 17:02:08 +0900743 // For now, the only supported OS is Microdroid and Microdroid GKI
Alan Stokes0d1ef782022-09-27 13:46:35 +0100744 let os_name = vm_payload_config.os.name.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +0900745 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000746 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900747 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000748
749 // It is safe to construct a filename based on the os_name because we've already checked that it
750 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900751 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
752 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000753 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900754
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100755 if let Some(custom_config) = &config.customConfig {
756 if let Some(file) = custom_config.customKernelImage.as_ref() {
757 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
758 }
759 vm_config.taskProfiles = custom_config.taskProfiles.clone();
760 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100761
762 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100763 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
764 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100765 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900766
767 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100768 }
769
Andrew Walbrancc045902021-07-27 16:06:17 +0000770 if config.memoryMib > 0 {
771 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000772 }
773
Seungjae Yoo62085c02022-08-12 04:44:52 +0000774 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000775 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000776 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900777
Shikha Panwar22e70452022-10-10 18:32:55 +0000778 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +0900779 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +0000780
781 // Include Microdroid payload disk (contains apks, idsigs) in vm config
782 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100783 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900784 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100785 temporary_directory,
786 apk_file,
787 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100788 &vm_payload_config,
789 &mut vm_config,
790 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900791
Andrew Walbrancc0db522021-07-12 17:03:42 +0000792 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900793}
794
Alan Stokes0d1ef782022-09-27 13:46:35 +0100795fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
796 let mut apk_zip = ZipArchive::new(apk_file)?;
797 let config_file = apk_zip.by_name(config_path)?;
798 Ok(serde_json::from_reader(config_file)?)
799}
800
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000801fn create_vm_payload_config(
802 payload_config: &VirtualMachinePayloadConfig,
803) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100804 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
805 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
806 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000807
808 let payload_binary_name = &payload_config.payloadBinaryName;
809 if payload_binary_name.contains('/') {
810 bail!("Payload binary name must not specify a path: {payload_binary_name}");
811 }
812
813 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Inseob Kim172f9eb2023-11-06 17:02:08 +0900814 let name = payload_config.osName.clone();
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000815 Ok(VmPayloadConfig {
Inseob Kim172f9eb2023-11-06 17:02:08 +0900816 os: OsConfig { name },
Alan Stokes0d1ef782022-09-27 13:46:35 +0100817 task: Some(task),
818 apexes: vec![],
819 extra_apks: vec![],
820 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900821 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100822 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000823 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100824}
825
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000826/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000827fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000828 temporary_directory: &Path,
829 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000830) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000831 let id = *next_temporary_image_id;
832 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000833 CompositeImageFilenames {
834 composite: temporary_directory.join(format!("composite-{}.img", id)),
835 header: temporary_directory.join(format!("composite-{}-header.img", id)),
836 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
837 }
838}
839
840/// Filenames for a composite disk image, including header and footer partitions.
841#[derive(Clone, Debug, Eq, PartialEq)]
842struct CompositeImageFilenames {
843 /// The composite disk image itself.
844 composite: PathBuf,
845 /// The header partition image.
846 header: PathBuf,
847 /// The footer partition image.
848 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000849}
850
Jiyong Park753553b2021-07-12 21:21:09 +0900851/// Checks whether the caller has a specific permission
852fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100853 let calling_pid = get_calling_pid();
854 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900855 // Root can do anything
856 if calling_uid == 0 {
857 return Ok(());
858 }
859 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
860 binder::get_interface("permission")?;
861 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000862 Ok(())
863 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900864 Err(anyhow!("does not have the {} permission", perm))
865 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000866 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000867}
868
Jiyong Park753553b2021-07-12 21:21:09 +0900869/// Check whether the caller of the current Binder method is allowed to manage VMs
870fn check_manage_access() -> binder::Result<()> {
871 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
872}
873
Inseob Kim1119d702022-05-02 18:01:58 +0900874/// Check whether the caller of the current Binder method is allowed to create custom VMs
875fn check_use_custom_virtual_machine() -> binder::Result<()> {
876 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
877}
878
Alan Stokes185fe112023-01-10 16:20:55 +0000879/// Return whether a partition is exempt from selinux label checks, because we know that it does
880/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100881fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000882 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100883 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000884 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100885 || label == "microdroid-apk-idsig"
886 || label == "payload-metadata"
887 || label.starts_with("extra-idsig-")
888}
889
Alice Wangc206b9b2023-08-28 14:13:51 +0000890/// Returns whether a partition with the given label is safe for a raw config VM.
891fn is_safe_raw_partition(label: &str) -> bool {
892 label == "vm-instance"
893}
894
Alan Stokes185fe112023-01-10 16:20:55 +0000895/// Check that a file SELinux label is acceptable.
896///
897/// 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 +0900898/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +0000899///
900/// Note that sepolicy must also grant read access for these types to both virtualization
901/// service and crosvm.
902///
903/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
904/// user devices (W^X).
905fn check_label_is_allowed(context: &SeContext) -> Result<()> {
906 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100907 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100908 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000909 | "staging_data_file" // updated/staged APEX images
910 | "system_file" // immutable dm-verity protected partition
911 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +0900912 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100913 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000914 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900915 }
916}
917
Alan Stokes185fe112023-01-10 16:20:55 +0000918fn check_label_for_partition(partition: &Partition) -> Result<()> {
919 let file = partition.image.as_ref().unwrap().as_ref();
920 check_label_is_allowed(&getfilecon(file)?)
921 .with_context(|| format!("Partition {} invalid", &partition.label))
922}
923
924fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
925 if let Some(f) = kernel {
926 check_label_for_file(f, "kernel")?;
927 }
928 if let Some(f) = initrd {
929 check_label_for_file(f, "initrd")?;
930 }
931 Ok(())
932}
933fn check_label_for_file(file: &File, name: &str) -> Result<()> {
934 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
935}
936
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000937/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
938#[derive(Debug)]
939struct VirtualMachine {
940 instance: Arc<VmInstance>,
941}
942
943impl VirtualMachine {
944 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000945 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000946 }
947}
948
949impl Interface for VirtualMachine {}
950
951impl IVirtualMachine for VirtualMachine {
952 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900953 // Don't check permission. The owner of the VM might have passed this binder object to
954 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000955 Ok(self.instance.cid as i32)
956 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000957
Andrew Walbran6b650662021-09-07 13:13:23 +0000958 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900959 // Don't check permission. The owner of the VM might have passed this binder object to
960 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000961 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000962 }
963
964 fn registerCallback(
965 &self,
966 callback: &Strong<dyn IVirtualMachineCallback>,
967 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900968 // Don't check permission. The owner of the VM might have passed this binder object to
969 // others.
970 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000971 // TODO: Should this give an error if the VM is already dead?
972 self.instance.callbacks.add(callback.clone());
973 Ok(())
974 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000975
Andrew Walbranf8d94112021-09-07 11:45:36 +0000976 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900977 self.instance
978 .start()
979 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
980 .with_log()
981 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000982 }
983
Inseob Kima446f802022-07-11 19:46:37 +0900984 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900985 self.instance
986 .kill()
987 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
988 .with_log()
989 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900990 }
991
Keir Frasercdd4b112022-11-24 14:02:25 +0000992 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900993 self.instance
994 .trim_memory(level)
995 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
996 .with_log()
997 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000998 }
999
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001000 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001001 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001002 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001003 }
Alan Stokes10c47672022-12-13 17:17:08 +00001004 let port = port as u32;
1005 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001006 return Err(anyhow!("Can't connect to privileged port {port}"))
1007 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001008 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001009 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1010 .context("Failed to connect")
1011 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001012 Ok(vsock_stream_to_pfd(stream))
1013 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001014}
1015
1016impl Drop for VirtualMachine {
1017 fn drop(&mut self) {
1018 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001019 if let Err(e) = self.instance.kill() {
1020 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1021 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001022 }
1023}
1024
1025/// A set of Binders to be called back in response to various events on the VM, such as when it
1026/// dies.
1027#[derive(Debug, Default)]
1028pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1029
1030impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001031 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001032 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001033 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001034 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001035 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001036 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001037 }
1038 }
1039 }
1040
Inseob Kim14cb8692021-08-31 21:50:39 +09001041 /// Call all registered callbacks to notify that the payload is ready to serve.
1042 pub fn notify_payload_ready(&self, cid: Cid) {
1043 let callbacks = &*self.0.lock().unwrap();
1044 for callback in callbacks {
1045 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001046 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001047 }
1048 }
1049 }
1050
Inseob Kim2444af92021-08-31 01:22:50 +09001051 /// Call all registered callbacks to notify that the payload has finished.
1052 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1053 let callbacks = &*self.0.lock().unwrap();
1054 for callback in callbacks {
1055 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001056 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001057 }
1058 }
1059 }
1060
Jooyung Handd0a1732021-11-23 15:26:20 +09001061 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001062 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001063 let callbacks = &*self.0.lock().unwrap();
1064 for callback in callbacks {
1065 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001066 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001067 }
1068 }
1069 }
1070
Andrew Walbrandae07162021-03-12 17:05:20 +00001071 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001072 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001073 let callbacks = &*self.0.lock().unwrap();
1074 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001075 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001076 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001077 }
1078 }
1079 }
1080
1081 /// Add a new callback to the set.
1082 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1083 self.0.lock().unwrap().push(callback);
1084 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001085}
1086
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001087/// The mutable state of the VirtualizationService. There should only be one instance of this
1088/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001089#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001090struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001091 /// The VMs which have been started. When VMs are started a weak reference is added to this
1092 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1093 /// the Binder client are dropped the weak reference here will become invalid, and will be
1094 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001095 vms: Vec<Weak<VmInstance>>,
1096}
1097
1098impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001099 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001100 fn vms(&self) -> Vec<Arc<VmInstance>> {
1101 // Attempt to upgrade the weak pointers to strong pointers.
1102 self.vms.iter().filter_map(Weak::upgrade).collect()
1103 }
1104
1105 /// Add a new VM to the list.
1106 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1107 // Garbage collect any entries from the stored list which no longer exist.
1108 self.vms.retain(|vm| vm.strong_count() > 0);
1109
1110 // Actually add the new VM.
1111 self.vms.push(vm);
1112 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001113
Jiyong Park8611a6c2021-07-09 18:17:44 +09001114 /// Get a VM that corresponds to the given cid
1115 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1116 self.vms().into_iter().find(|vm| vm.cid == cid)
1117 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001118}
1119
Andrew Walbran6b650662021-09-07 13:13:23 +00001120/// Gets the `VirtualMachineState` of the given `VmInstance`.
1121fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001122 match &*instance.vm_state.lock().unwrap() {
1123 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1124 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001125 PayloadState::Starting => VirtualMachineState::STARTING,
1126 PayloadState::Started => VirtualMachineState::STARTED,
1127 PayloadState::Ready => VirtualMachineState::READY,
1128 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001129 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001130 },
1131 VmState::Dead => VirtualMachineState::DEAD,
1132 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001133 }
1134}
1135
David Brazdilf50c7a62023-04-19 14:22:42 +00001136/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001137pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1138 file.as_ref()
1139 .try_clone()
1140 .context("Failed to clone File from ParcelFileDescriptor")
1141 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001142 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001143}
1144
Andrew Walbrand3a84182021-09-07 14:48:52 +00001145/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001146fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001147 file.as_ref().map(clone_file).transpose()
1148}
1149
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001150/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1151fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1152 // SAFETY: ownership is transferred from stream to f
1153 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1154 ParcelFileDescriptor::new(f)
1155}
1156
Jiyong Parkdcf17412022-02-08 15:07:23 +09001157/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001158fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1159 VersionReq::parse(s)
1160 .with_context(|| format!("Invalid platform version requirement {}", s))
1161 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001162}
1163
Jiyong Parked180932023-02-24 19:55:41 +09001164/// Create the empty ramdump file
1165fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1166 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1167 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1168 // owner) for readout.
1169 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001170 let ramdump = File::create(ramdump_path)
1171 .context("Failed to prepare ramdump file")
1172 .with_log()
1173 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001174 Ok(ramdump)
1175}
1176
Nikita Ioffe5776f082023-02-10 21:38:26 +00001177fn is_protected(config: &VirtualMachineConfig) -> bool {
1178 match config {
1179 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1180 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1181 }
1182}
1183
1184fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1185 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001186 return Err(anyhow!("Can't use gdb with protected VMs"))
1187 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001188 }
1189
1190 match config {
1191 VirtualMachineConfig::RawConfig(_) => Ok(()),
1192 VirtualMachineConfig::AppConfig(config) => {
1193 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001194 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1195 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001196 } else {
1197 Ok(())
1198 }
1199 }
1200 }
1201}
1202
1203fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1204 match config {
1205 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001206 VirtualMachineConfig::AppConfig(config) => {
1207 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1208 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001209 }
1210}
1211
Nikita Ioffe631717e2023-09-05 13:38:07 +01001212fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1213 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1214 if let Some(custom_config) = &config.customConfig {
1215 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1216 return Err(anyhow!("vendor modules feature is disabled"))
1217 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1218 }
1219 }
1220 Ok(())
1221}
1222
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001223fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1224 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1225 if let Some(custom_config) = &config.customConfig {
1226 if !custom_config.devices.is_empty() {
1227 return Err(anyhow!("device assignment feature is disabled"))
1228 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1229 }
1230 }
1231 Ok(())
1232}
1233
Nikita Ioffe631717e2023-09-05 13:38:07 +01001234fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1235 if !cfg!(vendor_modules) {
1236 check_no_vendor_modules(config)?;
1237 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001238 if !cfg!(device_assignment) {
1239 check_no_devices(config)?;
1240 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001241 Ok(())
1242}
1243
Inseob Kim0168b462022-12-27 14:54:35 +09001244fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001245 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001246 fd: Option<&ParcelFileDescriptor>,
1247 tag: String,
1248) -> Result<Option<File>, Status> {
1249 if let Some(fd) = fd {
1250 return Ok(Some(clone_file(fd)?));
1251 }
1252
Jaewan Kim61f86142023-03-28 15:12:52 +09001253 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001254 return Ok(None);
1255 };
Inseob Kim0168b462022-12-27 14:54:35 +09001256
Jiyong Park2227eaa2023-08-04 11:59:18 +09001257 let (raw_read_fd, raw_write_fd) =
1258 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001259
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001260 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001261 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001262 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001263 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1264
1265 std::thread::spawn(move || loop {
1266 let mut buf = vec![];
1267 match reader.read_until(b'\n', &mut buf) {
1268 Ok(0) => {
1269 // EOF
1270 return;
1271 }
1272 Ok(size) => {
1273 if buf[size - 1] == b'\n' {
1274 buf.pop();
1275 }
1276 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1277 }
1278 Err(e) => {
1279 error!("Could not read console pipe: {:?}", e);
1280 return;
1281 }
1282 };
1283 });
1284
1285 Ok(Some(write_fd))
1286}
1287
Jooyung Han35edb8f2021-07-01 16:17:16 +09001288/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1289/// it doesn't require that T implements Clone.
1290enum BorrowedOrOwned<'a, T> {
1291 Borrowed(&'a T),
1292 Owned(T),
1293}
1294
1295impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1296 fn as_ref(&self) -> &T {
1297 match self {
1298 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001299 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001300 }
1301 }
1302}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001303
1304/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1305#[derive(Debug, Default)]
1306struct VirtualMachineService {
1307 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001308 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001309}
1310
1311impl Interface for VirtualMachineService {}
1312
1313impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001314 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1315 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001316 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001317 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001318 vm.update_payload_state(PayloadState::Started)
1319 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001320 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001321
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001322 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1323 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001324 Ok(())
1325 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001326 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001327 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001328 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001329 }
Inseob Kim2444af92021-08-31 01:22:50 +09001330
Inseob Kimc7d28c72021-10-25 14:28:10 +00001331 fn notifyPayloadReady(&self) -> binder::Result<()> {
1332 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001333 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001334 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001335 vm.update_payload_state(PayloadState::Ready)
1336 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001337 vm.callbacks.notify_payload_ready(cid);
1338 Ok(())
1339 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001340 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001341 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001342 }
1343 }
1344
Inseob Kimc7d28c72021-10-25 14:28:10 +00001345 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1346 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001347 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001348 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001349 vm.update_payload_state(PayloadState::Finished)
1350 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001351 vm.callbacks.notify_payload_finished(cid, exit_code);
1352 Ok(())
1353 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001354 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001355 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001356 }
1357 }
1358
Alan Stokes2bead0d2022-09-05 16:58:34 +01001359 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001360 let cid = self.cid;
1361 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001362 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001363 vm.update_payload_state(PayloadState::Finished)
1364 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001365 vm.callbacks.notify_error(cid, error_code, message);
1366 Ok(())
1367 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001368 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001369 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001370 }
1371 }
Alice Wangc2fec932023-02-23 16:24:02 +00001372
Alice Wang4e3015d2023-10-10 09:35:37 +00001373 fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> {
Alice Wangbff017f2023-11-09 14:43:28 +00001374 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32)
Alice Wangc2fec932023-02-23 16:24:02 +00001375 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001376}
1377
1378impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001379 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001380 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001381 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001382 BinderFeatures::default(),
1383 )
1384 }
1385}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001386
1387#[cfg(test)]
1388mod tests {
1389 use super::*;
1390
1391 #[test]
1392 fn test_is_allowed_label_for_partition() -> Result<()> {
1393 let expected_results = vec![
1394 ("u:object_r:system_file:s0", true),
1395 ("u:object_r:apk_data_file:s0", true),
1396 ("u:object_r:app_data_file:s0", false),
1397 ("u:object_r:app_data_file:s0:c512,c768", false),
1398 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1399 ("invalid", false),
1400 ("user:role:apk_data_file:severity:categories", true),
1401 ("user:role:apk_data_file:severity:categories:extraneous", false),
1402 ];
1403
1404 for (label, expected_valid) in expected_results {
1405 let context = SeContext::new(label)?;
1406 let result = check_label_is_allowed(&context);
1407 if expected_valid {
1408 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1409 } else if result.is_ok() {
1410 bail!("Expected label {} to be disallowed", label);
1411 }
1412 }
1413 Ok(())
1414 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001415
1416 #[test]
1417 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1418 let apk = tempfile::tempfile().unwrap();
1419 let idsig = tempfile::tempfile().unwrap();
1420
1421 let ret = create_or_update_idsig_file(
1422 &ParcelFileDescriptor::new(apk),
1423 &ParcelFileDescriptor::new(idsig),
1424 );
1425 assert!(ret.is_err(), "should fail");
1426 Ok(())
1427 }
1428
1429 #[test]
1430 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1431 let tmp_dir = tempfile::TempDir::new().unwrap();
1432 let apk = File::open(tmp_dir.path()).unwrap();
1433 let idsig = tempfile::tempfile().unwrap();
1434
1435 let ret = create_or_update_idsig_file(
1436 &ParcelFileDescriptor::new(apk),
1437 &ParcelFileDescriptor::new(idsig),
1438 );
1439 assert!(ret.is_err(), "should fail");
1440 Ok(())
1441 }
1442
1443 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1444 /// on ext4 filesystem is passed.
1445 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1446 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1447 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1448 #[test]
1449 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1450 // APEXes are backed by the ext4.
1451 let apk = File::open("/apex/com.android.virt/").unwrap();
1452 let idsig = tempfile::tempfile().unwrap();
1453
1454 let ret = create_or_update_idsig_file(
1455 &ParcelFileDescriptor::new(apk),
1456 &ParcelFileDescriptor::new(idsig),
1457 );
1458 assert!(ret.is_err(), "should fail");
1459 Ok(())
1460 }
Jiyong Park8d192952023-06-26 14:29:51 +09001461
1462 #[test]
1463 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1464 use std::io::Seek;
1465
1466 // Pick any APK
1467 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1468 let mut idsig = tempfile::tempfile().unwrap();
1469
1470 create_or_update_idsig_file(
1471 &ParcelFileDescriptor::new(apk.try_clone()?),
1472 &ParcelFileDescriptor::new(idsig.try_clone()?),
1473 )?;
1474 let modified_orig = idsig.metadata()?.modified()?;
1475 apk.rewind()?;
1476 idsig.rewind()?;
1477
1478 // Call the function again
1479 create_or_update_idsig_file(
1480 &ParcelFileDescriptor::new(apk.try_clone()?),
1481 &ParcelFileDescriptor::new(idsig.try_clone()?),
1482 )?;
1483 let modified_new = idsig.metadata()?.modified()?;
1484 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1485 Ok(())
1486 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001487
1488 #[test]
1489 fn test_append_kernel_param_first_param() {
1490 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1491 append_kernel_param("foo=1", &mut vm_config);
1492 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1493 }
1494
1495 #[test]
1496 fn test_append_kernel_param() {
1497 let mut vm_config =
1498 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1499 append_kernel_param("bar=42", &mut vm_config);
1500 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1501 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09001502
1503 #[test]
1504 fn test_create_dtbo_for_vendor_image() -> Result<()> {
1505 let vendor_public_key = String::from("foo");
1506 let vendor_public_key = vendor_public_key.as_bytes();
1507
1508 let tmp_dir = tempfile::TempDir::new()?;
1509 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1510
1511 create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path)?;
1512
1513 let data = std::fs::read(dtbo_path)?;
1514 let fdt = Fdt::from_slice(&data).unwrap();
1515
1516 let fragment_node_path = CString::new("/fragment@0")?;
1517 let fragment_node = fdt.node(fragment_node_path.as_c_str()).unwrap();
1518 let Some(fragment_node) = fragment_node else {
1519 bail!("fragment_node shouldn't be None.");
1520 };
1521 let target_path_prop_name = CString::new("target-path")?;
1522 let target_path_from_dtbo =
1523 fragment_node.getprop(target_path_prop_name.as_c_str()).unwrap();
1524 let target_path_expected = CString::new("/")?;
1525 assert_eq!(target_path_from_dtbo, Some(target_path_expected.to_bytes_with_nul()));
1526
1527 let avf_node_path = CString::new("/fragment@0/__overlay__/avf")?;
1528 let avf_node = fdt.node(avf_node_path.as_c_str()).unwrap();
1529 let Some(avf_node) = avf_node else {
1530 bail!("avf_node shouldn't be None.");
1531 };
1532 let vendor_public_key_name = CString::new("vendor_public_key")?;
1533 let key_from_dtbo = avf_node.getprop(vendor_public_key_name.as_c_str()).unwrap();
1534 assert_eq!(key_from_dtbo, Some(vendor_public_key));
1535
1536 tmp_dir.close()?;
1537 Ok(())
1538 }
1539
1540 #[test]
1541 fn test_create_dtbo_for_vendor_image_throws_error_if_already_exists() -> Result<()> {
1542 let vendor_public_key = String::from("foo");
1543 let vendor_public_key = vendor_public_key.as_bytes();
1544
1545 let tmp_dir = tempfile::TempDir::new()?;
1546 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1547
1548 create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path)?;
1549
1550 let ret_second_trial = create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path);
1551 assert!(ret_second_trial.is_err(), "should fail");
1552
1553 tmp_dir.close()?;
1554 Ok(())
1555 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001556}