blob: cf4b537514352213d70a35bed44cbbc1ae893f6a [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoofd9a0622022-10-14 10:01:29 +090017use crate::atom::{
18 write_vm_booted_stats, write_vm_cpu_status_stats, write_vm_creation_stats,
19 write_vm_mem_status_stats,
20};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000021use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000022use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Seungjae Yoofd9a0622022-10-14 10:01:29 +090026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
Jooyung Han21e9b922021-06-26 04:14:16 +090027use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000029 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010030 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000031 IVirtualMachineCallback::IVirtualMachineCallback,
32 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090033 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090035 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090036 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010038 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090039 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090041};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
43 IVirtualMachineService::{
44 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
45 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
46 },
47 VirtualMachineCpuStatus::VirtualMachineCpuStatus,
48 VirtualMachineMemStatus::VirtualMachineMemStatus,
49};
50use anyhow::{anyhow, bail, Context, Result};
51use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010052use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000053 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
54 SpIBinder, Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000055};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000056use disk::QcowFile;
David Brazdila07a1792022-10-25 13:37:57 +010057use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000058use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090059use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Alice Wang86c88cc2022-10-17 08:10:49 +000060use rpcbinder::run_vsock_rpc_server_with_factory;
Jiyong Parkd50a0242021-09-16 21:00:14 +090061use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090062use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000063use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000064use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010065use std::fs::{create_dir, File, OpenOptions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090066use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000067use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000068use std::os::unix::io::{FromRawFd, IntoRawFd};
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};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090071use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000072use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000073use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090074use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000075
David Brazdil41d1a872022-10-05 14:44:19 +010076/// The unique ID of a VM used (together with a port number) for vsock communication.
77pub type Cid = u32;
78
Andrew Walbranf6bf6862021-05-21 12:41:13 +000079pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000080
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000082pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000083
David Brazdil41d1a872022-10-05 14:44:19 +010084/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
85/// are reserved for the host or other usage.
86const FIRST_GUEST_CID: Cid = 10;
87
88const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
89
Jooyung Han95884632021-07-06 22:27:54 +090090/// The size of zero.img.
91/// Gaps in composite disk images are filled with a shared zero.img.
92const ZERO_FILLER_SIZE: u64 = 4096;
93
Jiyong Park9dd389e2021-08-23 20:42:59 +090094/// Magic string for the instance image
95const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
96
97/// Version of the instance image format
98const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
99
Shikha Panwar7afc1392022-03-24 08:54:43 +0000100const CHUNK_RECV_MAX_LEN: usize = 1024;
101
Alan Stokes0d1ef782022-09-27 13:46:35 +0100102const MICRODROID_OS_NAME: &str = "microdroid";
103
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000104/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900105#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000106pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900107 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000108}
109
Shikha Panward8e35422021-10-11 13:51:27 +0000110impl Interface for VirtualizationService {
111 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
112 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
113 let state = &mut *self.state.lock().unwrap();
114 let vms = state.vms();
115 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
116 for vm in vms {
117 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
118 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
119 .or(Err(StatusCode::UNKNOWN_ERROR))?;
120 writeln!(file, "\tPayload state {:?}", vm.payload_state())
121 .or(Err(StatusCode::UNKNOWN_ERROR))?;
122 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
123 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
124 .or(Err(StatusCode::UNKNOWN_ERROR))?;
125 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
126 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000127 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
128 .or(Err(StatusCode::UNKNOWN_ERROR))?;
129 }
130 Ok(())
131 }
132}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000133
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000134impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000135 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
136 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000137 ///
138 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000139 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000140 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000141 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900142 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000143 log_fd: Option<&ParcelFileDescriptor>,
144 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000145 let mut is_protected = false;
146 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000147 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000148 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000149 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000150
Andrew Walbrandff3b942021-06-09 15:20:36 +0000151 /// Initialise an empty partition image of the given size to be used as a writable partition.
152 fn initializeWritablePartition(
153 &self,
154 image_fd: &ParcelFileDescriptor,
155 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900156 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000157 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900158 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000159 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000160 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000161 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100162 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000163 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000164 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000165 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900166 // initialize the file. Any data in the file will be erased.
167 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000168 Status::new_service_specific_error_str(
169 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100170 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900171 )
172 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900173 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000174 Status::new_service_specific_error_str(
175 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100176 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000177 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000178 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000179
Jiyong Park9dd389e2021-08-23 20:42:59 +0900180 match partition_type {
181 PartitionType::RAW => Ok(()),
182 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
183 _ => Err(Error::new(
184 ErrorKind::Unsupported,
185 format!("Unsupported partition type {:?}", partition_type),
186 )),
187 }
188 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000189 Status::new_service_specific_error_str(
190 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100191 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900192 )
193 })?;
194
Andrew Walbrandff3b942021-06-09 15:20:36 +0000195 Ok(())
196 }
197
Jiyong Park0a248432021-08-20 23:32:39 +0900198 /// Creates or update the idsig file by digesting the input APK file.
199 fn createOrUpdateIdsigFile(
200 &self,
201 input_fd: &ParcelFileDescriptor,
202 idsig_fd: &ParcelFileDescriptor,
203 ) -> binder::Result<()> {
204 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
205 // idsig_fd is different from APK digest in input_fd
206
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900207 check_manage_access()?;
208
Jiyong Park0a248432021-08-20 23:32:39 +0900209 let mut input = clone_file(input_fd)?;
210 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
211
212 let mut output = clone_file(idsig_fd)?;
213 output.set_len(0).unwrap();
214 sig.write_into(&mut output).unwrap();
215 Ok(())
216 }
217
Andrew Walbran320b5602021-03-04 16:11:12 +0000218 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
219 /// and as such is only permitted from the shell user.
220 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000221 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000222
223 let state = &mut *self.state.lock().unwrap();
224 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000225 let cids = vms
226 .into_iter()
227 .map(|vm| VirtualMachineDebugInfo {
228 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000229 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000230 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000231 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000232 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000233 })
234 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000235 Ok(cids)
236 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000237
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000238 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
239 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000240 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000241 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242
David Brazdil3c2ddef2021-03-18 13:09:57 +0000243 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000244 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000245 Ok(())
246 }
247
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000248 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
249 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
250 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000251 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000252 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000253
254 let state = &mut *self.state.lock().unwrap();
255 Ok(state.debug_drop_vm(cid))
256 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000257}
258
Shikha Panwar7afc1392022-03-24 08:54:43 +0000259fn handle_stream_connection_tombstoned() -> Result<()> {
260 let listener =
261 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
262 info!("Listening to tombstones from guests ...");
263 for incoming_stream in listener.incoming() {
264 let mut incoming_stream = match incoming_stream {
265 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100266 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000267 continue;
268 }
269 Ok(s) => s,
270 };
271 std::thread::spawn(move || {
272 if let Err(e) = handle_tombstone(&mut incoming_stream) {
273 error!("Failed to write tombstone- {:?}", e);
274 }
275 });
276 }
277 Ok(())
278}
279
280fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000281 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000282 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
283 }
284 let tb_connection =
285 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
286 .context("Failed to connect to tombstoned")?;
287 let mut text_output = tb_connection
288 .text_output
289 .as_ref()
290 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
291 let mut num_bytes_read = 0;
292 loop {
293 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
294 let n = stream
295 .read(&mut chunk_recv)
296 .context("Failed to read tombstone data from Vsock stream")?;
297 if n == 0 {
298 break;
299 }
300 num_bytes_read += n;
301 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
302 }
303 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
304 tb_connection.notify_completion()?;
305 Ok(())
306}
307
Jiyong Park8611a6c2021-07-09 18:17:44 +0900308impl VirtualizationService {
309 pub fn init() -> VirtualizationService {
310 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900311
312 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900313 let state = service.state.clone(); // reference to state (not the state itself) is copied
314 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900315 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900316 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900317
Shikha Panwar7afc1392022-03-24 08:54:43 +0000318 std::thread::spawn(|| {
319 if let Err(e) = handle_stream_connection_tombstoned() {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100320 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000321 }
322 });
323
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900324 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000325 // reference to state (not the state itself) is copied
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000326 let state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900327 std::thread::spawn(move || {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000328 debug!("VirtualMachineService is starting as an RPC service.");
Alice Wang86c88cc2022-10-17 08:10:49 +0000329 if run_vsock_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000330 VirtualMachineService::factory(cid, &state)
331 }) {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900332 debug!("RPC server has shut down gracefully");
333 } else {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000334 panic!("Premature termination of RPC server");
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900335 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900336 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900337 service
338 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000339
340 fn create_vm_internal(
341 &self,
342 config: &VirtualMachineConfig,
343 console_fd: Option<&ParcelFileDescriptor>,
344 log_fd: Option<&ParcelFileDescriptor>,
345 is_protected: &mut bool,
346 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
347 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900348
349 if let VirtualMachineConfig::RawConfig(config) = config {
350 if config.protectedVm {
351 check_use_custom_virtual_machine()?;
352 }
353 }
354
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000355 let state = &mut *self.state.lock().unwrap();
356 let console_fd = console_fd.map(clone_file).transpose()?;
357 let log_fd = log_fd.map(clone_file).transpose()?;
358 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000359 let requester_debug_pid = ThreadState::get_calling_pid();
David Brazdil7feea602022-10-05 14:06:01 +0100360 let cid = state.next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000361
362 // Counter to generate unique IDs for temporary image files.
363 let mut next_temporary_image_id = 0;
364 // Files which are referred to from composite images. These must be mapped to the crosvm
365 // child process, and not closed before it is started.
366 let mut indirect_files = vec![];
367
368 // Make directory for temporary files.
369 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
370 create_dir(&temporary_directory).map_err(|e| {
371 // At this point, we do not know the protected status of Vm
372 // setting it to false, though this may not be correct.
373 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100374 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000375 temporary_directory, e
376 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000377 Status::new_service_specific_error_str(
378 -1,
379 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100380 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000381 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000382 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000383 )
384 })?;
385
386 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
387
388 let config = match config {
389 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
390 load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000391 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100392 let message = format!("Failed to load app config: {:?}", e);
393 error!("{}", message);
394 Status::new_service_specific_error_str(-1, Some(message))
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000395 })?,
396 ),
397 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
398 };
399 let config = config.as_ref();
400 *is_protected = config.protectedVm;
401
402 // Check if partition images are labeled incorrectly. This is to prevent random images
403 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100404 // being loaded in a pVM. This applies to everything in the raw config, and everything but
405 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000406 config
407 .disks
408 .iter()
409 .flat_map(|disk| disk.partitions.iter())
410 .filter(|partition| {
411 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100412 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000413 } else {
414 true // all partitions are checked
415 }
416 })
417 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100418 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000419
420 let zero_filler_path = temporary_directory.join("zero.img");
421 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100422 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000423 Status::new_service_specific_error_str(
424 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100425 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000426 )
427 })?;
428
429 // Assemble disk images if needed.
430 let disks = config
431 .disks
432 .iter()
433 .map(|disk| {
434 assemble_disk_image(
435 disk,
436 &zero_filler_path,
437 &temporary_directory,
438 &mut next_temporary_image_id,
439 &mut indirect_files,
440 )
441 })
442 .collect::<Result<Vec<DiskFile>, _>>()?;
443
Jiyong Parke558ab12022-07-07 20:18:55 +0900444 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
445 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900446 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900447 // will be sent back to the client (i.e. the VM owner) for readout.
448 let ramdump_path = temporary_directory.join("ramdump");
449 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100450 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000451 Status::new_service_specific_error_str(
452 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100453 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900454 )
455 })?;
456
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000457 // Actually start the VM.
458 let crosvm_config = CrosvmConfig {
459 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000460 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000461 bootloader: maybe_clone_file(&config.bootloader)?,
462 kernel: maybe_clone_file(&config.kernel)?,
463 initrd: maybe_clone_file(&config.initrd)?,
464 disks,
465 params: config.params.to_owned(),
466 protected: *is_protected,
467 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
468 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900469 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470 console_fd,
471 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900472 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000473 indirect_files,
474 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900475 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000476 };
477 let instance = Arc::new(
David Brazdil2d967202022-10-05 13:01:03 +0100478 VmInstance::new(crosvm_config, temporary_directory, requester_uid, requester_debug_pid)
479 .map_err(|e| {
480 error!("Failed to create VM with config {:?}: {:?}", config, e);
481 Status::new_service_specific_error_str(
482 -1,
483 Some(format!("Failed to create VM: {:?}", e)),
484 )
485 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000486 );
487 state.add_vm(Arc::downgrade(&instance));
488 Ok(VirtualMachine::create(instance))
489 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900490}
491
Andrew Walbran6b650662021-09-07 13:13:23 +0000492/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
493/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900494fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900495 let listener =
496 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900497 for stream in listener.incoming() {
498 let stream = match stream {
499 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100500 warn!("invalid incoming connection: {:?}", e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900501 continue;
502 }
503 Ok(s) => s,
504 };
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000505 if let Ok(addr) = stream.peer_addr() {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900506 let cid = addr.cid();
507 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900508 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900509 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700510 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900511 } else {
512 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900513 }
514 }
515 }
516 Ok(())
517}
518
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000519fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900520 let file = OpenOptions::new()
521 .create_new(true)
522 .read(true)
523 .write(true)
524 .open(zero_filler_path)
525 .with_context(|| "Failed to create zero.img")?;
526 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000527 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900528}
529
Jiyong Park9dd389e2021-08-23 20:42:59 +0900530fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
531 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
532 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
533 part.flush()
534}
535
Jiyong Parke558ab12022-07-07 20:18:55 +0900536fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
537 File::create(&ramdump_path)
538 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
539}
540
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
542///
543/// This may involve assembling a composite disk from a set of partition images.
544fn assemble_disk_image(
545 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900546 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000547 temporary_directory: &Path,
548 next_temporary_image_id: &mut u64,
549 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000550) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000551 let image = if !disk.partitions.is_empty() {
552 if disk.image.is_some() {
553 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000554 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000555 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000556 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000557 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558 }
559
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000560 let composite_image_filenames =
561 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
562 let (image, partition_files) = make_composite_image(
563 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900564 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000565 &composite_image_filenames.composite,
566 &composite_image_filenames.header,
567 &composite_image_filenames.footer,
568 )
569 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100570 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000571 Status::new_service_specific_error_str(
572 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100573 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000574 )
575 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000576
577 // Pass the file descriptors for the various partition files to crosvm when it
578 // is run.
579 indirect_files.extend(partition_files);
580
581 image
582 } else if let Some(image) = &disk.image {
583 clone_file(image)?
584 } else {
585 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000586 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000587 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000588 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000589 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590 };
591
592 Ok(DiskFile { image, writable: disk.writable })
593}
594
Jooyung Han21e9b922021-06-26 04:14:16 +0900595fn load_app_config(
596 config: &VirtualMachineAppConfig,
597 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900598) -> Result<VirtualMachineRawConfig> {
Alan Stokes82f389c2022-09-08 12:23:52 +0100599 // Controlling CPUs is reserved for platform apps only, even when using
600 // VirtualMachineAppConfig.
Victor Hsiehf219cd82022-09-09 13:13:11 -0700601 if !config.taskProfiles.is_empty() {
Alan Stokes82f389c2022-09-08 12:23:52 +0100602 check_use_custom_virtual_machine()?
603 }
604
Andrew Walbrancc0db522021-07-12 17:03:42 +0000605 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
606 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900607 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900608
Shikha Panwar22e70452022-10-10 18:32:55 +0000609 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
610 Some(clone_file(file)?)
611 } else {
612 None
613 };
614
Alan Stokes0d1ef782022-09-27 13:46:35 +0100615 let vm_payload_config = match &config.payload {
616 Payload::ConfigPath(config_path) => {
617 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
618 .with_context(|| format!("Couldn't read config from {}", config_path))?
619 }
620 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
621 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900622
Alan Stokes0d1ef782022-09-27 13:46:35 +0100623 // For now, the only supported OS is Microdroid
624 let os_name = vm_payload_config.os.name.as_str();
625 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000626 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900627 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000628
629 // It is safe to construct a filename based on the os_name because we've already checked that it
630 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900631 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
632 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000633 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900634
Andrew Walbrancc045902021-07-27 16:06:17 +0000635 if config.memoryMib > 0 {
636 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000637 }
638
Seungjae Yoo62085c02022-08-12 04:44:52 +0000639 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000640 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900641 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900642 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900643
Shikha Panwar22e70452022-10-10 18:32:55 +0000644 // Microdroid takes additional init ramdisk & (optionally) storage image
645 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
646
647 // Include Microdroid payload disk (contains apks, idsigs) in vm config
648 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100649 config,
650 temporary_directory,
651 apk_file,
652 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100653 &vm_payload_config,
654 &mut vm_config,
655 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900656
Andrew Walbrancc0db522021-07-12 17:03:42 +0000657 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900658}
659
Alan Stokes0d1ef782022-09-27 13:46:35 +0100660fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
661 let mut apk_zip = ZipArchive::new(apk_file)?;
662 let config_file = apk_zip.by_name(config_path)?;
663 Ok(serde_json::from_reader(config_file)?)
664}
665
666fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
667 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
668 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
669 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100670 let task =
671 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100672 VmPayloadConfig {
673 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
674 task: Some(task),
675 apexes: vec![],
676 extra_apks: vec![],
677 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100678 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100679 enable_authfs: false,
680 }
681}
682
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000683/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000684fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000685 temporary_directory: &Path,
686 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000687) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000688 let id = *next_temporary_image_id;
689 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000690 CompositeImageFilenames {
691 composite: temporary_directory.join(format!("composite-{}.img", id)),
692 header: temporary_directory.join(format!("composite-{}-header.img", id)),
693 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
694 }
695}
696
697/// Filenames for a composite disk image, including header and footer partitions.
698#[derive(Clone, Debug, Eq, PartialEq)]
699struct CompositeImageFilenames {
700 /// The composite disk image itself.
701 composite: PathBuf,
702 /// The header partition image.
703 header: PathBuf,
704 /// The footer partition image.
705 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000706}
707
Jiyong Park753553b2021-07-12 21:21:09 +0900708/// Checks whether the caller has a specific permission
709fn check_permission(perm: &str) -> binder::Result<()> {
710 let calling_pid = ThreadState::get_calling_pid();
711 let calling_uid = ThreadState::get_calling_uid();
712 // Root can do anything
713 if calling_uid == 0 {
714 return Ok(());
715 }
716 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
717 binder::get_interface("permission")?;
718 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000719 Ok(())
720 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000721 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900722 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000723 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900724 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000725 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000726}
727
Jiyong Park753553b2021-07-12 21:21:09 +0900728/// Check whether the caller of the current Binder method is allowed to call debug methods.
729fn check_debug_access() -> binder::Result<()> {
730 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
731}
732
733/// Check whether the caller of the current Binder method is allowed to manage VMs
734fn check_manage_access() -> binder::Result<()> {
735 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
736}
737
Inseob Kim1119d702022-05-02 18:01:58 +0900738/// Check whether the caller of the current Binder method is allowed to create custom VMs
739fn check_use_custom_virtual_machine() -> binder::Result<()> {
740 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
741}
742
Jiyong Park029977d2021-11-24 21:56:49 +0900743/// Check if a partition has selinux labels that are not allowed
744fn check_label_for_partition(partition: &Partition) -> Result<()> {
745 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100746 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
747}
748
749// Return whether a partition is exempt from selinux label checks, because we know that it does
750// not contain code and is likely to be generated in an app-writable directory.
751fn is_safe_app_partition(label: &str) -> bool {
752 // See make_payload_disk in payload.rs.
753 label == "vm-instance"
754 || label == "microdroid-apk-idsig"
755 || label == "payload-metadata"
756 || label.starts_with("extra-idsig-")
757}
758
759fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
760 // We only want to allow code in a VM payload to be sourced from places that apps, and the
761 // system, do not have write access to.
762 // (Note that sepolicy must also grant read access for these types to both virtualization
763 // service and crosvm.)
764 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
765 // user devices (W^X).
766 match ctx.selinux_type()? {
767 | "system_file" // immutable dm-verity protected partition
768 | "apk_data_file" // APKs of an installed app
769 | "staging_data_file" // updated/staged APEX imagess
770 | "shell_data_file" // test files created via adb shell
771 => Ok(()),
772 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900773 }
774}
775
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000776/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
777#[derive(Debug)]
778struct VirtualMachine {
779 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100780 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800781 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100782 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000783}
784
785impl VirtualMachine {
786 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100787 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000788 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000789 }
790}
791
792impl Interface for VirtualMachine {}
793
794impl IVirtualMachine for VirtualMachine {
795 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900796 // Don't check permission. The owner of the VM might have passed this binder object to
797 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000798 Ok(self.instance.cid as i32)
799 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000800
Andrew Walbran6b650662021-09-07 13:13:23 +0000801 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900802 // Don't check permission. The owner of the VM might have passed this binder object to
803 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000804 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000805 }
806
807 fn registerCallback(
808 &self,
809 callback: &Strong<dyn IVirtualMachineCallback>,
810 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900811 // Don't check permission. The owner of the VM might have passed this binder object to
812 // others.
813 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000814 // TODO: Should this give an error if the VM is already dead?
815 self.instance.callbacks.add(callback.clone());
816 Ok(())
817 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000818
Andrew Walbranf8d94112021-09-07 11:45:36 +0000819 fn start(&self) -> binder::Result<()> {
820 self.instance.start().map_err(|e| {
821 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000822 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000823 })
824 }
825
Inseob Kima446f802022-07-11 19:46:37 +0900826 fn stop(&self) -> binder::Result<()> {
827 self.instance.kill().map_err(|e| {
828 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000829 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900830 })
831 }
832
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000833 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000834 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000835 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000836 }
837 let stream =
838 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000839 Status::new_service_specific_error_str(
840 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100841 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000842 )
843 })?;
844 Ok(vsock_stream_to_pfd(stream))
845 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000846}
847
848impl Drop for VirtualMachine {
849 fn drop(&mut self) {
850 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900851 if let Err(e) = self.instance.kill() {
852 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
853 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000854 }
855}
856
857/// A set of Binders to be called back in response to various events on the VM, such as when it
858/// dies.
859#[derive(Debug, Default)]
860pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
861
862impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900863 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900864 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900865 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900866 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900867 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900868 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100869 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900870 }
871 }
872 }
873
Inseob Kim14cb8692021-08-31 21:50:39 +0900874 /// Call all registered callbacks to notify that the payload is ready to serve.
875 pub fn notify_payload_ready(&self, cid: Cid) {
876 let callbacks = &*self.0.lock().unwrap();
877 for callback in callbacks {
878 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100879 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900880 }
881 }
882 }
883
Inseob Kim2444af92021-08-31 01:22:50 +0900884 /// Call all registered callbacks to notify that the payload has finished.
885 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
886 let callbacks = &*self.0.lock().unwrap();
887 for callback in callbacks {
888 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100889 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900890 }
891 }
892 }
893
Jooyung Handd0a1732021-11-23 15:26:20 +0900894 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100895 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900896 let callbacks = &*self.0.lock().unwrap();
897 for callback in callbacks {
898 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100899 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900900 }
901 }
902 }
903
Andrew Walbrandae07162021-03-12 17:05:20 +0000904 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000905 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000906 let callbacks = &*self.0.lock().unwrap();
907 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000908 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100909 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000910 }
911 }
912 }
913
Jiyong Parke558ab12022-07-07 20:18:55 +0900914 /// Call all registered callbacks to say that there was a ramdump to download.
915 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
916 let callbacks = &*self.0.lock().unwrap();
917 let pfd = ParcelFileDescriptor::new(ramdump);
918 for callback in callbacks {
919 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100920 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +0900921 }
922 }
923 }
924
Andrew Walbrandae07162021-03-12 17:05:20 +0000925 /// Add a new callback to the set.
926 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
927 self.0.lock().unwrap().push(callback);
928 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000929}
930
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000931/// The mutable state of the VirtualizationService. There should only be one instance of this
932/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800933#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000934struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000935 /// The VMs which have been started. When VMs are started a weak reference is added to this list
936 /// while a strong reference is returned to the caller over Binder. Once all copies of the
937 /// Binder client are dropped the weak reference here will become invalid, and will be removed
938 /// from the list opportunistically the next time `add_vm` is called.
939 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000940
941 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
942 /// This is only used for debugging purposes.
943 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000944}
945
946impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000947 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000948 fn vms(&self) -> Vec<Arc<VmInstance>> {
949 // Attempt to upgrade the weak pointers to strong pointers.
950 self.vms.iter().filter_map(Weak::upgrade).collect()
951 }
952
953 /// Add a new VM to the list.
954 fn add_vm(&mut self, vm: Weak<VmInstance>) {
955 // Garbage collect any entries from the stored list which no longer exist.
956 self.vms.retain(|vm| vm.strong_count() > 0);
957
958 // Actually add the new VM.
959 self.vms.push(vm);
960 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000961
Jiyong Park8611a6c2021-07-09 18:17:44 +0900962 /// Get a VM that corresponds to the given cid
963 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
964 self.vms().into_iter().find(|vm| vm.cid == cid)
965 }
966
David Brazdil3c2ddef2021-03-18 13:09:57 +0000967 /// Store a strong VM reference.
968 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
969 self.debug_held_vms.push(vm);
970 }
971
972 /// Retrieve and remove a strong VM reference.
973 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
974 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100975 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100976 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000977 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000978
David Brazdil7feea602022-10-05 14:06:01 +0100979 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
980 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
981 /// Android is up.
982 fn next_cid(&mut self) -> Result<Cid> {
983 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
984 if let Ok(num) = val.parse::<u32>() {
985 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
986 } else {
987 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
988 FIRST_GUEST_CID
989 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900990 } else {
David Brazdil7feea602022-10-05 14:06:01 +0100991 // First VM since the boot
Jiyong Parkd50a0242021-09-16 21:00:14 +0900992 FIRST_GUEST_CID
David Brazdil7feea602022-10-05 14:06:01 +0100993 };
994 // Persist the last value for next use
995 let str_val = format!("{}", next);
996 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
997 Ok(next)
998 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900999}
1000
Andrew Walbran6b650662021-09-07 13:13:23 +00001001/// Gets the `VirtualMachineState` of the given `VmInstance`.
1002fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001003 match &*instance.vm_state.lock().unwrap() {
1004 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1005 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001006 PayloadState::Starting => VirtualMachineState::STARTING,
1007 PayloadState::Started => VirtualMachineState::STARTED,
1008 PayloadState::Ready => VirtualMachineState::READY,
1009 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001010 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001011 },
1012 VmState::Dead => VirtualMachineState::DEAD,
1013 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001014 }
1015}
1016
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001017/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001018pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001019 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001020 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001021 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001022 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001023 )
1024 })
1025}
1026
Andrew Walbrand3a84182021-09-07 14:48:52 +00001027/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1028fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1029 file.as_ref().map(clone_file).transpose()
1030}
1031
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001032/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1033fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1034 // SAFETY: ownership is transferred from stream to f
1035 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1036 ParcelFileDescriptor::new(f)
1037}
1038
Jiyong Parkdcf17412022-02-08 15:07:23 +09001039/// Parses the platform version requirement string.
1040fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1041 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001042 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001043 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001044 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001045 )
1046 })
1047}
1048
Jooyung Han35edb8f2021-07-01 16:17:16 +09001049/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1050/// it doesn't require that T implements Clone.
1051enum BorrowedOrOwned<'a, T> {
1052 Borrowed(&'a T),
1053 Owned(T),
1054}
1055
1056impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1057 fn as_ref(&self) -> &T {
1058 match self {
1059 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001060 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001061 }
1062 }
1063}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001064
1065/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1066#[derive(Debug, Default)]
1067struct VirtualMachineService {
1068 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001069 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001070}
1071
1072impl Interface for VirtualMachineService {}
1073
1074impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001075 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1076 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001077 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1078 info!("VM having CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001079 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1080 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1081 })?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001082 let stream = vm.stream.lock().unwrap().take();
1083 vm.callbacks.notify_payload_started(cid, stream);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001084
Seungjae Yoo2e7beea2022-08-24 16:09:12 +09001085 let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap();
1086 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001087 Ok(())
1088 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001089 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001090 Err(Status::new_service_specific_error_str(
1091 -1,
1092 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001093 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001094 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001095 }
Inseob Kim2444af92021-08-31 01:22:50 +09001096
Inseob Kimc7d28c72021-10-25 14:28:10 +00001097 fn notifyPayloadReady(&self) -> binder::Result<()> {
1098 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001099 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1100 info!("VM having CID {} payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001101 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1102 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1103 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001104 vm.callbacks.notify_payload_ready(cid);
1105 Ok(())
1106 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001107 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001108 Err(Status::new_service_specific_error_str(
1109 -1,
1110 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001111 ))
1112 }
1113 }
1114
Inseob Kimc7d28c72021-10-25 14:28:10 +00001115 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1116 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001117 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1118 info!("VM having CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001119 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1120 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1121 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001122 vm.callbacks.notify_payload_finished(cid, exit_code);
1123 Ok(())
1124 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001125 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001126 Err(Status::new_service_specific_error_str(
1127 -1,
1128 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001129 ))
1130 }
1131 }
1132
Alan Stokes2bead0d2022-09-05 16:58:34 +01001133 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001134 let cid = self.cid;
1135 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1136 info!("VM having CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001137 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1138 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1139 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001140 vm.callbacks.notify_error(cid, error_code, message);
1141 Ok(())
1142 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001143 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001144 Err(Status::new_service_specific_error_str(
1145 -1,
1146 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001147 ))
1148 }
1149 }
Seungjae Yoofd9a0622022-10-14 10:01:29 +09001150
1151 fn notifyCpuStatus(&self, status: &VirtualMachineCpuStatus) -> binder::Result<()> {
1152 let cid = self.cid;
1153 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1154 info!("VM having CID {} encountered an error", cid);
1155 write_vm_cpu_status_stats(vm.requester_uid as i32, &vm.name, status);
1156 Ok(())
1157 } else {
1158 error!("notifyCurrentStatus is called from an unknown CID {}", cid);
1159 Err(Status::new_service_specific_error_str(
1160 -1,
1161 Some(format!("cannot find a VM with CID {}", cid)),
1162 ))
1163 }
1164 }
1165
1166 fn notifyMemStatus(&self, status: &VirtualMachineMemStatus) -> binder::Result<()> {
1167 let cid = self.cid;
1168 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1169 info!("VM having CID {} encountered an error", cid);
1170 write_vm_mem_status_stats(vm.requester_uid as i32, &vm.name, status);
1171 Ok(())
1172 } else {
1173 error!("notifyCurrentStatus is called from an unknown CID {}", cid);
1174 Err(Status::new_service_specific_error_str(
1175 -1,
1176 Some(format!("cannot find a VM with CID {}", cid)),
1177 ))
1178 }
1179 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001180}
1181
1182impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001183 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001184 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1185 let mut vm_service = vm.vm_service.lock().unwrap();
1186 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001187 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001188 } else {
1189 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001190 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001191 }
1192 }
1193
1194 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001195 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001196 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001197 BinderFeatures::default(),
1198 )
1199 }
1200}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001201
1202#[cfg(test)]
1203mod tests {
1204 use super::*;
1205
1206 #[test]
1207 fn test_is_allowed_label_for_partition() -> Result<()> {
1208 let expected_results = vec![
1209 ("u:object_r:system_file:s0", true),
1210 ("u:object_r:apk_data_file:s0", true),
1211 ("u:object_r:app_data_file:s0", false),
1212 ("u:object_r:app_data_file:s0:c512,c768", false),
1213 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1214 ("invalid", false),
1215 ("user:role:apk_data_file:severity:categories", true),
1216 ("user:role:apk_data_file:severity:categories:extraneous", false),
1217 ];
1218
1219 for (label, expected_valid) in expected_results {
1220 let context = SeContext::new(label)?;
1221 let result = check_label_is_allowed(&context);
1222 if expected_valid {
1223 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1224 } else if result.is_ok() {
1225 bail!("Expected label {} to be disallowed", label);
1226 }
1227 }
1228 Ok(())
1229 }
1230}