blob: aceb3197efd8bafaaa6dbcf4729568ed018fff34 [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;
David Brazdil8cf8f482022-11-23 14:21:26 +000021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000022use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090023use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090024use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000025use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000026 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000027 ErrorCode::ErrorCode,
28};
29use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000030 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010032 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000033 IVirtualMachineCallback::IVirtualMachineCallback,
34 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000035 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090036 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090038 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090039 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010041 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090044};
David Brazdilafc9a9e2023-01-12 16:08:10 +000045use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090046use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000047 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090048};
David Brazdilafc9a9e2023-01-12 16:08:10 +000049use anyhow::{bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090050use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010051use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
53 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000054};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000055use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000056use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000057use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090058use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090059use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000060use rpcbinder::RpcServer;
Jiyong Parkdcf17412022-02-08 15:07:23 +090061use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000062use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000063use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000064use std::fs::{read_dir, remove_file, File, OpenOptions};
65use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000066use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000067use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000068use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000070use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000071use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000072use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090073use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000074
David Brazdil41d1a872022-10-05 14:44:19 +010075/// The unique ID of a VM used (together with a port number) for vsock communication.
76pub type Cid = u32;
77
David Brazdil4b4c5102022-12-19 22:56:20 +000078pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
79
Jooyung Han95884632021-07-06 22:27:54 +090080/// The size of zero.img.
81/// Gaps in composite disk images are filled with a shared zero.img.
82const ZERO_FILLER_SIZE: u64 = 4096;
83
Jiyong Park9dd389e2021-08-23 20:42:59 +090084/// Magic string for the instance image
85const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
86
87/// Version of the instance image format
88const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
89
Alan Stokes0d1ef782022-09-27 13:46:35 +010090const MICRODROID_OS_NAME: &str = "microdroid";
91
Shikha Panwar9fd198f2022-11-18 17:43:43 +000092const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
93
Alan Stokesff0005f2023-01-30 09:53:00 +000094/// crosvm requires all partitions to be a multiple of 4KiB.
95const PARTITION_GRANULARITY_BYTES: u64 = 4096;
96
David Brazdil49f96f52022-12-16 21:29:13 +000097lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +000098 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
99 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
100 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000101}
102
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000103fn create_or_update_idsig_file(
104 input_fd: &ParcelFileDescriptor,
105 idsig_fd: &ParcelFileDescriptor,
106) -> Result<()> {
107 let mut input = clone_file(input_fd)?;
108 let metadata = input.metadata().context("failed to get input metadata")?;
109 if !metadata.is_file() {
110 bail!("input is not a regular file");
111 }
112 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
113 .context("failed to create idsig")?;
114
115 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000116 output.set_len(0).context("failed to set_len on the idsig output")?;
117 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000118 Ok(())
119}
120
David Brazdil4b4c5102022-12-19 22:56:20 +0000121pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
122 for dir_entry in read_dir(path)? {
123 remove_file(dir_entry?.path())?;
124 }
125 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100126}
127
David Brazdil528e0472022-10-10 15:06:02 +0100128/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000129#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000130pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900131 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132}
133
Shikha Panward8e35422021-10-11 13:51:27 +0000134impl Interface for VirtualizationService {
135 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
136 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
137 let state = &mut *self.state.lock().unwrap();
138 let vms = state.vms();
139 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
140 for vm in vms {
141 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
142 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
143 .or(Err(StatusCode::UNKNOWN_ERROR))?;
144 writeln!(file, "\tPayload state {:?}", vm.payload_state())
145 .or(Err(StatusCode::UNKNOWN_ERROR))?;
146 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
147 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
148 .or(Err(StatusCode::UNKNOWN_ERROR))?;
149 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
150 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000151 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
152 .or(Err(StatusCode::UNKNOWN_ERROR))?;
153 }
154 Ok(())
155 }
156}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000157
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000158impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000159 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
160 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000161 ///
162 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000163 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000164 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000165 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900166 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000167 log_fd: Option<&ParcelFileDescriptor>,
168 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000169 let mut is_protected = false;
170 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000171 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000172 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000173 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000174
Andrew Walbrandff3b942021-06-09 15:20:36 +0000175 /// Initialise an empty partition image of the given size to be used as a writable partition.
176 fn initializeWritablePartition(
177 &self,
178 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000179 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900180 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000181 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900182 check_manage_access()?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000183 let size_bytes = size_bytes.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000184 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000185 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokesff0005f2023-01-30 09:53:00 +0000186 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000187 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000188 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000189 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000190 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900191 // initialize the file. Any data in the file will be erased.
192 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000193 Status::new_service_specific_error_str(
194 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100195 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900196 )
197 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000198 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000199 Status::new_service_specific_error_str(
200 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100201 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000202 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000203 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000204
Jiyong Park9dd389e2021-08-23 20:42:59 +0900205 match partition_type {
206 PartitionType::RAW => Ok(()),
207 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000208 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900209 _ => Err(Error::new(
210 ErrorKind::Unsupported,
211 format!("Unsupported partition type {:?}", partition_type),
212 )),
213 }
214 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000215 Status::new_service_specific_error_str(
216 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100217 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900218 )
219 })?;
220
Andrew Walbrandff3b942021-06-09 15:20:36 +0000221 Ok(())
222 }
223
Jiyong Park0a248432021-08-20 23:32:39 +0900224 /// Creates or update the idsig file by digesting the input APK file.
225 fn createOrUpdateIdsigFile(
226 &self,
227 input_fd: &ParcelFileDescriptor,
228 idsig_fd: &ParcelFileDescriptor,
229 ) -> binder::Result<()> {
230 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
231 // idsig_fd is different from APK digest in input_fd
232
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900233 check_manage_access()?;
234
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000235 create_or_update_idsig_file(input_fd, idsig_fd)
236 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900237 Ok(())
238 }
239
Andrew Walbran320b5602021-03-04 16:11:12 +0000240 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
241 /// and as such is only permitted from the shell user.
242 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000243 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000244 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000245 }
246}
247
Jiyong Park8611a6c2021-07-09 18:17:44 +0900248impl VirtualizationService {
249 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000250 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900251 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000252
David Brazdil209074a2023-01-12 16:44:51 +0000253 fn create_vm_context(
254 &self,
255 requester_debug_pid: pid_t,
256 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000257 const NUM_ATTEMPTS: usize = 5;
258
259 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000260 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000261 let cid = vm_context.getCid()? as Cid;
262 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000263 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
264
265 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000266 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000267 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000268 Ok(vm_server) => {
269 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000270 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000271 }
272 Err(err) => {
273 warn!("Could not start RpcServer on port {}: {}", port, err);
274 }
275 }
276 }
David Brazdil209074a2023-01-12 16:44:51 +0000277 Err(Status::new_service_specific_error_str(
278 -1,
279 Some("Too many attempts to create VM context failed."),
280 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000281 }
282
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000283 fn create_vm_internal(
284 &self,
285 config: &VirtualMachineConfig,
286 console_fd: Option<&ParcelFileDescriptor>,
287 log_fd: Option<&ParcelFileDescriptor>,
288 is_protected: &mut bool,
289 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000290 let requester_uid = get_calling_uid();
291 let requester_debug_pid = get_calling_pid();
292
293 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
294 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900295
Alan Stokes7bc146c2022-10-20 17:10:32 +0100296 let is_custom = match config {
297 VirtualMachineConfig::RawConfig(_) => true,
298 VirtualMachineConfig::AppConfig(config) => {
299 // Some features are reserved for platform apps only, even when using
300 // VirtualMachineAppConfig:
301 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000302 // - specifying a config file in the APK;
303 // - gdbPort is set, meaning that crosvm will start a gdb server.
304 !config.taskProfiles.is_empty()
305 || matches!(config.payload, Payload::ConfigPath(_))
306 || config.gdbPort > 0
Inseob Kim1119d702022-05-02 18:01:58 +0900307 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100308 };
309 if is_custom {
310 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900311 }
312
Nikita Ioffe5776f082023-02-10 21:38:26 +0000313 let gdb_port = extract_gdb_port(config);
314
315 // Additional permission checks if caller request gdb.
316 if gdb_port.is_some() {
317 check_gdb_allowed(config)?;
318 }
319
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000320 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900321 let console_fd =
322 clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
323 let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000324
325 // Counter to generate unique IDs for temporary image files.
326 let mut next_temporary_image_id = 0;
327 // Files which are referred to from composite images. These must be mapped to the crosvm
328 // child process, and not closed before it is started.
329 let mut indirect_files = vec![];
330
Alan Stokes7bc146c2022-10-20 17:10:32 +0100331 let (is_app_config, config) = match config {
332 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
333 VirtualMachineConfig::AppConfig(config) => {
334 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000335 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100336 let message = format!("Failed to load app config: {:?}", e);
337 error!("{}", message);
338 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100339 })?;
340 (true, BorrowedOrOwned::Owned(config))
341 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000342 };
343 let config = config.as_ref();
344 *is_protected = config.protectedVm;
345
346 // Check if partition images are labeled incorrectly. This is to prevent random images
347 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100348 // being loaded in a pVM. This applies to everything in the raw config, and everything but
349 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000350 config
351 .disks
352 .iter()
353 .flat_map(|disk| disk.partitions.iter())
354 .filter(|partition| {
355 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100356 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000357 } else {
358 true // all partitions are checked
359 }
360 })
361 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100362 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000363
Alan Stokes185fe112023-01-10 16:20:55 +0000364 let kernel = maybe_clone_file(&config.kernel)?;
365 let initrd = maybe_clone_file(&config.initrd)?;
366
367 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
368 if config.protectedVm {
369 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
370 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
371 })?;
372 }
373
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000374 let zero_filler_path = temporary_directory.join("zero.img");
375 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100376 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000377 Status::new_service_specific_error_str(
378 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100379 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000380 )
381 })?;
382
383 // Assemble disk images if needed.
384 let disks = config
385 .disks
386 .iter()
387 .map(|disk| {
388 assemble_disk_image(
389 disk,
390 &zero_filler_path,
391 &temporary_directory,
392 &mut next_temporary_image_id,
393 &mut indirect_files,
394 )
395 })
396 .collect::<Result<Vec<DiskFile>, _>>()?;
397
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000398 let (cpus, host_cpu_topology) = match config.cpuTopology {
399 CpuTopology::MATCH_HOST => (None, true),
400 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
401 val => {
402 error!("Unexpected value of CPU topology: {:?}", val);
403 return Err(Status::new_service_specific_error_str(
404 -1,
405 Some(format!("Failed to parse CPU topology value: {:?}", val)),
406 ));
407 }
408 };
409
Jiyong Parke558ab12022-07-07 20:18:55 +0900410 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
411 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900412 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900413 // will be sent back to the client (i.e. the VM owner) for readout.
414 let ramdump_path = temporary_directory.join("ramdump");
415 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100416 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000417 Status::new_service_specific_error_str(
418 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100419 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900420 )
421 })?;
422
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000423 // Actually start the VM.
424 let crosvm_config = CrosvmConfig {
425 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000426 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000427 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000428 kernel,
429 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000430 disks,
431 params: config.params.to_owned(),
432 protected: *is_protected,
433 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000434 cpus,
435 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900436 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000437 console_fd,
438 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900439 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000440 indirect_files,
441 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900442 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000443 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000444 };
445 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100446 VmInstance::new(
447 crosvm_config,
448 temporary_directory,
449 requester_uid,
450 requester_debug_pid,
451 vm_context,
452 )
453 .map_err(|e| {
454 error!("Failed to create VM with config {:?}: {:?}", config, e);
455 Status::new_service_specific_error_str(
456 -1,
457 Some(format!("Failed to create VM: {:?}", e)),
458 )
459 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000460 );
461 state.add_vm(Arc::downgrade(&instance));
462 Ok(VirtualMachine::create(instance))
463 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900464}
465
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000466fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900467 let file = OpenOptions::new()
468 .create_new(true)
469 .read(true)
470 .write(true)
471 .open(zero_filler_path)
472 .with_context(|| "Failed to create zero.img")?;
473 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000474 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900475}
476
Jiyong Park9dd389e2021-08-23 20:42:59 +0900477fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
478 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
479 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
480 part.flush()
481}
482
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000483fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
484 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
485 part.flush()
486}
487
Jiyong Parke558ab12022-07-07 20:18:55 +0900488fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800489 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900490}
491
Alan Stokesff0005f2023-01-30 09:53:00 +0000492fn round_up(input: u64, granularity: u64) -> u64 {
493 if granularity == 0 {
494 return input;
495 }
496 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
497 let result = input.checked_add(granularity - 1).unwrap_or(input);
498 (result / granularity) * granularity
499}
500
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000501/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
502///
503/// This may involve assembling a composite disk from a set of partition images.
504fn assemble_disk_image(
505 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900506 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000507 temporary_directory: &Path,
508 next_temporary_image_id: &mut u64,
509 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000510) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000511 let image = if !disk.partitions.is_empty() {
512 if disk.image.is_some() {
513 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000514 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000515 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000516 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000517 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000518 }
519
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000520 let composite_image_filenames =
521 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
522 let (image, partition_files) = make_composite_image(
523 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900524 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000525 &composite_image_filenames.composite,
526 &composite_image_filenames.header,
527 &composite_image_filenames.footer,
528 )
529 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100530 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000531 Status::new_service_specific_error_str(
532 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100533 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000534 )
535 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000536
537 // Pass the file descriptors for the various partition files to crosvm when it
538 // is run.
539 indirect_files.extend(partition_files);
540
541 image
542 } else if let Some(image) = &disk.image {
543 clone_file(image)?
544 } else {
545 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000546 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000547 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000548 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000549 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000550 };
551
552 Ok(DiskFile { image, writable: disk.writable })
553}
554
Jooyung Han21e9b922021-06-26 04:14:16 +0900555fn load_app_config(
556 config: &VirtualMachineAppConfig,
557 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900558) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000559 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
560 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900561 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900562
Shikha Panwar22e70452022-10-10 18:32:55 +0000563 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
564 Some(clone_file(file)?)
565 } else {
566 None
567 };
568
Alan Stokes0d1ef782022-09-27 13:46:35 +0100569 let vm_payload_config = match &config.payload {
570 Payload::ConfigPath(config_path) => {
571 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
572 .with_context(|| format!("Couldn't read config from {}", config_path))?
573 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000574 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100575 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900576
Alan Stokes0d1ef782022-09-27 13:46:35 +0100577 // For now, the only supported OS is Microdroid
578 let os_name = vm_payload_config.os.name.as_str();
579 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000580 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900581 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000582
583 // It is safe to construct a filename based on the os_name because we've already checked that it
584 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900585 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
586 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000587 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900588
Andrew Walbrancc045902021-07-27 16:06:17 +0000589 if config.memoryMib > 0 {
590 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000591 }
592
Seungjae Yoo62085c02022-08-12 04:44:52 +0000593 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000594 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000595 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900596 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000597 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900598
Shikha Panwar22e70452022-10-10 18:32:55 +0000599 // Microdroid takes additional init ramdisk & (optionally) storage image
600 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
601
602 // Include Microdroid payload disk (contains apks, idsigs) in vm config
603 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100604 config,
605 temporary_directory,
606 apk_file,
607 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100608 &vm_payload_config,
609 &mut vm_config,
610 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900611
Andrew Walbrancc0db522021-07-12 17:03:42 +0000612 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900613}
614
Alan Stokes0d1ef782022-09-27 13:46:35 +0100615fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
616 let mut apk_zip = ZipArchive::new(apk_file)?;
617 let config_file = apk_zip.by_name(config_path)?;
618 Ok(serde_json::from_reader(config_file)?)
619}
620
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000621fn create_vm_payload_config(
622 payload_config: &VirtualMachinePayloadConfig,
623) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100624 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
625 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
626 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000627
628 let payload_binary_name = &payload_config.payloadBinaryName;
629 if payload_binary_name.contains('/') {
630 bail!("Payload binary name must not specify a path: {payload_binary_name}");
631 }
632
633 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
634 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100635 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
636 task: Some(task),
637 apexes: vec![],
638 extra_apks: vec![],
639 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900640 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100641 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000642 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100643}
644
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000645/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000646fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000647 temporary_directory: &Path,
648 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000649) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000650 let id = *next_temporary_image_id;
651 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000652 CompositeImageFilenames {
653 composite: temporary_directory.join(format!("composite-{}.img", id)),
654 header: temporary_directory.join(format!("composite-{}-header.img", id)),
655 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
656 }
657}
658
659/// Filenames for a composite disk image, including header and footer partitions.
660#[derive(Clone, Debug, Eq, PartialEq)]
661struct CompositeImageFilenames {
662 /// The composite disk image itself.
663 composite: PathBuf,
664 /// The header partition image.
665 header: PathBuf,
666 /// The footer partition image.
667 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000668}
669
Jiyong Park753553b2021-07-12 21:21:09 +0900670/// Checks whether the caller has a specific permission
671fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100672 let calling_pid = get_calling_pid();
673 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900674 // Root can do anything
675 if calling_uid == 0 {
676 return Ok(());
677 }
678 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
679 binder::get_interface("permission")?;
680 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000681 Ok(())
682 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000683 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900684 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000685 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900686 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000687 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000688}
689
Jiyong Park753553b2021-07-12 21:21:09 +0900690/// Check whether the caller of the current Binder method is allowed to manage VMs
691fn check_manage_access() -> binder::Result<()> {
692 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
693}
694
Inseob Kim1119d702022-05-02 18:01:58 +0900695/// Check whether the caller of the current Binder method is allowed to create custom VMs
696fn check_use_custom_virtual_machine() -> binder::Result<()> {
697 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
698}
699
Alan Stokes185fe112023-01-10 16:20:55 +0000700/// Return whether a partition is exempt from selinux label checks, because we know that it does
701/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100702fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000703 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100704 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000705 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100706 || label == "microdroid-apk-idsig"
707 || label == "payload-metadata"
708 || label.starts_with("extra-idsig-")
709}
710
Alan Stokes185fe112023-01-10 16:20:55 +0000711/// Check that a file SELinux label is acceptable.
712///
713/// We only want to allow code in a VM to be sourced from places that apps, and the
714/// system, do not have write access to.
715///
716/// Note that sepolicy must also grant read access for these types to both virtualization
717/// service and crosvm.
718///
719/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
720/// user devices (W^X).
721fn check_label_is_allowed(context: &SeContext) -> Result<()> {
722 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100723 | "system_file" // immutable dm-verity protected partition
724 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000725 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100726 | "shell_data_file" // test files created via adb shell
727 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000728 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900729 }
730}
731
Alan Stokes185fe112023-01-10 16:20:55 +0000732fn check_label_for_partition(partition: &Partition) -> Result<()> {
733 let file = partition.image.as_ref().unwrap().as_ref();
734 check_label_is_allowed(&getfilecon(file)?)
735 .with_context(|| format!("Partition {} invalid", &partition.label))
736}
737
738fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
739 if let Some(f) = kernel {
740 check_label_for_file(f, "kernel")?;
741 }
742 if let Some(f) = initrd {
743 check_label_for_file(f, "initrd")?;
744 }
745 Ok(())
746}
747fn check_label_for_file(file: &File, name: &str) -> Result<()> {
748 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
749}
750
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000751/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
752#[derive(Debug)]
753struct VirtualMachine {
754 instance: Arc<VmInstance>,
755}
756
757impl VirtualMachine {
758 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000759 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000760 }
761}
762
763impl Interface for VirtualMachine {}
764
765impl IVirtualMachine for VirtualMachine {
766 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900767 // Don't check permission. The owner of the VM might have passed this binder object to
768 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000769 Ok(self.instance.cid as i32)
770 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000771
Andrew Walbran6b650662021-09-07 13:13:23 +0000772 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900773 // Don't check permission. The owner of the VM might have passed this binder object to
774 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000775 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000776 }
777
778 fn registerCallback(
779 &self,
780 callback: &Strong<dyn IVirtualMachineCallback>,
781 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900782 // Don't check permission. The owner of the VM might have passed this binder object to
783 // others.
784 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000785 // TODO: Should this give an error if the VM is already dead?
786 self.instance.callbacks.add(callback.clone());
787 Ok(())
788 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000789
Andrew Walbranf8d94112021-09-07 11:45:36 +0000790 fn start(&self) -> binder::Result<()> {
791 self.instance.start().map_err(|e| {
792 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000793 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000794 })
795 }
796
Inseob Kima446f802022-07-11 19:46:37 +0900797 fn stop(&self) -> binder::Result<()> {
798 self.instance.kill().map_err(|e| {
799 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000800 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900801 })
802 }
803
Keir Frasercdd4b112022-11-24 14:02:25 +0000804 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
805 self.instance.trim_memory(level).map_err(|e| {
806 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
807 Status::new_service_specific_error_str(-1, Some(e.to_string()))
808 })
809 }
810
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000811 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000812 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000813 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000814 }
Alan Stokes10c47672022-12-13 17:17:08 +0000815 let port = port as u32;
816 if port < 1024 {
817 return Err(Status::new_service_specific_error_str(
818 -1,
819 Some(format!("Can't connect to privileged port {port}")),
820 ));
821 }
822 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
823 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
824 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000825 Ok(vsock_stream_to_pfd(stream))
826 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000827}
828
829impl Drop for VirtualMachine {
830 fn drop(&mut self) {
831 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900832 if let Err(e) = self.instance.kill() {
833 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
834 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000835 }
836}
837
838/// A set of Binders to be called back in response to various events on the VM, such as when it
839/// dies.
840#[derive(Debug, Default)]
841pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
842
843impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900844 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100845 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900846 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900847 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100848 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100849 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900850 }
851 }
852 }
853
Inseob Kim14cb8692021-08-31 21:50:39 +0900854 /// Call all registered callbacks to notify that the payload is ready to serve.
855 pub fn notify_payload_ready(&self, cid: Cid) {
856 let callbacks = &*self.0.lock().unwrap();
857 for callback in callbacks {
858 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100859 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900860 }
861 }
862 }
863
Inseob Kim2444af92021-08-31 01:22:50 +0900864 /// Call all registered callbacks to notify that the payload has finished.
865 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
866 let callbacks = &*self.0.lock().unwrap();
867 for callback in callbacks {
868 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100869 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900870 }
871 }
872 }
873
Jooyung Handd0a1732021-11-23 15:26:20 +0900874 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100875 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900876 let callbacks = &*self.0.lock().unwrap();
877 for callback in callbacks {
878 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100879 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900880 }
881 }
882 }
883
Andrew Walbrandae07162021-03-12 17:05:20 +0000884 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000885 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000886 let callbacks = &*self.0.lock().unwrap();
887 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000888 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100889 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000890 }
891 }
892 }
893
894 /// Add a new callback to the set.
895 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
896 self.0.lock().unwrap().push(callback);
897 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000898}
899
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000900/// The mutable state of the VirtualizationService. There should only be one instance of this
901/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800902#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000903struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000904 /// The VMs which have been started. When VMs are started a weak reference is added to this list
905 /// while a strong reference is returned to the caller over Binder. Once all copies of the
906 /// Binder client are dropped the weak reference here will become invalid, and will be removed
907 /// from the list opportunistically the next time `add_vm` is called.
908 vms: Vec<Weak<VmInstance>>,
909}
910
911impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000912 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000913 fn vms(&self) -> Vec<Arc<VmInstance>> {
914 // Attempt to upgrade the weak pointers to strong pointers.
915 self.vms.iter().filter_map(Weak::upgrade).collect()
916 }
917
918 /// Add a new VM to the list.
919 fn add_vm(&mut self, vm: Weak<VmInstance>) {
920 // Garbage collect any entries from the stored list which no longer exist.
921 self.vms.retain(|vm| vm.strong_count() > 0);
922
923 // Actually add the new VM.
924 self.vms.push(vm);
925 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000926
Jiyong Park8611a6c2021-07-09 18:17:44 +0900927 /// Get a VM that corresponds to the given cid
928 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
929 self.vms().into_iter().find(|vm| vm.cid == cid)
930 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900931}
932
Andrew Walbran6b650662021-09-07 13:13:23 +0000933/// Gets the `VirtualMachineState` of the given `VmInstance`.
934fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000935 match &*instance.vm_state.lock().unwrap() {
936 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
937 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000938 PayloadState::Starting => VirtualMachineState::STARTING,
939 PayloadState::Started => VirtualMachineState::STARTED,
940 PayloadState::Ready => VirtualMachineState::READY,
941 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900942 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000943 },
944 VmState::Dead => VirtualMachineState::DEAD,
945 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000946 }
947}
948
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000949/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000950pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000951 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000952 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000953 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100954 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000955 )
956 })
957}
958
Andrew Walbrand3a84182021-09-07 14:48:52 +0000959/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
960fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
961 file.as_ref().map(clone_file).transpose()
962}
963
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000964/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
965fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
966 // SAFETY: ownership is transferred from stream to f
967 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
968 ParcelFileDescriptor::new(f)
969}
970
Jiyong Parkdcf17412022-02-08 15:07:23 +0900971/// Parses the platform version requirement string.
972fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
973 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000974 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +0900975 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100976 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +0900977 )
978 })
979}
980
Inseob Kim0168b462022-12-27 14:54:35 +0900981fn is_debuggable(config: &VirtualMachineConfig) -> bool {
982 match config {
983 VirtualMachineConfig::AppConfig(config) => config.debugLevel != DebugLevel::NONE,
984 _ => false,
985 }
986}
987
Nikita Ioffe5776f082023-02-10 21:38:26 +0000988fn is_protected(config: &VirtualMachineConfig) -> bool {
989 match config {
990 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
991 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
992 }
993}
994
995fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
996 if is_protected(config) {
997 return Err(Status::new_exception_str(
998 ExceptionCode::SECURITY,
999 Some("can't use gdb with protected VMs"),
1000 ));
1001 }
1002
1003 match config {
1004 VirtualMachineConfig::RawConfig(_) => Ok(()),
1005 VirtualMachineConfig::AppConfig(config) => {
1006 if config.debugLevel != DebugLevel::FULL {
1007 Err(Status::new_exception_str(
1008 ExceptionCode::SECURITY,
1009 Some("can't use gdb with non-debuggable VMs"),
1010 ))
1011 } else {
1012 Ok(())
1013 }
1014 }
1015 }
1016}
1017
1018fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1019 match config {
1020 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1021 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1022 }
1023}
1024
Inseob Kim0168b462022-12-27 14:54:35 +09001025fn clone_or_prepare_logger_fd(
1026 config: &VirtualMachineConfig,
1027 fd: Option<&ParcelFileDescriptor>,
1028 tag: String,
1029) -> Result<Option<File>, Status> {
1030 if let Some(fd) = fd {
1031 return Ok(Some(clone_file(fd)?));
1032 }
1033
1034 if !is_debuggable(config) {
1035 return Ok(None);
1036 }
1037
1038 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1039 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1040 })?;
1041
1042 // SAFETY: We are the sole owners of these fds as they were just created.
1043 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1044 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1045
1046 std::thread::spawn(move || loop {
1047 let mut buf = vec![];
1048 match reader.read_until(b'\n', &mut buf) {
1049 Ok(0) => {
1050 // EOF
1051 return;
1052 }
1053 Ok(size) => {
1054 if buf[size - 1] == b'\n' {
1055 buf.pop();
1056 }
1057 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1058 }
1059 Err(e) => {
1060 error!("Could not read console pipe: {:?}", e);
1061 return;
1062 }
1063 };
1064 });
1065
1066 Ok(Some(write_fd))
1067}
1068
Jooyung Han35edb8f2021-07-01 16:17:16 +09001069/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1070/// it doesn't require that T implements Clone.
1071enum BorrowedOrOwned<'a, T> {
1072 Borrowed(&'a T),
1073 Owned(T),
1074}
1075
1076impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1077 fn as_ref(&self) -> &T {
1078 match self {
1079 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001080 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001081 }
1082 }
1083}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001084
1085/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1086#[derive(Debug, Default)]
1087struct VirtualMachineService {
1088 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001089 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001090}
1091
1092impl Interface for VirtualMachineService {}
1093
1094impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001095 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1096 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001097 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001098 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001099 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1100 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1101 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001102 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001103
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001104 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1105 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001106 Ok(())
1107 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001108 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001109 Err(Status::new_service_specific_error_str(
1110 -1,
1111 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001112 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001113 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001114 }
Inseob Kim2444af92021-08-31 01:22:50 +09001115
Inseob Kimc7d28c72021-10-25 14:28:10 +00001116 fn notifyPayloadReady(&self) -> binder::Result<()> {
1117 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001118 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001119 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001120 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1121 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1122 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001123 vm.callbacks.notify_payload_ready(cid);
1124 Ok(())
1125 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001126 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001127 Err(Status::new_service_specific_error_str(
1128 -1,
1129 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001130 ))
1131 }
1132 }
1133
Inseob Kimc7d28c72021-10-25 14:28:10 +00001134 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1135 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001136 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001137 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001138 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1139 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1140 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001141 vm.callbacks.notify_payload_finished(cid, exit_code);
1142 Ok(())
1143 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001144 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001145 Err(Status::new_service_specific_error_str(
1146 -1,
1147 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001148 ))
1149 }
1150 }
1151
Alan Stokes2bead0d2022-09-05 16:58:34 +01001152 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001153 let cid = self.cid;
1154 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001155 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001156 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1157 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1158 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001159 vm.callbacks.notify_error(cid, error_code, message);
1160 Ok(())
1161 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001162 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001163 Err(Status::new_service_specific_error_str(
1164 -1,
1165 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001166 ))
1167 }
1168 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001169}
1170
1171impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001172 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001173 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001174 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001175 BinderFeatures::default(),
1176 )
1177 }
1178}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001179
1180#[cfg(test)]
1181mod tests {
1182 use super::*;
1183
1184 #[test]
1185 fn test_is_allowed_label_for_partition() -> Result<()> {
1186 let expected_results = vec![
1187 ("u:object_r:system_file:s0", true),
1188 ("u:object_r:apk_data_file:s0", true),
1189 ("u:object_r:app_data_file:s0", false),
1190 ("u:object_r:app_data_file:s0:c512,c768", false),
1191 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1192 ("invalid", false),
1193 ("user:role:apk_data_file:severity:categories", true),
1194 ("user:role:apk_data_file:severity:categories:extraneous", false),
1195 ];
1196
1197 for (label, expected_valid) in expected_results {
1198 let context = SeContext::new(label)?;
1199 let result = check_label_is_allowed(&context);
1200 if expected_valid {
1201 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1202 } else if result.is_ok() {
1203 bail!("Expected label {} to be disallowed", label);
1204 }
1205 }
1206 Ok(())
1207 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001208
1209 #[test]
1210 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1211 let apk = tempfile::tempfile().unwrap();
1212 let idsig = tempfile::tempfile().unwrap();
1213
1214 let ret = create_or_update_idsig_file(
1215 &ParcelFileDescriptor::new(apk),
1216 &ParcelFileDescriptor::new(idsig),
1217 );
1218 assert!(ret.is_err(), "should fail");
1219 Ok(())
1220 }
1221
1222 #[test]
1223 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1224 let tmp_dir = tempfile::TempDir::new().unwrap();
1225 let apk = File::open(tmp_dir.path()).unwrap();
1226 let idsig = tempfile::tempfile().unwrap();
1227
1228 let ret = create_or_update_idsig_file(
1229 &ParcelFileDescriptor::new(apk),
1230 &ParcelFileDescriptor::new(idsig),
1231 );
1232 assert!(ret.is_err(), "should fail");
1233 Ok(())
1234 }
1235
1236 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1237 /// on ext4 filesystem is passed.
1238 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1239 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1240 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1241 #[test]
1242 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1243 // APEXes are backed by the ext4.
1244 let apk = File::open("/apex/com.android.virt/").unwrap();
1245 let idsig = tempfile::tempfile().unwrap();
1246
1247 let ret = create_or_update_idsig_file(
1248 &ParcelFileDescriptor::new(apk),
1249 &ParcelFileDescriptor::new(idsig),
1250 );
1251 assert!(ret.is_err(), "should fail");
1252 Ok(())
1253 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001254}