blob: a8f68bc3326ee6bd689c6769b159e8b7eb56a34a [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 Yoodd91f0f2022-11-09 15:25:21 +090017use 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};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090021use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Seungjae Yoofd9a0622022-10-14 10:01:29 +090023use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
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,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090032 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
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};
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090039use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Seungjae Yoofd9a0622022-10-14 10:01:29 +090040 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
David Brazdil451cc962022-10-14 14:08:12 +010041 VM_TOMBSTONES_SERVICE_PORT,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090042};
43use anyhow::{anyhow, bail, Context, Result};
44use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010045use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000046 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
47 SpIBinder, Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000048};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000049use disk::QcowFile;
David Brazdila07a1792022-10-25 13:37:57 +010050use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000051use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Alice Wang86c88cc2022-10-17 08:10:49 +000053use rpcbinder::run_vsock_rpc_server_with_factory;
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};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090059use std::io::{Error, ErrorKind, Read, Write};
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};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
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
David Brazdil41d1a872022-10-05 14:44:19 +010069/// The unique ID of a VM used (together with a port number) for vsock communication.
70pub type Cid = u32;
71
Andrew Walbranf6bf6862021-05-21 12:41:13 +000072pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000075pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076
David Brazdil41d1a872022-10-05 14:44:19 +010077/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
78/// are reserved for the host or other usage.
79const FIRST_GUEST_CID: Cid = 10;
80
81const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
Jiyong Park8611a6c2021-07-09 18:17:44 +090082
Jooyung Han95884632021-07-06 22:27:54 +090083/// The size of zero.img.
84/// Gaps in composite disk images are filled with a shared zero.img.
85const ZERO_FILLER_SIZE: u64 = 4096;
86
Jiyong Park9dd389e2021-08-23 20:42:59 +090087/// Magic string for the instance image
88const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
89
90/// Version of the instance image format
91const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
92
Shikha Panwar7afc1392022-03-24 08:54:43 +000093const CHUNK_RECV_MAX_LEN: usize = 1024;
94
Alan Stokes0d1ef782022-09-27 13:46:35 +010095const MICRODROID_OS_NAME: &str = "microdroid";
96
Andrew Walbranf6bf6862021-05-21 12:41:13 +000097/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090098#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000099pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900100 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000101}
102
Shikha Panward8e35422021-10-11 13:51:27 +0000103impl Interface for VirtualizationService {
104 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
105 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
106 let state = &mut *self.state.lock().unwrap();
107 let vms = state.vms();
108 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
109 for vm in vms {
110 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\tPayload state {:?}", vm.payload_state())
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
116 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
117 .or(Err(StatusCode::UNKNOWN_ERROR))?;
118 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
119 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000120 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
121 .or(Err(StatusCode::UNKNOWN_ERROR))?;
122 }
123 Ok(())
124 }
125}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000126
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000127impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000128 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
129 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000130 ///
131 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000132 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000133 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000134 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900135 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000136 log_fd: Option<&ParcelFileDescriptor>,
137 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000138 let mut is_protected = false;
139 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000140 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000141 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000142 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000143
Andrew Walbrandff3b942021-06-09 15:20:36 +0000144 /// Initialise an empty partition image of the given size to be used as a writable partition.
145 fn initializeWritablePartition(
146 &self,
147 image_fd: &ParcelFileDescriptor,
148 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900149 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000150 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900151 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000152 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000153 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000154 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100155 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000156 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000157 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000158 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900159 // initialize the file. Any data in the file will be erased.
160 image.set_len(0).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 reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900164 )
165 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900166 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000167 Status::new_service_specific_error_str(
168 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100169 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000170 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000171 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000172
Jiyong Park9dd389e2021-08-23 20:42:59 +0900173 match partition_type {
174 PartitionType::RAW => Ok(()),
175 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
176 _ => Err(Error::new(
177 ErrorKind::Unsupported,
178 format!("Unsupported partition type {:?}", partition_type),
179 )),
180 }
181 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000182 Status::new_service_specific_error_str(
183 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100184 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900185 )
186 })?;
187
Andrew Walbrandff3b942021-06-09 15:20:36 +0000188 Ok(())
189 }
190
Jiyong Park0a248432021-08-20 23:32:39 +0900191 /// Creates or update the idsig file by digesting the input APK file.
192 fn createOrUpdateIdsigFile(
193 &self,
194 input_fd: &ParcelFileDescriptor,
195 idsig_fd: &ParcelFileDescriptor,
196 ) -> binder::Result<()> {
197 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
198 // idsig_fd is different from APK digest in input_fd
199
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900200 check_manage_access()?;
201
Jiyong Park0a248432021-08-20 23:32:39 +0900202 let mut input = clone_file(input_fd)?;
203 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
204
205 let mut output = clone_file(idsig_fd)?;
206 output.set_len(0).unwrap();
207 sig.write_into(&mut output).unwrap();
208 Ok(())
209 }
210
Andrew Walbran320b5602021-03-04 16:11:12 +0000211 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
212 /// and as such is only permitted from the shell user.
213 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000214 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000215
216 let state = &mut *self.state.lock().unwrap();
217 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000218 let cids = vms
219 .into_iter()
220 .map(|vm| VirtualMachineDebugInfo {
221 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000222 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000223 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000224 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000225 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000226 })
227 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000228 Ok(cids)
229 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000230
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000231 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
232 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000233 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000234 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000235
David Brazdil3c2ddef2021-03-18 13:09:57 +0000236 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000237 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000238 Ok(())
239 }
240
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000241 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
242 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
243 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000244 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000245 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000246
247 let state = &mut *self.state.lock().unwrap();
248 Ok(state.debug_drop_vm(cid))
249 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000250}
251
Shikha Panwar7afc1392022-03-24 08:54:43 +0000252fn handle_stream_connection_tombstoned() -> Result<()> {
253 let listener =
254 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000255 for incoming_stream in listener.incoming() {
256 let mut incoming_stream = match incoming_stream {
257 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100258 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000259 continue;
260 }
261 Ok(s) => s,
262 };
263 std::thread::spawn(move || {
264 if let Err(e) = handle_tombstone(&mut incoming_stream) {
265 error!("Failed to write tombstone- {:?}", e);
266 }
267 });
268 }
269 Ok(())
270}
271
272fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000273 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000274 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
275 }
276 let tb_connection =
277 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
278 .context("Failed to connect to tombstoned")?;
279 let mut text_output = tb_connection
280 .text_output
281 .as_ref()
282 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
283 let mut num_bytes_read = 0;
284 loop {
285 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
286 let n = stream
287 .read(&mut chunk_recv)
288 .context("Failed to read tombstone data from Vsock stream")?;
289 if n == 0 {
290 break;
291 }
292 num_bytes_read += n;
293 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
294 }
295 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
296 tb_connection.notify_completion()?;
297 Ok(())
298}
299
Jiyong Park8611a6c2021-07-09 18:17:44 +0900300impl VirtualizationService {
301 pub fn init() -> VirtualizationService {
302 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900303
Shikha Panwar7afc1392022-03-24 08:54:43 +0000304 std::thread::spawn(|| {
305 if let Err(e) = handle_stream_connection_tombstoned() {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100306 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000307 }
308 });
309
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900310 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000311 // reference to state (not the state itself) is copied
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000312 let state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900313 std::thread::spawn(move || {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000314 debug!("VirtualMachineService is starting as an RPC service.");
Alice Wang86c88cc2022-10-17 08:10:49 +0000315 if run_vsock_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000316 VirtualMachineService::factory(cid, &state)
317 }) {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900318 debug!("RPC server has shut down gracefully");
319 } else {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000320 panic!("Premature termination of RPC server");
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900321 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900322 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900323 service
324 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000325
326 fn create_vm_internal(
327 &self,
328 config: &VirtualMachineConfig,
329 console_fd: Option<&ParcelFileDescriptor>,
330 log_fd: Option<&ParcelFileDescriptor>,
331 is_protected: &mut bool,
332 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
333 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900334
Alan Stokes7bc146c2022-10-20 17:10:32 +0100335 let is_custom = match config {
336 VirtualMachineConfig::RawConfig(_) => true,
337 VirtualMachineConfig::AppConfig(config) => {
338 // Some features are reserved for platform apps only, even when using
339 // VirtualMachineAppConfig:
340 // - controlling CPUs;
341 // - specifying a config file in the APK.
342 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900343 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100344 };
345 if is_custom {
346 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900347 }
348
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000349 let state = &mut *self.state.lock().unwrap();
350 let console_fd = console_fd.map(clone_file).transpose()?;
351 let log_fd = log_fd.map(clone_file).transpose()?;
352 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000353 let requester_debug_pid = ThreadState::get_calling_pid();
David Brazdil7feea602022-10-05 14:06:01 +0100354 let cid = state.next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000355
356 // Counter to generate unique IDs for temporary image files.
357 let mut next_temporary_image_id = 0;
358 // Files which are referred to from composite images. These must be mapped to the crosvm
359 // child process, and not closed before it is started.
360 let mut indirect_files = vec![];
361
362 // Make directory for temporary files.
363 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
364 create_dir(&temporary_directory).map_err(|e| {
365 // At this point, we do not know the protected status of Vm
366 // setting it to false, though this may not be correct.
367 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100368 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000369 temporary_directory, e
370 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000371 Status::new_service_specific_error_str(
372 -1,
373 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100374 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000375 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000376 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000377 )
378 })?;
379
Alan Stokes7bc146c2022-10-20 17:10:32 +0100380 let (is_app_config, config) = match config {
381 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
382 VirtualMachineConfig::AppConfig(config) => {
383 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000384 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100385 let message = format!("Failed to load app config: {:?}", e);
386 error!("{}", message);
387 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100388 })?;
389 (true, BorrowedOrOwned::Owned(config))
390 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000391 };
392 let config = config.as_ref();
393 *is_protected = config.protectedVm;
394
395 // Check if partition images are labeled incorrectly. This is to prevent random images
396 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100397 // being loaded in a pVM. This applies to everything in the raw config, and everything but
398 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000399 config
400 .disks
401 .iter()
402 .flat_map(|disk| disk.partitions.iter())
403 .filter(|partition| {
404 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100405 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000406 } else {
407 true // all partitions are checked
408 }
409 })
410 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100411 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000412
413 let zero_filler_path = temporary_directory.join("zero.img");
414 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100415 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000416 Status::new_service_specific_error_str(
417 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100418 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000419 )
420 })?;
421
422 // Assemble disk images if needed.
423 let disks = config
424 .disks
425 .iter()
426 .map(|disk| {
427 assemble_disk_image(
428 disk,
429 &zero_filler_path,
430 &temporary_directory,
431 &mut next_temporary_image_id,
432 &mut indirect_files,
433 )
434 })
435 .collect::<Result<Vec<DiskFile>, _>>()?;
436
Jiyong Parke558ab12022-07-07 20:18:55 +0900437 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
438 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900439 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900440 // will be sent back to the client (i.e. the VM owner) for readout.
441 let ramdump_path = temporary_directory.join("ramdump");
442 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100443 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000444 Status::new_service_specific_error_str(
445 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100446 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900447 )
448 })?;
449
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000450 // Actually start the VM.
451 let crosvm_config = CrosvmConfig {
452 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000453 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000454 bootloader: maybe_clone_file(&config.bootloader)?,
455 kernel: maybe_clone_file(&config.kernel)?,
456 initrd: maybe_clone_file(&config.initrd)?,
457 disks,
458 params: config.params.to_owned(),
459 protected: *is_protected,
460 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
461 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900462 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 console_fd,
464 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900465 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000466 indirect_files,
467 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900468 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000469 };
470 let instance = Arc::new(
David Brazdil2d967202022-10-05 13:01:03 +0100471 VmInstance::new(crosvm_config, temporary_directory, requester_uid, requester_debug_pid)
472 .map_err(|e| {
473 error!("Failed to create VM with config {:?}: {:?}", config, e);
474 Status::new_service_specific_error_str(
475 -1,
476 Some(format!("Failed to create VM: {:?}", e)),
477 )
478 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000479 );
480 state.add_vm(Arc::downgrade(&instance));
481 Ok(VirtualMachine::create(instance))
482 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900483}
484
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000485fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900486 let file = OpenOptions::new()
487 .create_new(true)
488 .read(true)
489 .write(true)
490 .open(zero_filler_path)
491 .with_context(|| "Failed to create zero.img")?;
492 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000493 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900494}
495
Jiyong Park9dd389e2021-08-23 20:42:59 +0900496fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
497 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
498 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
499 part.flush()
500}
501
Jiyong Parke558ab12022-07-07 20:18:55 +0900502fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800503 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900504}
505
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000506/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
507///
508/// This may involve assembling a composite disk from a set of partition images.
509fn assemble_disk_image(
510 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900511 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000512 temporary_directory: &Path,
513 next_temporary_image_id: &mut u64,
514 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000515) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000516 let image = if !disk.partitions.is_empty() {
517 if disk.image.is_some() {
518 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000519 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000520 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000521 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000522 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000523 }
524
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000525 let composite_image_filenames =
526 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
527 let (image, partition_files) = make_composite_image(
528 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900529 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000530 &composite_image_filenames.composite,
531 &composite_image_filenames.header,
532 &composite_image_filenames.footer,
533 )
534 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100535 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000536 Status::new_service_specific_error_str(
537 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100538 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000539 )
540 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541
542 // Pass the file descriptors for the various partition files to crosvm when it
543 // is run.
544 indirect_files.extend(partition_files);
545
546 image
547 } else if let Some(image) = &disk.image {
548 clone_file(image)?
549 } else {
550 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000551 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000552 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000553 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000554 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000555 };
556
557 Ok(DiskFile { image, writable: disk.writable })
558}
559
Jooyung Han21e9b922021-06-26 04:14:16 +0900560fn load_app_config(
561 config: &VirtualMachineAppConfig,
562 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900563) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000564 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
565 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900566 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900567
Shikha Panwar22e70452022-10-10 18:32:55 +0000568 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
569 Some(clone_file(file)?)
570 } else {
571 None
572 };
573
Alan Stokes0d1ef782022-09-27 13:46:35 +0100574 let vm_payload_config = match &config.payload {
575 Payload::ConfigPath(config_path) => {
576 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
577 .with_context(|| format!("Couldn't read config from {}", config_path))?
578 }
579 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
580 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900581
Alan Stokes0d1ef782022-09-27 13:46:35 +0100582 // For now, the only supported OS is Microdroid
583 let os_name = vm_payload_config.os.name.as_str();
584 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000585 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900586 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000587
588 // It is safe to construct a filename based on the os_name because we've already checked that it
589 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900590 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
591 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000592 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900593
Andrew Walbrancc045902021-07-27 16:06:17 +0000594 if config.memoryMib > 0 {
595 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000596 }
597
Seungjae Yoo62085c02022-08-12 04:44:52 +0000598 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000599 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900600 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900601 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900602
Shikha Panwar22e70452022-10-10 18:32:55 +0000603 // Microdroid takes additional init ramdisk & (optionally) storage image
604 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
605
606 // Include Microdroid payload disk (contains apks, idsigs) in vm config
607 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100608 config,
609 temporary_directory,
610 apk_file,
611 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100612 &vm_payload_config,
613 &mut vm_config,
614 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900615
Andrew Walbrancc0db522021-07-12 17:03:42 +0000616 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900617}
618
Alan Stokes0d1ef782022-09-27 13:46:35 +0100619fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
620 let mut apk_zip = ZipArchive::new(apk_file)?;
621 let config_file = apk_zip.by_name(config_path)?;
622 Ok(serde_json::from_reader(config_file)?)
623}
624
625fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
626 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
627 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
628 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100629 let task =
630 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100631 VmPayloadConfig {
632 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
633 task: Some(task),
634 apexes: vec![],
635 extra_apks: vec![],
636 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100637 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100638 enable_authfs: false,
639 }
640}
641
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000642/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000643fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000644 temporary_directory: &Path,
645 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000646) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000647 let id = *next_temporary_image_id;
648 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000649 CompositeImageFilenames {
650 composite: temporary_directory.join(format!("composite-{}.img", id)),
651 header: temporary_directory.join(format!("composite-{}-header.img", id)),
652 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
653 }
654}
655
656/// Filenames for a composite disk image, including header and footer partitions.
657#[derive(Clone, Debug, Eq, PartialEq)]
658struct CompositeImageFilenames {
659 /// The composite disk image itself.
660 composite: PathBuf,
661 /// The header partition image.
662 header: PathBuf,
663 /// The footer partition image.
664 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000665}
666
Jiyong Park753553b2021-07-12 21:21:09 +0900667/// Checks whether the caller has a specific permission
668fn check_permission(perm: &str) -> binder::Result<()> {
669 let calling_pid = ThreadState::get_calling_pid();
670 let calling_uid = ThreadState::get_calling_uid();
671 // Root can do anything
672 if calling_uid == 0 {
673 return Ok(());
674 }
675 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
676 binder::get_interface("permission")?;
677 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000678 Ok(())
679 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000680 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900681 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000682 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900683 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000684 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000685}
686
Jiyong Park753553b2021-07-12 21:21:09 +0900687/// Check whether the caller of the current Binder method is allowed to call debug methods.
688fn check_debug_access() -> binder::Result<()> {
689 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
690}
691
692/// Check whether the caller of the current Binder method is allowed to manage VMs
693fn check_manage_access() -> binder::Result<()> {
694 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
695}
696
Inseob Kim1119d702022-05-02 18:01:58 +0900697/// Check whether the caller of the current Binder method is allowed to create custom VMs
698fn check_use_custom_virtual_machine() -> binder::Result<()> {
699 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
700}
701
Jiyong Park029977d2021-11-24 21:56:49 +0900702/// Check if a partition has selinux labels that are not allowed
703fn check_label_for_partition(partition: &Partition) -> Result<()> {
704 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100705 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
706}
707
708// Return whether a partition is exempt from selinux label checks, because we know that it does
709// not contain code and is likely to be generated in an app-writable directory.
710fn is_safe_app_partition(label: &str) -> bool {
711 // See make_payload_disk in payload.rs.
712 label == "vm-instance"
713 || label == "microdroid-apk-idsig"
714 || label == "payload-metadata"
715 || label.starts_with("extra-idsig-")
716}
717
718fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
719 // We only want to allow code in a VM payload to be sourced from places that apps, and the
720 // system, do not have write access to.
721 // (Note that sepolicy must also grant read access for these types to both virtualization
722 // service and crosvm.)
723 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
724 // user devices (W^X).
725 match ctx.selinux_type()? {
726 | "system_file" // immutable dm-verity protected partition
727 | "apk_data_file" // APKs of an installed app
728 | "staging_data_file" // updated/staged APEX imagess
729 | "shell_data_file" // test files created via adb shell
730 => Ok(()),
731 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900732 }
733}
734
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000735/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
736#[derive(Debug)]
737struct VirtualMachine {
738 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100739 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800740 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100741 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000742}
743
744impl VirtualMachine {
745 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100746 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000747 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000748 }
749}
750
751impl Interface for VirtualMachine {}
752
753impl IVirtualMachine for VirtualMachine {
754 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900755 // Don't check permission. The owner of the VM might have passed this binder object to
756 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000757 Ok(self.instance.cid as i32)
758 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000759
Andrew Walbran6b650662021-09-07 13:13:23 +0000760 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900761 // Don't check permission. The owner of the VM might have passed this binder object to
762 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000763 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000764 }
765
766 fn registerCallback(
767 &self,
768 callback: &Strong<dyn IVirtualMachineCallback>,
769 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900770 // Don't check permission. The owner of the VM might have passed this binder object to
771 // others.
772 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000773 // TODO: Should this give an error if the VM is already dead?
774 self.instance.callbacks.add(callback.clone());
775 Ok(())
776 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000777
Andrew Walbranf8d94112021-09-07 11:45:36 +0000778 fn start(&self) -> binder::Result<()> {
779 self.instance.start().map_err(|e| {
780 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000781 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000782 })
783 }
784
Inseob Kima446f802022-07-11 19:46:37 +0900785 fn stop(&self) -> binder::Result<()> {
786 self.instance.kill().map_err(|e| {
787 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000788 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900789 })
790 }
791
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000792 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000793 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000794 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000795 }
796 let stream =
797 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000798 Status::new_service_specific_error_str(
799 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100800 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000801 )
802 })?;
803 Ok(vsock_stream_to_pfd(stream))
804 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000805}
806
807impl Drop for VirtualMachine {
808 fn drop(&mut self) {
809 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900810 if let Err(e) = self.instance.kill() {
811 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
812 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000813 }
814}
815
816/// A set of Binders to be called back in response to various events on the VM, such as when it
817/// dies.
818#[derive(Debug, Default)]
819pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
820
821impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900822 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100823 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900824 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900825 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100826 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100827 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900828 }
829 }
830 }
831
Inseob Kim14cb8692021-08-31 21:50:39 +0900832 /// Call all registered callbacks to notify that the payload is ready to serve.
833 pub fn notify_payload_ready(&self, cid: Cid) {
834 let callbacks = &*self.0.lock().unwrap();
835 for callback in callbacks {
836 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100837 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900838 }
839 }
840 }
841
Inseob Kim2444af92021-08-31 01:22:50 +0900842 /// Call all registered callbacks to notify that the payload has finished.
843 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
844 let callbacks = &*self.0.lock().unwrap();
845 for callback in callbacks {
846 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100847 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900848 }
849 }
850 }
851
Jooyung Handd0a1732021-11-23 15:26:20 +0900852 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100853 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900854 let callbacks = &*self.0.lock().unwrap();
855 for callback in callbacks {
856 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100857 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900858 }
859 }
860 }
861
David Brazdil451cc962022-10-14 14:08:12 +0100862 /// Call all registered callbacks to notify that the payload has provided a standard I/O proxy.
863 pub fn notify_payload_stdio(&self, cid: Cid, fd: ParcelFileDescriptor) {
864 let callbacks = &*self.0.lock().unwrap();
865 for callback in callbacks {
866 if let Err(e) = callback.onPayloadStdio(cid as i32, &fd) {
867 error!("Error notifying payload stdio event from VM CID {}: {:?}", cid, e);
868 }
869 }
870 }
871
Andrew Walbrandae07162021-03-12 17:05:20 +0000872 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000873 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000874 let callbacks = &*self.0.lock().unwrap();
875 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000876 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100877 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000878 }
879 }
880 }
881
Jiyong Parke558ab12022-07-07 20:18:55 +0900882 /// Call all registered callbacks to say that there was a ramdump to download.
883 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
884 let callbacks = &*self.0.lock().unwrap();
885 let pfd = ParcelFileDescriptor::new(ramdump);
886 for callback in callbacks {
887 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100888 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +0900889 }
890 }
891 }
892
Andrew Walbrandae07162021-03-12 17:05:20 +0000893 /// Add a new callback to the set.
894 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
895 self.0.lock().unwrap().push(callback);
896 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000897}
898
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000899/// The mutable state of the VirtualizationService. There should only be one instance of this
900/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800901#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000902struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000903 /// The VMs which have been started. When VMs are started a weak reference is added to this list
904 /// while a strong reference is returned to the caller over Binder. Once all copies of the
905 /// Binder client are dropped the weak reference here will become invalid, and will be removed
906 /// from the list opportunistically the next time `add_vm` is called.
907 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000908
909 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
910 /// This is only used for debugging purposes.
911 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000912}
913
914impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000915 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000916 fn vms(&self) -> Vec<Arc<VmInstance>> {
917 // Attempt to upgrade the weak pointers to strong pointers.
918 self.vms.iter().filter_map(Weak::upgrade).collect()
919 }
920
921 /// Add a new VM to the list.
922 fn add_vm(&mut self, vm: Weak<VmInstance>) {
923 // Garbage collect any entries from the stored list which no longer exist.
924 self.vms.retain(|vm| vm.strong_count() > 0);
925
926 // Actually add the new VM.
927 self.vms.push(vm);
928 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000929
Jiyong Park8611a6c2021-07-09 18:17:44 +0900930 /// Get a VM that corresponds to the given cid
931 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
932 self.vms().into_iter().find(|vm| vm.cid == cid)
933 }
934
David Brazdil3c2ddef2021-03-18 13:09:57 +0000935 /// Store a strong VM reference.
936 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
937 self.debug_held_vms.push(vm);
938 }
939
940 /// Retrieve and remove a strong VM reference.
941 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
942 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100943 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100944 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000945 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000946
David Brazdil7feea602022-10-05 14:06:01 +0100947 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
948 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
949 /// Android is up.
950 fn next_cid(&mut self) -> Result<Cid> {
951 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
952 if let Ok(num) = val.parse::<u32>() {
953 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
954 } else {
955 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
956 FIRST_GUEST_CID
957 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900958 } else {
David Brazdil7feea602022-10-05 14:06:01 +0100959 // First VM since the boot
Jiyong Parkd50a0242021-09-16 21:00:14 +0900960 FIRST_GUEST_CID
David Brazdil7feea602022-10-05 14:06:01 +0100961 };
962 // Persist the last value for next use
963 let str_val = format!("{}", next);
964 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
965 Ok(next)
966 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900967}
968
Andrew Walbran6b650662021-09-07 13:13:23 +0000969/// Gets the `VirtualMachineState` of the given `VmInstance`.
970fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000971 match &*instance.vm_state.lock().unwrap() {
972 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
973 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000974 PayloadState::Starting => VirtualMachineState::STARTING,
975 PayloadState::Started => VirtualMachineState::STARTED,
976 PayloadState::Ready => VirtualMachineState::READY,
977 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900978 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000979 },
980 VmState::Dead => VirtualMachineState::DEAD,
981 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000982 }
983}
984
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000985/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000986pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000987 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000988 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000989 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100990 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000991 )
992 })
993}
994
Andrew Walbrand3a84182021-09-07 14:48:52 +0000995/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
996fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
997 file.as_ref().map(clone_file).transpose()
998}
999
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001000/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1001fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1002 // SAFETY: ownership is transferred from stream to f
1003 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1004 ParcelFileDescriptor::new(f)
1005}
1006
Jiyong Parkdcf17412022-02-08 15:07:23 +09001007/// Parses the platform version requirement string.
1008fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1009 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001010 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001011 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001012 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001013 )
1014 })
1015}
1016
Jooyung Han35edb8f2021-07-01 16:17:16 +09001017/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1018/// it doesn't require that T implements Clone.
1019enum BorrowedOrOwned<'a, T> {
1020 Borrowed(&'a T),
1021 Owned(T),
1022}
1023
1024impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1025 fn as_ref(&self) -> &T {
1026 match self {
1027 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001028 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001029 }
1030 }
1031}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001032
1033/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1034#[derive(Debug, Default)]
1035struct VirtualMachineService {
1036 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001037 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001038}
1039
1040impl Interface for VirtualMachineService {}
1041
1042impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001043 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1044 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001045 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001046 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001047 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1048 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1049 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001050 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001051
Seungjae Yoo2e7beea2022-08-24 16:09:12 +09001052 let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap();
1053 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001054 Ok(())
1055 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001056 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001057 Err(Status::new_service_specific_error_str(
1058 -1,
1059 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001060 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001061 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001062 }
Inseob Kim2444af92021-08-31 01:22:50 +09001063
Inseob Kimc7d28c72021-10-25 14:28:10 +00001064 fn notifyPayloadReady(&self) -> binder::Result<()> {
1065 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001066 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001067 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001068 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1069 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1070 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001071 vm.callbacks.notify_payload_ready(cid);
1072 Ok(())
1073 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001074 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001075 Err(Status::new_service_specific_error_str(
1076 -1,
1077 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001078 ))
1079 }
1080 }
1081
Inseob Kimc7d28c72021-10-25 14:28:10 +00001082 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1083 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001084 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001085 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001086 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1087 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1088 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001089 vm.callbacks.notify_payload_finished(cid, exit_code);
1090 Ok(())
1091 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001092 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001093 Err(Status::new_service_specific_error_str(
1094 -1,
1095 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001096 ))
1097 }
1098 }
1099
Alan Stokes2bead0d2022-09-05 16:58:34 +01001100 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001101 let cid = self.cid;
1102 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001103 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001104 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1105 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1106 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001107 vm.callbacks.notify_error(cid, error_code, message);
1108 Ok(())
1109 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001110 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001111 Err(Status::new_service_specific_error_str(
1112 -1,
1113 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001114 ))
1115 }
1116 }
David Brazdil451cc962022-10-14 14:08:12 +01001117
1118 fn connectPayloadStdioProxy(&self, port: i32) -> binder::Result<()> {
1119 let cid = self.cid;
1120 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1121 info!("VM with CID {} started a stdio proxy", cid);
1122 let stream = VsockStream::connect_with_cid_port(cid, port as u32).map_err(|e| {
1123 Status::new_service_specific_error_str(
1124 -1,
1125 Some(format!("Failed to connect to guest stdio proxy: {:?}", e)),
1126 )
1127 })?;
1128 vm.callbacks.notify_payload_stdio(cid, vsock_stream_to_pfd(stream));
1129 Ok(())
1130 } else {
1131 error!("connectPayloadStdioProxy is called from an unknown CID {}", cid);
1132 Err(Status::new_service_specific_error_str(
1133 -1,
1134 Some(format!("cannot find a VM with CID {}", cid)),
1135 ))
1136 }
1137 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001138}
1139
1140impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001141 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001142 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1143 let mut vm_service = vm.vm_service.lock().unwrap();
1144 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001145 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001146 } else {
1147 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001148 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001149 }
1150 }
1151
1152 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001153 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001154 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001155 BinderFeatures::default(),
1156 )
1157 }
1158}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001159
1160#[cfg(test)]
1161mod tests {
1162 use super::*;
1163
1164 #[test]
1165 fn test_is_allowed_label_for_partition() -> Result<()> {
1166 let expected_results = vec![
1167 ("u:object_r:system_file:s0", true),
1168 ("u:object_r:apk_data_file:s0", true),
1169 ("u:object_r:app_data_file:s0", false),
1170 ("u:object_r:app_data_file:s0:c512,c768", false),
1171 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1172 ("invalid", false),
1173 ("user:role:apk_data_file:severity:categories", true),
1174 ("user:role:apk_data_file:severity:categories:extraneous", false),
1175 ];
1176
1177 for (label, expected_valid) in expected_results {
1178 let context = SeContext::new(label)?;
1179 let result = check_label_is_allowed(&context);
1180 if expected_valid {
1181 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1182 } else if result.is_ok() {
1183 bail!("Expected label {} to be disallowed", label);
1184 }
1185 }
1186 Ok(())
1187 }
1188}