blob: 48e2431734a73d824acbfb4af45e703389294da1 [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};
Jaewan Kimc03f6612023-02-20 00:06:26 +090022use crate::debug_config::should_prepare_console_output;
Jiyong Parked180932023-02-24 19:55:41 +090023use crate::debug_config::is_ramdump_needed;
Shikha Panwar22e70452022-10-10 18:32:55 +000024use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090025use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090026use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000027use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
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::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000032 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010034 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000035 IVirtualMachineCallback::IVirtualMachineCallback,
36 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000037 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090038 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000039 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090040 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090041 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010043 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090046};
David Brazdilafc9a9e2023-01-12 16:08:10 +000047use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090048use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000049 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090050};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use anyhow::{bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010053use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000054 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
55 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000056};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000057use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000058use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000059use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090060use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090061use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000062use rpcbinder::RpcServer;
Jiyong Parkdcf17412022-02-08 15:07:23 +090063use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000064use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000065use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000066use std::fs::{read_dir, remove_file, File, OpenOptions};
67use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000068use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000069use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000070use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000072use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000073use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000074use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090075use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000076
David Brazdil41d1a872022-10-05 14:44:19 +010077/// The unique ID of a VM used (together with a port number) for vsock communication.
78pub type Cid = u32;
79
David Brazdil4b4c5102022-12-19 22:56:20 +000080pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
81
Jooyung Han95884632021-07-06 22:27:54 +090082/// The size of zero.img.
83/// Gaps in composite disk images are filled with a shared zero.img.
84const ZERO_FILLER_SIZE: u64 = 4096;
85
Jiyong Park9dd389e2021-08-23 20:42:59 +090086/// Magic string for the instance image
87const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
88
89/// Version of the instance image format
90const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
91
Alan Stokes0d1ef782022-09-27 13:46:35 +010092const MICRODROID_OS_NAME: &str = "microdroid";
93
Shikha Panwar9fd198f2022-11-18 17:43:43 +000094const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
95
Alan Stokesff0005f2023-01-30 09:53:00 +000096/// crosvm requires all partitions to be a multiple of 4KiB.
97const PARTITION_GRANULARITY_BYTES: u64 = 4096;
98
David Brazdil49f96f52022-12-16 21:29:13 +000099lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000100 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
101 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
102 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000103}
104
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000105fn create_or_update_idsig_file(
106 input_fd: &ParcelFileDescriptor,
107 idsig_fd: &ParcelFileDescriptor,
108) -> Result<()> {
109 let mut input = clone_file(input_fd)?;
110 let metadata = input.metadata().context("failed to get input metadata")?;
111 if !metadata.is_file() {
112 bail!("input is not a regular file");
113 }
114 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
115 .context("failed to create idsig")?;
116
117 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000118 output.set_len(0).context("failed to set_len on the idsig output")?;
119 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000120 Ok(())
121}
122
David Brazdil4b4c5102022-12-19 22:56:20 +0000123pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
124 for dir_entry in read_dir(path)? {
125 remove_file(dir_entry?.path())?;
126 }
127 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100128}
129
David Brazdil528e0472022-10-10 15:06:02 +0100130/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000131#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000132pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900133 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000134}
135
Shikha Panward8e35422021-10-11 13:51:27 +0000136impl Interface for VirtualizationService {
137 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
138 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
139 let state = &mut *self.state.lock().unwrap();
140 let vms = state.vms();
141 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
142 for vm in vms {
143 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
144 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
145 .or(Err(StatusCode::UNKNOWN_ERROR))?;
146 writeln!(file, "\tPayload state {:?}", vm.payload_state())
147 .or(Err(StatusCode::UNKNOWN_ERROR))?;
148 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
149 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
150 .or(Err(StatusCode::UNKNOWN_ERROR))?;
151 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
152 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000153 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
154 .or(Err(StatusCode::UNKNOWN_ERROR))?;
155 }
156 Ok(())
157 }
158}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000159
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000160impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000161 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
162 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000163 ///
164 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000165 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000166 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000167 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900168 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000169 log_fd: Option<&ParcelFileDescriptor>,
170 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000171 let mut is_protected = false;
172 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000173 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000174 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000175 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000176
Andrew Walbrandff3b942021-06-09 15:20:36 +0000177 /// Initialise an empty partition image of the given size to be used as a writable partition.
178 fn initializeWritablePartition(
179 &self,
180 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000181 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900182 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000183 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900184 check_manage_access()?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000185 let size_bytes = size_bytes.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000186 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000187 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokesff0005f2023-01-30 09:53:00 +0000188 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000189 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000190 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000191 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000192 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900193 // initialize the file. Any data in the file will be erased.
194 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000195 Status::new_service_specific_error_str(
196 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100197 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900198 )
199 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000200 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000201 Status::new_service_specific_error_str(
202 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100203 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000204 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000205 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000206
Jiyong Park9dd389e2021-08-23 20:42:59 +0900207 match partition_type {
208 PartitionType::RAW => Ok(()),
209 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000210 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900211 _ => Err(Error::new(
212 ErrorKind::Unsupported,
213 format!("Unsupported partition type {:?}", partition_type),
214 )),
215 }
216 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000217 Status::new_service_specific_error_str(
218 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100219 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900220 )
221 })?;
222
Andrew Walbrandff3b942021-06-09 15:20:36 +0000223 Ok(())
224 }
225
Jiyong Park0a248432021-08-20 23:32:39 +0900226 /// Creates or update the idsig file by digesting the input APK file.
227 fn createOrUpdateIdsigFile(
228 &self,
229 input_fd: &ParcelFileDescriptor,
230 idsig_fd: &ParcelFileDescriptor,
231 ) -> binder::Result<()> {
232 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
233 // idsig_fd is different from APK digest in input_fd
234
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900235 check_manage_access()?;
236
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000237 create_or_update_idsig_file(input_fd, idsig_fd)
238 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900239 Ok(())
240 }
241
Andrew Walbran320b5602021-03-04 16:11:12 +0000242 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
243 /// and as such is only permitted from the shell user.
244 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000245 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000246 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000247 }
248}
249
Jiyong Park8611a6c2021-07-09 18:17:44 +0900250impl VirtualizationService {
251 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000252 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900253 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000254
David Brazdil209074a2023-01-12 16:44:51 +0000255 fn create_vm_context(
256 &self,
257 requester_debug_pid: pid_t,
258 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000259 const NUM_ATTEMPTS: usize = 5;
260
261 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000262 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000263 let cid = vm_context.getCid()? as Cid;
264 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000265 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
266
267 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000268 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000269 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000270 Ok(vm_server) => {
271 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000272 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000273 }
274 Err(err) => {
275 warn!("Could not start RpcServer on port {}: {}", port, err);
276 }
277 }
278 }
David Brazdil209074a2023-01-12 16:44:51 +0000279 Err(Status::new_service_specific_error_str(
280 -1,
281 Some("Too many attempts to create VM context failed."),
282 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000283 }
284
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000285 fn create_vm_internal(
286 &self,
287 config: &VirtualMachineConfig,
288 console_fd: Option<&ParcelFileDescriptor>,
289 log_fd: Option<&ParcelFileDescriptor>,
290 is_protected: &mut bool,
291 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000292 let requester_uid = get_calling_uid();
293 let requester_debug_pid = get_calling_pid();
294
295 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
296 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900297
Alan Stokes7bc146c2022-10-20 17:10:32 +0100298 let is_custom = match config {
299 VirtualMachineConfig::RawConfig(_) => true,
300 VirtualMachineConfig::AppConfig(config) => {
301 // Some features are reserved for platform apps only, even when using
302 // VirtualMachineAppConfig:
303 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000304 // - specifying a config file in the APK;
305 // - gdbPort is set, meaning that crosvm will start a gdb server.
306 !config.taskProfiles.is_empty()
307 || matches!(config.payload, Payload::ConfigPath(_))
308 || config.gdbPort > 0
Inseob Kim1119d702022-05-02 18:01:58 +0900309 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100310 };
311 if is_custom {
312 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900313 }
314
Nikita Ioffe5776f082023-02-10 21:38:26 +0000315 let gdb_port = extract_gdb_port(config);
316
317 // Additional permission checks if caller request gdb.
318 if gdb_port.is_some() {
319 check_gdb_allowed(config)?;
320 }
321
Jiyong Parked180932023-02-24 19:55:41 +0900322 let ramdump = if is_ramdump_needed(config) {
323 Some(prepare_ramdump_file(&temporary_directory)?)
324 } else {
325 None
326 };
327
Jaewan Kim84b91212023-02-28 00:11:57 +0900328 let debug_level = match config {
329 VirtualMachineConfig::AppConfig(app_config) => app_config.debugLevel,
330 _ => DebugLevel::NONE,
331 };
332
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000333 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900334 let console_fd =
335 clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
336 let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000337
338 // Counter to generate unique IDs for temporary image files.
339 let mut next_temporary_image_id = 0;
340 // Files which are referred to from composite images. These must be mapped to the crosvm
341 // child process, and not closed before it is started.
342 let mut indirect_files = vec![];
343
Alan Stokes7bc146c2022-10-20 17:10:32 +0100344 let (is_app_config, config) = match config {
345 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
346 VirtualMachineConfig::AppConfig(config) => {
347 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000348 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100349 let message = format!("Failed to load app config: {:?}", e);
350 error!("{}", message);
351 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100352 })?;
353 (true, BorrowedOrOwned::Owned(config))
354 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000355 };
356 let config = config.as_ref();
357 *is_protected = config.protectedVm;
358
359 // Check if partition images are labeled incorrectly. This is to prevent random images
360 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100361 // being loaded in a pVM. This applies to everything in the raw config, and everything but
362 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000363 config
364 .disks
365 .iter()
366 .flat_map(|disk| disk.partitions.iter())
367 .filter(|partition| {
368 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100369 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000370 } else {
371 true // all partitions are checked
372 }
373 })
374 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100375 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000376
Alan Stokes185fe112023-01-10 16:20:55 +0000377 let kernel = maybe_clone_file(&config.kernel)?;
378 let initrd = maybe_clone_file(&config.initrd)?;
379
380 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
381 if config.protectedVm {
382 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
383 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
384 })?;
385 }
386
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000387 let zero_filler_path = temporary_directory.join("zero.img");
388 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100389 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000390 Status::new_service_specific_error_str(
391 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100392 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000393 )
394 })?;
395
396 // Assemble disk images if needed.
397 let disks = config
398 .disks
399 .iter()
400 .map(|disk| {
401 assemble_disk_image(
402 disk,
403 &zero_filler_path,
404 &temporary_directory,
405 &mut next_temporary_image_id,
406 &mut indirect_files,
407 )
408 })
409 .collect::<Result<Vec<DiskFile>, _>>()?;
410
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000411 let (cpus, host_cpu_topology) = match config.cpuTopology {
412 CpuTopology::MATCH_HOST => (None, true),
413 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
414 val => {
415 error!("Unexpected value of CPU topology: {:?}", val);
416 return Err(Status::new_service_specific_error_str(
417 -1,
418 Some(format!("Failed to parse CPU topology value: {:?}", val)),
419 ));
420 }
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,
Jaewan Kim84b91212023-02-28 00:11:57 +0900433 debug_level,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000434 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000435 cpus,
436 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900437 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000438 console_fd,
439 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900440 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000441 indirect_files,
442 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900443 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000444 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000445 };
446 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100447 VmInstance::new(
448 crosvm_config,
449 temporary_directory,
450 requester_uid,
451 requester_debug_pid,
452 vm_context,
453 )
454 .map_err(|e| {
455 error!("Failed to create VM with config {:?}: {:?}", config, e);
456 Status::new_service_specific_error_str(
457 -1,
458 Some(format!("Failed to create VM: {:?}", e)),
459 )
460 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000461 );
462 state.add_vm(Arc::downgrade(&instance));
463 Ok(VirtualMachine::create(instance))
464 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900465}
466
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000467fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900468 let file = OpenOptions::new()
469 .create_new(true)
470 .read(true)
471 .write(true)
472 .open(zero_filler_path)
473 .with_context(|| "Failed to create zero.img")?;
474 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000475 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900476}
477
Jiyong Park9dd389e2021-08-23 20:42:59 +0900478fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
479 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
480 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
481 part.flush()
482}
483
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000484fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
485 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
486 part.flush()
487}
488
Alan Stokesff0005f2023-01-30 09:53:00 +0000489fn round_up(input: u64, granularity: u64) -> u64 {
490 if granularity == 0 {
491 return input;
492 }
493 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
494 let result = input.checked_add(granularity - 1).unwrap_or(input);
495 (result / granularity) * granularity
496}
497
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000498/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
499///
500/// This may involve assembling a composite disk from a set of partition images.
501fn assemble_disk_image(
502 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900503 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000504 temporary_directory: &Path,
505 next_temporary_image_id: &mut u64,
506 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000507) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000508 let image = if !disk.partitions.is_empty() {
509 if disk.image.is_some() {
510 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000511 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000512 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000513 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000514 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000515 }
516
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000517 let composite_image_filenames =
518 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
519 let (image, partition_files) = make_composite_image(
520 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900521 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000522 &composite_image_filenames.composite,
523 &composite_image_filenames.header,
524 &composite_image_filenames.footer,
525 )
526 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100527 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000528 Status::new_service_specific_error_str(
529 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100530 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000531 )
532 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000533
534 // Pass the file descriptors for the various partition files to crosvm when it
535 // is run.
536 indirect_files.extend(partition_files);
537
538 image
539 } else if let Some(image) = &disk.image {
540 clone_file(image)?
541 } else {
542 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000543 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000544 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000545 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000546 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000547 };
548
549 Ok(DiskFile { image, writable: disk.writable })
550}
551
Jooyung Han21e9b922021-06-26 04:14:16 +0900552fn load_app_config(
553 config: &VirtualMachineAppConfig,
554 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900555) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000556 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
557 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900558 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900559
Shikha Panwar22e70452022-10-10 18:32:55 +0000560 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
561 Some(clone_file(file)?)
562 } else {
563 None
564 };
565
Alan Stokes0d1ef782022-09-27 13:46:35 +0100566 let vm_payload_config = match &config.payload {
567 Payload::ConfigPath(config_path) => {
568 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
569 .with_context(|| format!("Couldn't read config from {}", config_path))?
570 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000571 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100572 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900573
Alan Stokes0d1ef782022-09-27 13:46:35 +0100574 // For now, the only supported OS is Microdroid
575 let os_name = vm_payload_config.os.name.as_str();
576 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000577 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900578 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000579
580 // It is safe to construct a filename based on the os_name because we've already checked that it
581 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900582 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
583 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000584 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900585
Andrew Walbrancc045902021-07-27 16:06:17 +0000586 if config.memoryMib > 0 {
587 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000588 }
589
Seungjae Yoo62085c02022-08-12 04:44:52 +0000590 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000591 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000592 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900593 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000594 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900595
Shikha Panwar22e70452022-10-10 18:32:55 +0000596 // Microdroid takes additional init ramdisk & (optionally) storage image
597 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
598
599 // Include Microdroid payload disk (contains apks, idsigs) in vm config
600 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100601 config,
602 temporary_directory,
603 apk_file,
604 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100605 &vm_payload_config,
606 &mut vm_config,
607 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900608
Andrew Walbrancc0db522021-07-12 17:03:42 +0000609 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900610}
611
Alan Stokes0d1ef782022-09-27 13:46:35 +0100612fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
613 let mut apk_zip = ZipArchive::new(apk_file)?;
614 let config_file = apk_zip.by_name(config_path)?;
615 Ok(serde_json::from_reader(config_file)?)
616}
617
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000618fn create_vm_payload_config(
619 payload_config: &VirtualMachinePayloadConfig,
620) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100621 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
622 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
623 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000624
625 let payload_binary_name = &payload_config.payloadBinaryName;
626 if payload_binary_name.contains('/') {
627 bail!("Payload binary name must not specify a path: {payload_binary_name}");
628 }
629
630 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
631 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100632 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
633 task: Some(task),
634 apexes: vec![],
635 extra_apks: vec![],
636 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900637 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100638 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000639 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100640}
641
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000642/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000643fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000644 temporary_directory: &Path,
645 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000646) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000647 let id = *next_temporary_image_id;
648 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000649 CompositeImageFilenames {
650 composite: temporary_directory.join(format!("composite-{}.img", id)),
651 header: temporary_directory.join(format!("composite-{}-header.img", id)),
652 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
653 }
654}
655
656/// Filenames for a composite disk image, including header and footer partitions.
657#[derive(Clone, Debug, Eq, PartialEq)]
658struct CompositeImageFilenames {
659 /// The composite disk image itself.
660 composite: PathBuf,
661 /// The header partition image.
662 header: PathBuf,
663 /// The footer partition image.
664 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000665}
666
Jiyong Park753553b2021-07-12 21:21:09 +0900667/// Checks whether the caller has a specific permission
668fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100669 let calling_pid = get_calling_pid();
670 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900671 // Root can do anything
672 if calling_uid == 0 {
673 return Ok(());
674 }
675 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
676 binder::get_interface("permission")?;
677 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000678 Ok(())
679 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000680 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900681 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000682 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900683 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000684 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000685}
686
Jiyong Park753553b2021-07-12 21:21:09 +0900687/// Check whether the caller of the current Binder method is allowed to manage VMs
688fn check_manage_access() -> binder::Result<()> {
689 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
690}
691
Inseob Kim1119d702022-05-02 18:01:58 +0900692/// Check whether the caller of the current Binder method is allowed to create custom VMs
693fn check_use_custom_virtual_machine() -> binder::Result<()> {
694 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
695}
696
Alan Stokes185fe112023-01-10 16:20:55 +0000697/// Return whether a partition is exempt from selinux label checks, because we know that it does
698/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100699fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000700 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100701 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000702 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100703 || label == "microdroid-apk-idsig"
704 || label == "payload-metadata"
705 || label.starts_with("extra-idsig-")
706}
707
Alan Stokes185fe112023-01-10 16:20:55 +0000708/// Check that a file SELinux label is acceptable.
709///
710/// We only want to allow code in a VM to be sourced from places that apps, and the
711/// system, do not have write access to.
712///
713/// Note that sepolicy must also grant read access for these types to both virtualization
714/// service and crosvm.
715///
716/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
717/// user devices (W^X).
718fn check_label_is_allowed(context: &SeContext) -> Result<()> {
719 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100720 | "system_file" // immutable dm-verity protected partition
721 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000722 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100723 | "shell_data_file" // test files created via adb shell
724 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000725 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900726 }
727}
728
Alan Stokes185fe112023-01-10 16:20:55 +0000729fn check_label_for_partition(partition: &Partition) -> Result<()> {
730 let file = partition.image.as_ref().unwrap().as_ref();
731 check_label_is_allowed(&getfilecon(file)?)
732 .with_context(|| format!("Partition {} invalid", &partition.label))
733}
734
735fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
736 if let Some(f) = kernel {
737 check_label_for_file(f, "kernel")?;
738 }
739 if let Some(f) = initrd {
740 check_label_for_file(f, "initrd")?;
741 }
742 Ok(())
743}
744fn check_label_for_file(file: &File, name: &str) -> Result<()> {
745 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
746}
747
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000748/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
749#[derive(Debug)]
750struct VirtualMachine {
751 instance: Arc<VmInstance>,
752}
753
754impl VirtualMachine {
755 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000756 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000757 }
758}
759
760impl Interface for VirtualMachine {}
761
762impl IVirtualMachine for VirtualMachine {
763 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900764 // Don't check permission. The owner of the VM might have passed this binder object to
765 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000766 Ok(self.instance.cid as i32)
767 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000768
Andrew Walbran6b650662021-09-07 13:13:23 +0000769 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900770 // Don't check permission. The owner of the VM might have passed this binder object to
771 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000772 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000773 }
774
775 fn registerCallback(
776 &self,
777 callback: &Strong<dyn IVirtualMachineCallback>,
778 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900779 // Don't check permission. The owner of the VM might have passed this binder object to
780 // others.
781 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000782 // TODO: Should this give an error if the VM is already dead?
783 self.instance.callbacks.add(callback.clone());
784 Ok(())
785 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000786
Andrew Walbranf8d94112021-09-07 11:45:36 +0000787 fn start(&self) -> binder::Result<()> {
788 self.instance.start().map_err(|e| {
789 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000790 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000791 })
792 }
793
Inseob Kima446f802022-07-11 19:46:37 +0900794 fn stop(&self) -> binder::Result<()> {
795 self.instance.kill().map_err(|e| {
796 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000797 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900798 })
799 }
800
Keir Frasercdd4b112022-11-24 14:02:25 +0000801 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
802 self.instance.trim_memory(level).map_err(|e| {
803 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
804 Status::new_service_specific_error_str(-1, Some(e.to_string()))
805 })
806 }
807
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000808 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000809 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000810 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000811 }
Alan Stokes10c47672022-12-13 17:17:08 +0000812 let port = port as u32;
813 if port < 1024 {
814 return Err(Status::new_service_specific_error_str(
815 -1,
816 Some(format!("Can't connect to privileged port {port}")),
817 ));
818 }
819 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
820 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
821 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000822 Ok(vsock_stream_to_pfd(stream))
823 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000824}
825
826impl Drop for VirtualMachine {
827 fn drop(&mut self) {
828 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900829 if let Err(e) = self.instance.kill() {
830 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
831 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000832 }
833}
834
835/// A set of Binders to be called back in response to various events on the VM, such as when it
836/// dies.
837#[derive(Debug, Default)]
838pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
839
840impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900841 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100842 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900843 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900844 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100845 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100846 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900847 }
848 }
849 }
850
Inseob Kim14cb8692021-08-31 21:50:39 +0900851 /// Call all registered callbacks to notify that the payload is ready to serve.
852 pub fn notify_payload_ready(&self, cid: Cid) {
853 let callbacks = &*self.0.lock().unwrap();
854 for callback in callbacks {
855 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100856 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900857 }
858 }
859 }
860
Inseob Kim2444af92021-08-31 01:22:50 +0900861 /// Call all registered callbacks to notify that the payload has finished.
862 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
863 let callbacks = &*self.0.lock().unwrap();
864 for callback in callbacks {
865 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100866 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900867 }
868 }
869 }
870
Jooyung Handd0a1732021-11-23 15:26:20 +0900871 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100872 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900873 let callbacks = &*self.0.lock().unwrap();
874 for callback in callbacks {
875 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100876 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900877 }
878 }
879 }
880
Andrew Walbrandae07162021-03-12 17:05:20 +0000881 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000882 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000883 let callbacks = &*self.0.lock().unwrap();
884 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000885 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100886 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000887 }
888 }
889 }
890
891 /// Add a new callback to the set.
892 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
893 self.0.lock().unwrap().push(callback);
894 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000895}
896
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000897/// The mutable state of the VirtualizationService. There should only be one instance of this
898/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800899#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000900struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000901 /// The VMs which have been started. When VMs are started a weak reference is added to this list
902 /// while a strong reference is returned to the caller over Binder. Once all copies of the
903 /// Binder client are dropped the weak reference here will become invalid, and will be removed
904 /// from the list opportunistically the next time `add_vm` is called.
905 vms: Vec<Weak<VmInstance>>,
906}
907
908impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000909 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000910 fn vms(&self) -> Vec<Arc<VmInstance>> {
911 // Attempt to upgrade the weak pointers to strong pointers.
912 self.vms.iter().filter_map(Weak::upgrade).collect()
913 }
914
915 /// Add a new VM to the list.
916 fn add_vm(&mut self, vm: Weak<VmInstance>) {
917 // Garbage collect any entries from the stored list which no longer exist.
918 self.vms.retain(|vm| vm.strong_count() > 0);
919
920 // Actually add the new VM.
921 self.vms.push(vm);
922 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000923
Jiyong Park8611a6c2021-07-09 18:17:44 +0900924 /// Get a VM that corresponds to the given cid
925 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
926 self.vms().into_iter().find(|vm| vm.cid == cid)
927 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900928}
929
Andrew Walbran6b650662021-09-07 13:13:23 +0000930/// Gets the `VirtualMachineState` of the given `VmInstance`.
931fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000932 match &*instance.vm_state.lock().unwrap() {
933 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
934 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000935 PayloadState::Starting => VirtualMachineState::STARTING,
936 PayloadState::Started => VirtualMachineState::STARTED,
937 PayloadState::Ready => VirtualMachineState::READY,
938 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900939 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000940 },
941 VmState::Dead => VirtualMachineState::DEAD,
942 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000943 }
944}
945
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000946/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000947pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000948 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000949 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000950 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100951 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000952 )
953 })
954}
955
Andrew Walbrand3a84182021-09-07 14:48:52 +0000956/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
957fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
958 file.as_ref().map(clone_file).transpose()
959}
960
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000961/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
962fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
963 // SAFETY: ownership is transferred from stream to f
964 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
965 ParcelFileDescriptor::new(f)
966}
967
Jiyong Parkdcf17412022-02-08 15:07:23 +0900968/// Parses the platform version requirement string.
969fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
970 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000971 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +0900972 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100973 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +0900974 )
975 })
976}
977
Jiyong Parked180932023-02-24 19:55:41 +0900978/// Create the empty ramdump file
979fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
980 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
981 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
982 // owner) for readout.
983 let ramdump_path = temporary_directory.join("ramdump");
984 let ramdump = File::create(ramdump_path).map_err(|e| {
985 error!("Failed to prepare ramdump file: {:?}", e);
986 Status::new_service_specific_error_str(
987 -1,
988 Some(format!("Failed to prepare ramdump file: {:?}", e)),
989 )
990 })?;
991 Ok(ramdump)
992}
993
Nikita Ioffe5776f082023-02-10 21:38:26 +0000994fn is_protected(config: &VirtualMachineConfig) -> bool {
995 match config {
996 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
997 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
998 }
999}
1000
1001fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1002 if is_protected(config) {
1003 return Err(Status::new_exception_str(
1004 ExceptionCode::SECURITY,
1005 Some("can't use gdb with protected VMs"),
1006 ));
1007 }
1008
1009 match config {
1010 VirtualMachineConfig::RawConfig(_) => Ok(()),
1011 VirtualMachineConfig::AppConfig(config) => {
1012 if config.debugLevel != DebugLevel::FULL {
1013 Err(Status::new_exception_str(
1014 ExceptionCode::SECURITY,
1015 Some("can't use gdb with non-debuggable VMs"),
1016 ))
1017 } else {
1018 Ok(())
1019 }
1020 }
1021 }
1022}
1023
1024fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1025 match config {
1026 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1027 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1028 }
1029}
1030
Inseob Kim0168b462022-12-27 14:54:35 +09001031fn clone_or_prepare_logger_fd(
1032 config: &VirtualMachineConfig,
1033 fd: Option<&ParcelFileDescriptor>,
1034 tag: String,
1035) -> Result<Option<File>, Status> {
1036 if let Some(fd) = fd {
1037 return Ok(Some(clone_file(fd)?));
1038 }
1039
Jaewan Kim66f062e2023-02-25 01:07:43 +09001040 let VirtualMachineConfig::AppConfig(app_config) = config else {
Inseob Kim0168b462022-12-27 14:54:35 +09001041 return Ok(None);
Jaewan Kim66f062e2023-02-25 01:07:43 +09001042 };
1043 if !should_prepare_console_output(app_config.debugLevel) {
1044 return Ok(None);
1045 };
Inseob Kim0168b462022-12-27 14:54:35 +09001046
1047 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1048 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1049 })?;
1050
1051 // SAFETY: We are the sole owners of these fds as they were just created.
1052 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1053 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1054
1055 std::thread::spawn(move || loop {
1056 let mut buf = vec![];
1057 match reader.read_until(b'\n', &mut buf) {
1058 Ok(0) => {
1059 // EOF
1060 return;
1061 }
1062 Ok(size) => {
1063 if buf[size - 1] == b'\n' {
1064 buf.pop();
1065 }
1066 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1067 }
1068 Err(e) => {
1069 error!("Could not read console pipe: {:?}", e);
1070 return;
1071 }
1072 };
1073 });
1074
1075 Ok(Some(write_fd))
1076}
1077
Jooyung Han35edb8f2021-07-01 16:17:16 +09001078/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1079/// it doesn't require that T implements Clone.
1080enum BorrowedOrOwned<'a, T> {
1081 Borrowed(&'a T),
1082 Owned(T),
1083}
1084
1085impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1086 fn as_ref(&self) -> &T {
1087 match self {
1088 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001089 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001090 }
1091 }
1092}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001093
1094/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1095#[derive(Debug, Default)]
1096struct VirtualMachineService {
1097 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001098 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001099}
1100
1101impl Interface for VirtualMachineService {}
1102
1103impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001104 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1105 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001106 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001107 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001108 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1109 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1110 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001111 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001112
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001113 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1114 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001115 Ok(())
1116 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001117 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001118 Err(Status::new_service_specific_error_str(
1119 -1,
1120 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001121 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001122 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001123 }
Inseob Kim2444af92021-08-31 01:22:50 +09001124
Inseob Kimc7d28c72021-10-25 14:28:10 +00001125 fn notifyPayloadReady(&self) -> binder::Result<()> {
1126 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001127 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001128 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001129 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1130 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1131 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001132 vm.callbacks.notify_payload_ready(cid);
1133 Ok(())
1134 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001135 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001136 Err(Status::new_service_specific_error_str(
1137 -1,
1138 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001139 ))
1140 }
1141 }
1142
Inseob Kimc7d28c72021-10-25 14:28:10 +00001143 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1144 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001145 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001146 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001147 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1148 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1149 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001150 vm.callbacks.notify_payload_finished(cid, exit_code);
1151 Ok(())
1152 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001153 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001154 Err(Status::new_service_specific_error_str(
1155 -1,
1156 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001157 ))
1158 }
1159 }
1160
Alan Stokes2bead0d2022-09-05 16:58:34 +01001161 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001162 let cid = self.cid;
1163 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001164 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001165 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1166 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1167 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001168 vm.callbacks.notify_error(cid, error_code, message);
1169 Ok(())
1170 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001171 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001172 Err(Status::new_service_specific_error_str(
1173 -1,
1174 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001175 ))
1176 }
1177 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001178}
1179
1180impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001181 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001182 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001183 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001184 BinderFeatures::default(),
1185 )
1186 }
1187}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001188
1189#[cfg(test)]
1190mod tests {
1191 use super::*;
1192
1193 #[test]
1194 fn test_is_allowed_label_for_partition() -> Result<()> {
1195 let expected_results = vec![
1196 ("u:object_r:system_file:s0", true),
1197 ("u:object_r:apk_data_file:s0", true),
1198 ("u:object_r:app_data_file:s0", false),
1199 ("u:object_r:app_data_file:s0:c512,c768", false),
1200 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1201 ("invalid", false),
1202 ("user:role:apk_data_file:severity:categories", true),
1203 ("user:role:apk_data_file:severity:categories:extraneous", false),
1204 ];
1205
1206 for (label, expected_valid) in expected_results {
1207 let context = SeContext::new(label)?;
1208 let result = check_label_is_allowed(&context);
1209 if expected_valid {
1210 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1211 } else if result.is_ok() {
1212 bail!("Expected label {} to be disallowed", label);
1213 }
1214 }
1215 Ok(())
1216 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001217
1218 #[test]
1219 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1220 let apk = tempfile::tempfile().unwrap();
1221 let idsig = tempfile::tempfile().unwrap();
1222
1223 let ret = create_or_update_idsig_file(
1224 &ParcelFileDescriptor::new(apk),
1225 &ParcelFileDescriptor::new(idsig),
1226 );
1227 assert!(ret.is_err(), "should fail");
1228 Ok(())
1229 }
1230
1231 #[test]
1232 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1233 let tmp_dir = tempfile::TempDir::new().unwrap();
1234 let apk = File::open(tmp_dir.path()).unwrap();
1235 let idsig = tempfile::tempfile().unwrap();
1236
1237 let ret = create_or_update_idsig_file(
1238 &ParcelFileDescriptor::new(apk),
1239 &ParcelFileDescriptor::new(idsig),
1240 );
1241 assert!(ret.is_err(), "should fail");
1242 Ok(())
1243 }
1244
1245 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1246 /// on ext4 filesystem is passed.
1247 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1248 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1249 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1250 #[test]
1251 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1252 // APEXes are backed by the ext4.
1253 let apk = File::open("/apex/com.android.virt/").unwrap();
1254 let idsig = tempfile::tempfile().unwrap();
1255
1256 let ret = create_or_update_idsig_file(
1257 &ParcelFileDescriptor::new(apk),
1258 &ParcelFileDescriptor::new(idsig),
1259 );
1260 assert!(ret.is_err(), "should fail");
1261 Ok(())
1262 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001263}