blob: e8cbb6e898c6e838efeb0fc6ede942db1714b3ab [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 Yooacf559a2022-08-12 04:44:51 +000017use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000018use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000019use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000020use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Jiyong Parkd50a0242021-09-16 21:00:14 +090021use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID};
Jiyong Park029977d2021-11-24 21:56:49 +090022use crate::selinux::{SeContext, getfilecon};
Jiyong Park753553b2021-07-12 21:21:09 +090023use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000025 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000026 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010027 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000028 IVirtualMachineCallback::IVirtualMachineCallback,
29 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090030 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 PartitionType::PartitionType,
Alan Stokes0d1ef782022-09-27 13:46:35 +010032 VirtualMachineAppConfig::{VirtualMachineAppConfig, Payload::Payload},
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010035 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090036 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090038};
Alan Stokes0e82b502022-08-08 14:44:48 +010039use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000040 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
41 SpIBinder, Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000042};
Alan Stokes2bead0d2022-09-05 16:58:34 +010043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Alan Stokes0cc59ee2021-09-24 11:20:34 +010044 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
Shikha Panwar7afc1392022-03-24 08:54:43 +000045 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090046};
Alan Stokes2bead0d2022-09-05 16:58:34 +010047use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
Jiyong Parkd50a0242021-09-16 21:00:14 +090048use anyhow::{anyhow, bail, Context, Result};
Andrew Walbran7eb5ca42022-08-08 15:33:34 +000049use rpcbinder::run_rpc_server_with_factory;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000050use disk::QcowFile;
Alice Wang1bf3d782022-09-28 07:56:36 +000051use apkverify::{HashAlgorithm, V4Signature};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000052use log::{debug, error, info, warn};
Alan Stokes0d1ef782022-09-27 13:46:35 +010053use microdroid_payload_config::{VmPayloadConfig, OsConfig, Task, TaskType};
Jiyong Parkd50a0242021-09-16 21:00:14 +090054use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090055use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000056use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000057use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010058use std::fs::{create_dir, File, OpenOptions};
Shikha Panwar7afc1392022-03-24 08:54:43 +000059use std::io::{Error, ErrorKind, Write, Read};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000060use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000061use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000062use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000063use std::sync::{Arc, Mutex, Weak};
Shikha Panwar7afc1392022-03-24 08:54:43 +000064use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrancc0db522021-07-12 17:03:42 +000065use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000066use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090067use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000068
Andrew Walbranf6bf6862021-05-21 12:41:13 +000069pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000070
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000072pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073
Jiyong Park8611a6c2021-07-09 18:17:44 +090074/// The CID representing the host VM
75const VMADDR_CID_HOST: u32 = 2;
76
Jooyung Han95884632021-07-06 22:27:54 +090077/// The size of zero.img.
78/// Gaps in composite disk images are filled with a shared zero.img.
79const ZERO_FILLER_SIZE: u64 = 4096;
80
Jiyong Park9dd389e2021-08-23 20:42:59 +090081/// Magic string for the instance image
82const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
83
84/// Version of the instance image format
85const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
86
Shikha Panwar7afc1392022-03-24 08:54:43 +000087const CHUNK_RECV_MAX_LEN: usize = 1024;
88
Alan Stokes0d1ef782022-09-27 13:46:35 +010089const MICRODROID_OS_NAME: &str = "microdroid";
90
Andrew Walbranf6bf6862021-05-21 12:41:13 +000091/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090092#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000093pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090094 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000095}
96
Shikha Panward8e35422021-10-11 13:51:27 +000097impl Interface for VirtualizationService {
98 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
99 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
100 let state = &mut *self.state.lock().unwrap();
101 let vms = state.vms();
102 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
103 for vm in vms {
104 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
105 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
106 .or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\tPayload state {:?}", vm.payload_state())
108 .or(Err(StatusCode::UNKNOWN_ERROR))?;
109 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
113 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000114 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
115 .or(Err(StatusCode::UNKNOWN_ERROR))?;
116 }
117 Ok(())
118 }
119}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000121impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
123 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000124 ///
125 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000127 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000128 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900129 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000130 log_fd: Option<&ParcelFileDescriptor>,
131 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000132 let mut is_protected = false;
133 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000134 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000135 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000136 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000137
Andrew Walbrandff3b942021-06-09 15:20:36 +0000138 /// Initialise an empty partition image of the given size to be used as a writable partition.
139 fn initializeWritablePartition(
140 &self,
141 image_fd: &ParcelFileDescriptor,
142 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900143 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000144 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900145 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000146 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000147 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000148 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100149 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000150 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000151 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000152 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900153 // initialize the file. Any data in the file will be erased.
154 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000155 Status::new_service_specific_error_str(
156 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100157 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900158 )
159 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900160 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000161 Status::new_service_specific_error_str(
162 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100163 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000164 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000165 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000166
Jiyong Park9dd389e2021-08-23 20:42:59 +0900167 match partition_type {
168 PartitionType::RAW => Ok(()),
169 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
170 _ => Err(Error::new(
171 ErrorKind::Unsupported,
172 format!("Unsupported partition type {:?}", partition_type),
173 )),
174 }
175 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000176 Status::new_service_specific_error_str(
177 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100178 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900179 )
180 })?;
181
Andrew Walbrandff3b942021-06-09 15:20:36 +0000182 Ok(())
183 }
184
Jiyong Park0a248432021-08-20 23:32:39 +0900185 /// Creates or update the idsig file by digesting the input APK file.
186 fn createOrUpdateIdsigFile(
187 &self,
188 input_fd: &ParcelFileDescriptor,
189 idsig_fd: &ParcelFileDescriptor,
190 ) -> binder::Result<()> {
191 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
192 // idsig_fd is different from APK digest in input_fd
193
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900194 check_manage_access()?;
195
Jiyong Park0a248432021-08-20 23:32:39 +0900196 let mut input = clone_file(input_fd)?;
197 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
198
199 let mut output = clone_file(idsig_fd)?;
200 output.set_len(0).unwrap();
201 sig.write_into(&mut output).unwrap();
202 Ok(())
203 }
204
Andrew Walbran320b5602021-03-04 16:11:12 +0000205 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
206 /// and as such is only permitted from the shell user.
207 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000208 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000209
210 let state = &mut *self.state.lock().unwrap();
211 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000212 let cids = vms
213 .into_iter()
214 .map(|vm| VirtualMachineDebugInfo {
215 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000216 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000217 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000218 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000219 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000220 })
221 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000222 Ok(cids)
223 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000224
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000225 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
226 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000227 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000228 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000229
David Brazdil3c2ddef2021-03-18 13:09:57 +0000230 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000231 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000232 Ok(())
233 }
234
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000235 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
236 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
237 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000238 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000239 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000240
241 let state = &mut *self.state.lock().unwrap();
242 Ok(state.debug_drop_vm(cid))
243 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000244}
245
Shikha Panwar7afc1392022-03-24 08:54:43 +0000246fn handle_stream_connection_tombstoned() -> Result<()> {
247 let listener =
248 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
249 info!("Listening to tombstones from guests ...");
250 for incoming_stream in listener.incoming() {
251 let mut incoming_stream = match incoming_stream {
252 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100253 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000254 continue;
255 }
256 Ok(s) => s,
257 };
258 std::thread::spawn(move || {
259 if let Err(e) = handle_tombstone(&mut incoming_stream) {
260 error!("Failed to write tombstone- {:?}", e);
261 }
262 });
263 }
264 Ok(())
265}
266
267fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000268 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000269 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
270 }
271 let tb_connection =
272 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
273 .context("Failed to connect to tombstoned")?;
274 let mut text_output = tb_connection
275 .text_output
276 .as_ref()
277 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
278 let mut num_bytes_read = 0;
279 loop {
280 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
281 let n = stream
282 .read(&mut chunk_recv)
283 .context("Failed to read tombstone data from Vsock stream")?;
284 if n == 0 {
285 break;
286 }
287 num_bytes_read += n;
288 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
289 }
290 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
291 tb_connection.notify_completion()?;
292 Ok(())
293}
294
Jiyong Park8611a6c2021-07-09 18:17:44 +0900295impl VirtualizationService {
296 pub fn init() -> VirtualizationService {
297 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900298
299 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900300 let state = service.state.clone(); // reference to state (not the state itself) is copied
301 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900302 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900303 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900304
Shikha Panwar7afc1392022-03-24 08:54:43 +0000305 std::thread::spawn(|| {
306 if let Err(e) = handle_stream_connection_tombstoned() {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100307 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000308 }
309 });
310
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900311 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000312 // reference to state (not the state itself) is copied
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000313 let state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900314 std::thread::spawn(move || {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000315 debug!("VirtualMachineService is starting as an RPC service.");
316 if run_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| {
317 VirtualMachineService::factory(cid, &state)
318 }) {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900319 debug!("RPC server has shut down gracefully");
320 } else {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000321 panic!("Premature termination of RPC server");
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900322 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900323 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900324 service
325 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000326
327 fn create_vm_internal(
328 &self,
329 config: &VirtualMachineConfig,
330 console_fd: Option<&ParcelFileDescriptor>,
331 log_fd: Option<&ParcelFileDescriptor>,
332 is_protected: &mut bool,
333 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
334 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900335
336 if let VirtualMachineConfig::RawConfig(config) = config {
337 if config.protectedVm {
338 check_use_custom_virtual_machine()?;
339 }
340 }
341
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000342 let state = &mut *self.state.lock().unwrap();
343 let console_fd = console_fd.map(clone_file).transpose()?;
344 let log_fd = log_fd.map(clone_file).transpose()?;
345 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000346 let requester_debug_pid = ThreadState::get_calling_pid();
347 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
348
349 // Counter to generate unique IDs for temporary image files.
350 let mut next_temporary_image_id = 0;
351 // Files which are referred to from composite images. These must be mapped to the crosvm
352 // child process, and not closed before it is started.
353 let mut indirect_files = vec![];
354
355 // Make directory for temporary files.
356 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
357 create_dir(&temporary_directory).map_err(|e| {
358 // At this point, we do not know the protected status of Vm
359 // setting it to false, though this may not be correct.
360 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100361 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000362 temporary_directory, e
363 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000364 Status::new_service_specific_error_str(
365 -1,
366 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100367 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000368 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000369 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000370 )
371 })?;
372
373 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
374
375 let config = match config {
376 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
377 load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000378 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100379 let message = format!("Failed to load app config: {:?}", e);
380 error!("{}", message);
381 Status::new_service_specific_error_str(-1, Some(message))
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000382 })?,
383 ),
384 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
385 };
386 let config = config.as_ref();
387 *is_protected = config.protectedVm;
388
389 // Check if partition images are labeled incorrectly. This is to prevent random images
390 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100391 // being loaded in a pVM. This applies to everything in the raw config, and everything but
392 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000393 config
394 .disks
395 .iter()
396 .flat_map(|disk| disk.partitions.iter())
397 .filter(|partition| {
398 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100399 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000400 } else {
401 true // all partitions are checked
402 }
403 })
404 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100405 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000406
407 let zero_filler_path = temporary_directory.join("zero.img");
408 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100409 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000410 Status::new_service_specific_error_str(
411 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100412 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000413 )
414 })?;
415
416 // Assemble disk images if needed.
417 let disks = config
418 .disks
419 .iter()
420 .map(|disk| {
421 assemble_disk_image(
422 disk,
423 &zero_filler_path,
424 &temporary_directory,
425 &mut next_temporary_image_id,
426 &mut indirect_files,
427 )
428 })
429 .collect::<Result<Vec<DiskFile>, _>>()?;
430
Jiyong Parke558ab12022-07-07 20:18:55 +0900431 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
432 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900433 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900434 // will be sent back to the client (i.e. the VM owner) for readout.
435 let ramdump_path = temporary_directory.join("ramdump");
436 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100437 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000438 Status::new_service_specific_error_str(
439 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100440 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900441 )
442 })?;
443
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000444 // Actually start the VM.
445 let crosvm_config = CrosvmConfig {
446 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000447 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000448 bootloader: maybe_clone_file(&config.bootloader)?,
449 kernel: maybe_clone_file(&config.kernel)?,
450 initrd: maybe_clone_file(&config.initrd)?,
451 disks,
452 params: config.params.to_owned(),
453 protected: *is_protected,
454 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
455 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900456 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000457 console_fd,
458 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900459 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000460 indirect_files,
461 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900462 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 };
464 let instance = Arc::new(
David Brazdil2d967202022-10-05 13:01:03 +0100465 VmInstance::new(crosvm_config, temporary_directory, requester_uid, requester_debug_pid)
466 .map_err(|e| {
467 error!("Failed to create VM with config {:?}: {:?}", config, e);
468 Status::new_service_specific_error_str(
469 -1,
470 Some(format!("Failed to create VM: {:?}", e)),
471 )
472 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000473 );
474 state.add_vm(Arc::downgrade(&instance));
475 Ok(VirtualMachine::create(instance))
476 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900477}
478
Andrew Walbran6b650662021-09-07 13:13:23 +0000479/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
480/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900481fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900482 let listener =
483 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900484 for stream in listener.incoming() {
485 let stream = match stream {
486 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100487 warn!("invalid incoming connection: {:?}", e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900488 continue;
489 }
490 Ok(s) => s,
491 };
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000492 if let Ok(addr) = stream.peer_addr() {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900493 let cid = addr.cid();
494 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900495 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900496 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700497 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900498 } else {
499 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900500 }
501 }
502 }
503 Ok(())
504}
505
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000506fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900507 let file = OpenOptions::new()
508 .create_new(true)
509 .read(true)
510 .write(true)
511 .open(zero_filler_path)
512 .with_context(|| "Failed to create zero.img")?;
513 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000514 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900515}
516
Jiyong Park9dd389e2021-08-23 20:42:59 +0900517fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
518 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
519 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
520 part.flush()
521}
522
Jiyong Parke558ab12022-07-07 20:18:55 +0900523fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
524 File::create(&ramdump_path)
525 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
526}
527
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000528/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
529///
530/// This may involve assembling a composite disk from a set of partition images.
531fn assemble_disk_image(
532 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900533 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000534 temporary_directory: &Path,
535 next_temporary_image_id: &mut u64,
536 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000537) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000538 let image = if !disk.partitions.is_empty() {
539 if disk.image.is_some() {
540 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000541 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000542 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000543 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000544 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000545 }
546
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000547 let composite_image_filenames =
548 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
549 let (image, partition_files) = make_composite_image(
550 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900551 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000552 &composite_image_filenames.composite,
553 &composite_image_filenames.header,
554 &composite_image_filenames.footer,
555 )
556 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100557 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000558 Status::new_service_specific_error_str(
559 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100560 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000561 )
562 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000563
564 // Pass the file descriptors for the various partition files to crosvm when it
565 // is run.
566 indirect_files.extend(partition_files);
567
568 image
569 } else if let Some(image) = &disk.image {
570 clone_file(image)?
571 } else {
572 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000573 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000574 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000575 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000576 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000577 };
578
579 Ok(DiskFile { image, writable: disk.writable })
580}
581
Jooyung Han21e9b922021-06-26 04:14:16 +0900582fn load_app_config(
583 config: &VirtualMachineAppConfig,
584 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900585) -> Result<VirtualMachineRawConfig> {
Alan Stokes82f389c2022-09-08 12:23:52 +0100586 // Controlling CPUs is reserved for platform apps only, even when using
587 // VirtualMachineAppConfig.
Victor Hsiehf219cd82022-09-09 13:13:11 -0700588 if !config.taskProfiles.is_empty() {
Alan Stokes82f389c2022-09-08 12:23:52 +0100589 check_use_custom_virtual_machine()?
590 }
591
Andrew Walbrancc0db522021-07-12 17:03:42 +0000592 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
593 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900594 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900595
Shikha Panwar22e70452022-10-10 18:32:55 +0000596 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
597 Some(clone_file(file)?)
598 } else {
599 None
600 };
601
Alan Stokes0d1ef782022-09-27 13:46:35 +0100602 let vm_payload_config = match &config.payload {
603 Payload::ConfigPath(config_path) => {
604 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
605 .with_context(|| format!("Couldn't read config from {}", config_path))?
606 }
607 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
608 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900609
Alan Stokes0d1ef782022-09-27 13:46:35 +0100610 // For now, the only supported OS is Microdroid
611 let os_name = vm_payload_config.os.name.as_str();
612 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000613 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900614 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000615
616 // It is safe to construct a filename based on the os_name because we've already checked that it
617 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900618 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
619 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000620 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900621
Andrew Walbrancc045902021-07-27 16:06:17 +0000622 if config.memoryMib > 0 {
623 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000624 }
625
Seungjae Yoo62085c02022-08-12 04:44:52 +0000626 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000627 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900628 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900629 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900630
Shikha Panwar22e70452022-10-10 18:32:55 +0000631 // Microdroid takes additional init ramdisk & (optionally) storage image
632 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
633
634 // Include Microdroid payload disk (contains apks, idsigs) in vm config
635 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100636 config,
637 temporary_directory,
638 apk_file,
639 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100640 &vm_payload_config,
641 &mut vm_config,
642 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900643
Andrew Walbrancc0db522021-07-12 17:03:42 +0000644 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900645}
646
Alan Stokes0d1ef782022-09-27 13:46:35 +0100647fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
648 let mut apk_zip = ZipArchive::new(apk_file)?;
649 let config_file = apk_zip.by_name(config_path)?;
650 Ok(serde_json::from_reader(config_file)?)
651}
652
653fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
654 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
655 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
656 // payload config that we send it via the metadata file.
657 let task = Task {
658 type_: TaskType::MicrodroidLauncher,
659 command: payload_config.payloadPath.clone(),
660 args: payload_config.args.clone(),
661 };
662 VmPayloadConfig {
663 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
664 task: Some(task),
665 apexes: vec![],
666 extra_apks: vec![],
667 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100668 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100669 enable_authfs: false,
670 }
671}
672
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000673/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000674fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000675 temporary_directory: &Path,
676 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000677) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000678 let id = *next_temporary_image_id;
679 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000680 CompositeImageFilenames {
681 composite: temporary_directory.join(format!("composite-{}.img", id)),
682 header: temporary_directory.join(format!("composite-{}-header.img", id)),
683 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
684 }
685}
686
687/// Filenames for a composite disk image, including header and footer partitions.
688#[derive(Clone, Debug, Eq, PartialEq)]
689struct CompositeImageFilenames {
690 /// The composite disk image itself.
691 composite: PathBuf,
692 /// The header partition image.
693 header: PathBuf,
694 /// The footer partition image.
695 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696}
697
Jiyong Park753553b2021-07-12 21:21:09 +0900698/// Checks whether the caller has a specific permission
699fn check_permission(perm: &str) -> binder::Result<()> {
700 let calling_pid = ThreadState::get_calling_pid();
701 let calling_uid = ThreadState::get_calling_uid();
702 // Root can do anything
703 if calling_uid == 0 {
704 return Ok(());
705 }
706 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
707 binder::get_interface("permission")?;
708 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000709 Ok(())
710 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000711 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900712 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000713 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900714 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000715 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000716}
717
Jiyong Park753553b2021-07-12 21:21:09 +0900718/// Check whether the caller of the current Binder method is allowed to call debug methods.
719fn check_debug_access() -> binder::Result<()> {
720 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
721}
722
723/// Check whether the caller of the current Binder method is allowed to manage VMs
724fn check_manage_access() -> binder::Result<()> {
725 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
726}
727
Inseob Kim1119d702022-05-02 18:01:58 +0900728/// Check whether the caller of the current Binder method is allowed to create custom VMs
729fn check_use_custom_virtual_machine() -> binder::Result<()> {
730 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
731}
732
Jiyong Park029977d2021-11-24 21:56:49 +0900733/// Check if a partition has selinux labels that are not allowed
734fn check_label_for_partition(partition: &Partition) -> Result<()> {
735 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100736 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
737}
738
739// Return whether a partition is exempt from selinux label checks, because we know that it does
740// not contain code and is likely to be generated in an app-writable directory.
741fn is_safe_app_partition(label: &str) -> bool {
742 // See make_payload_disk in payload.rs.
743 label == "vm-instance"
744 || label == "microdroid-apk-idsig"
745 || label == "payload-metadata"
746 || label.starts_with("extra-idsig-")
747}
748
749fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
750 // We only want to allow code in a VM payload to be sourced from places that apps, and the
751 // system, do not have write access to.
752 // (Note that sepolicy must also grant read access for these types to both virtualization
753 // service and crosvm.)
754 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
755 // user devices (W^X).
756 match ctx.selinux_type()? {
757 | "system_file" // immutable dm-verity protected partition
758 | "apk_data_file" // APKs of an installed app
759 | "staging_data_file" // updated/staged APEX imagess
760 | "shell_data_file" // test files created via adb shell
761 => Ok(()),
762 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900763 }
764}
765
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000766/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
767#[derive(Debug)]
768struct VirtualMachine {
769 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100770 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800771 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100772 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000773}
774
775impl VirtualMachine {
776 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100777 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000778 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000779 }
780}
781
782impl Interface for VirtualMachine {}
783
784impl IVirtualMachine for VirtualMachine {
785 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900786 // Don't check permission. The owner of the VM might have passed this binder object to
787 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000788 Ok(self.instance.cid as i32)
789 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000790
Andrew Walbran6b650662021-09-07 13:13:23 +0000791 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900792 // Don't check permission. The owner of the VM might have passed this binder object to
793 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000794 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000795 }
796
797 fn registerCallback(
798 &self,
799 callback: &Strong<dyn IVirtualMachineCallback>,
800 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900801 // Don't check permission. The owner of the VM might have passed this binder object to
802 // others.
803 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000804 // TODO: Should this give an error if the VM is already dead?
805 self.instance.callbacks.add(callback.clone());
806 Ok(())
807 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000808
Andrew Walbranf8d94112021-09-07 11:45:36 +0000809 fn start(&self) -> binder::Result<()> {
810 self.instance.start().map_err(|e| {
811 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000812 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000813 })
814 }
815
Inseob Kima446f802022-07-11 19:46:37 +0900816 fn stop(&self) -> binder::Result<()> {
817 self.instance.kill().map_err(|e| {
818 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000819 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900820 })
821 }
822
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000823 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000824 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000825 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000826 }
827 let stream =
828 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000829 Status::new_service_specific_error_str(
830 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100831 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000832 )
833 })?;
834 Ok(vsock_stream_to_pfd(stream))
835 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000836}
837
838impl Drop for VirtualMachine {
839 fn drop(&mut self) {
840 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900841 if let Err(e) = self.instance.kill() {
842 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
843 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000844 }
845}
846
847/// A set of Binders to be called back in response to various events on the VM, such as when it
848/// dies.
849#[derive(Debug, Default)]
850pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
851
852impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900853 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900854 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900855 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900856 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900857 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900858 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100859 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900860 }
861 }
862 }
863
Inseob Kim14cb8692021-08-31 21:50:39 +0900864 /// Call all registered callbacks to notify that the payload is ready to serve.
865 pub fn notify_payload_ready(&self, cid: Cid) {
866 let callbacks = &*self.0.lock().unwrap();
867 for callback in callbacks {
868 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100869 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900870 }
871 }
872 }
873
Inseob Kim2444af92021-08-31 01:22:50 +0900874 /// Call all registered callbacks to notify that the payload has finished.
875 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
876 let callbacks = &*self.0.lock().unwrap();
877 for callback in callbacks {
878 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100879 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900880 }
881 }
882 }
883
Jooyung Handd0a1732021-11-23 15:26:20 +0900884 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100885 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900886 let callbacks = &*self.0.lock().unwrap();
887 for callback in callbacks {
888 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100889 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900890 }
891 }
892 }
893
Andrew Walbrandae07162021-03-12 17:05:20 +0000894 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000895 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000896 let callbacks = &*self.0.lock().unwrap();
897 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000898 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100899 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000900 }
901 }
902 }
903
Jiyong Parke558ab12022-07-07 20:18:55 +0900904 /// Call all registered callbacks to say that there was a ramdump to download.
905 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
906 let callbacks = &*self.0.lock().unwrap();
907 let pfd = ParcelFileDescriptor::new(ramdump);
908 for callback in callbacks {
909 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100910 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +0900911 }
912 }
913 }
914
Andrew Walbrandae07162021-03-12 17:05:20 +0000915 /// Add a new callback to the set.
916 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
917 self.0.lock().unwrap().push(callback);
918 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000919}
920
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000921/// The mutable state of the VirtualizationService. There should only be one instance of this
922/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800923#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000924struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000925 /// The VMs which have been started. When VMs are started a weak reference is added to this list
926 /// while a strong reference is returned to the caller over Binder. Once all copies of the
927 /// Binder client are dropped the weak reference here will become invalid, and will be removed
928 /// from the list opportunistically the next time `add_vm` is called.
929 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000930
931 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
932 /// This is only used for debugging purposes.
933 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000934}
935
936impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000937 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000938 fn vms(&self) -> Vec<Arc<VmInstance>> {
939 // Attempt to upgrade the weak pointers to strong pointers.
940 self.vms.iter().filter_map(Weak::upgrade).collect()
941 }
942
943 /// Add a new VM to the list.
944 fn add_vm(&mut self, vm: Weak<VmInstance>) {
945 // Garbage collect any entries from the stored list which no longer exist.
946 self.vms.retain(|vm| vm.strong_count() > 0);
947
948 // Actually add the new VM.
949 self.vms.push(vm);
950 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000951
Jiyong Park8611a6c2021-07-09 18:17:44 +0900952 /// Get a VM that corresponds to the given cid
953 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
954 self.vms().into_iter().find(|vm| vm.cid == cid)
955 }
956
David Brazdil3c2ddef2021-03-18 13:09:57 +0000957 /// Store a strong VM reference.
958 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
959 self.debug_held_vms.push(vm);
960 }
961
962 /// Retrieve and remove a strong VM reference.
963 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
964 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100965 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100966 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000967 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000968}
969
Jiyong Parkd50a0242021-09-16 21:00:14 +0900970/// Get the next available CID, or an error if we have run out. The last CID used is stored in
971/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
972/// Android is up.
973fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000974 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900975 if let Ok(num) = val.parse::<u32>() {
976 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
977 } else {
978 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
979 FIRST_GUEST_CID
980 }
981 } else {
982 // First VM since the boot
983 FIRST_GUEST_CID
984 };
985 // Persist the last value for next use
986 let str_val = format!("{}", next);
987 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
988 Ok(next)
989}
990
Andrew Walbran6b650662021-09-07 13:13:23 +0000991/// Gets the `VirtualMachineState` of the given `VmInstance`.
992fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000993 match &*instance.vm_state.lock().unwrap() {
994 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
995 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000996 PayloadState::Starting => VirtualMachineState::STARTING,
997 PayloadState::Started => VirtualMachineState::STARTED,
998 PayloadState::Ready => VirtualMachineState::READY,
999 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001000 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001001 },
1002 VmState::Dead => VirtualMachineState::DEAD,
1003 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001004 }
1005}
1006
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001007/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001008pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001009 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001010 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001011 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001012 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001013 )
1014 })
1015}
1016
Andrew Walbrand3a84182021-09-07 14:48:52 +00001017/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1018fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1019 file.as_ref().map(clone_file).transpose()
1020}
1021
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001022/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1023fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1024 // SAFETY: ownership is transferred from stream to f
1025 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1026 ParcelFileDescriptor::new(f)
1027}
1028
Jiyong Parkdcf17412022-02-08 15:07:23 +09001029/// Parses the platform version requirement string.
1030fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1031 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001032 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001033 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001034 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001035 )
1036 })
1037}
1038
Jooyung Han35edb8f2021-07-01 16:17:16 +09001039/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1040/// it doesn't require that T implements Clone.
1041enum BorrowedOrOwned<'a, T> {
1042 Borrowed(&'a T),
1043 Owned(T),
1044}
1045
1046impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1047 fn as_ref(&self) -> &T {
1048 match self {
1049 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001050 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001051 }
1052 }
1053}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001054
1055/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1056#[derive(Debug, Default)]
1057struct VirtualMachineService {
1058 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001059 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001060}
1061
1062impl Interface for VirtualMachineService {}
1063
1064impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001065 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1066 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001067 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1068 info!("VM having CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001069 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1070 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1071 })?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001072 let stream = vm.stream.lock().unwrap().take();
1073 vm.callbacks.notify_payload_started(cid, stream);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001074
Seungjae Yoo2e7beea2022-08-24 16:09:12 +09001075 let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap();
1076 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001077 Ok(())
1078 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001079 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001080 Err(Status::new_service_specific_error_str(
1081 -1,
1082 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001083 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001084 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001085 }
Inseob Kim2444af92021-08-31 01:22:50 +09001086
Inseob Kimc7d28c72021-10-25 14:28:10 +00001087 fn notifyPayloadReady(&self) -> binder::Result<()> {
1088 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001089 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1090 info!("VM having CID {} payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001091 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1092 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1093 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001094 vm.callbacks.notify_payload_ready(cid);
1095 Ok(())
1096 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001097 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001098 Err(Status::new_service_specific_error_str(
1099 -1,
1100 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001101 ))
1102 }
1103 }
1104
Inseob Kimc7d28c72021-10-25 14:28:10 +00001105 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1106 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001107 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1108 info!("VM having CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001109 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1110 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1111 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001112 vm.callbacks.notify_payload_finished(cid, exit_code);
1113 Ok(())
1114 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001115 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001116 Err(Status::new_service_specific_error_str(
1117 -1,
1118 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001119 ))
1120 }
1121 }
1122
Alan Stokes2bead0d2022-09-05 16:58:34 +01001123 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001124 let cid = self.cid;
1125 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1126 info!("VM having CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001127 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1128 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1129 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001130 vm.callbacks.notify_error(cid, error_code, message);
1131 Ok(())
1132 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001133 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001134 Err(Status::new_service_specific_error_str(
1135 -1,
1136 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001137 ))
1138 }
1139 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001140}
1141
1142impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001143 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001144 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1145 let mut vm_service = vm.vm_service.lock().unwrap();
1146 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001147 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001148 } else {
1149 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001150 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001151 }
1152 }
1153
1154 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001155 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001156 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001157 BinderFeatures::default(),
1158 )
1159 }
1160}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001161
1162#[cfg(test)]
1163mod tests {
1164 use super::*;
1165
1166 #[test]
1167 fn test_is_allowed_label_for_partition() -> Result<()> {
1168 let expected_results = vec![
1169 ("u:object_r:system_file:s0", true),
1170 ("u:object_r:apk_data_file:s0", true),
1171 ("u:object_r:app_data_file:s0", false),
1172 ("u:object_r:app_data_file:s0:c512,c768", false),
1173 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1174 ("invalid", false),
1175 ("user:role:apk_data_file:severity:categories", true),
1176 ("user:role:apk_data_file:severity:categories:extraneous", false),
1177 ];
1178
1179 for (label, expected_valid) in expected_results {
1180 let context = SeContext::new(label)?;
1181 let result = check_label_is_allowed(&context);
1182 if expected_valid {
1183 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1184 } else if result.is_ok() {
1185 bail!("Expected label {} to be disallowed", label);
1186 }
1187 }
1188 Ok(())
1189 }
1190}