blob: dcc2d489411c8616da49a7b991641d4c5b719c3c [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};
Andrew Walbrancc0db522021-07-12 17:03:42 +000020use crate::payload::add_microdroid_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,
Jooyung Han21e9b922021-06-26 04:14:16 +090032 VirtualMachineAppConfig::VirtualMachineAppConfig,
33 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090035 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090037};
Alan Stokes0e82b502022-08-08 14:44:48 +010038use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000039 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
40 SpIBinder, Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000041};
Alan Stokes2bead0d2022-09-05 16:58:34 +010042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Alan Stokes0cc59ee2021-09-24 11:20:34 +010043 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
Shikha Panwar7afc1392022-03-24 08:54:43 +000044 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045};
Alan Stokes2bead0d2022-09-05 16:58:34 +010046use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
Jiyong Parkd50a0242021-09-16 21:00:14 +090047use anyhow::{anyhow, bail, Context, Result};
Andrew Walbran7eb5ca42022-08-08 15:33:34 +000048use rpcbinder::run_rpc_server_with_factory;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000049use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010050use idsig::{HashAlgorithm, V4Signature};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000051use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000052use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090053use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090054use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000055use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000056use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010057use std::fs::{create_dir, File, OpenOptions};
Shikha Panwar7afc1392022-03-24 08:54:43 +000058use std::io::{Error, ErrorKind, Write, Read};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000059use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000060use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000061use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000062use std::sync::{Arc, Mutex, Weak};
Shikha Panwar7afc1392022-03-24 08:54:43 +000063use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrancc0db522021-07-12 17:03:42 +000064use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090065use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090066use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000067
Andrew Walbranf6bf6862021-05-21 12:41:13 +000068pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000069
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000070/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000071pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072
Jiyong Park8611a6c2021-07-09 18:17:44 +090073/// The CID representing the host VM
74const VMADDR_CID_HOST: u32 = 2;
75
Jooyung Han95884632021-07-06 22:27:54 +090076/// The size of zero.img.
77/// Gaps in composite disk images are filled with a shared zero.img.
78const ZERO_FILLER_SIZE: u64 = 4096;
79
Jiyong Park9dd389e2021-08-23 20:42:59 +090080/// Magic string for the instance image
81const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
82
83/// Version of the instance image format
84const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
85
Shikha Panwar7afc1392022-03-24 08:54:43 +000086const CHUNK_RECV_MAX_LEN: usize = 1024;
87
Andrew Walbranf6bf6862021-05-21 12:41:13 +000088/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090089#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000090pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090091 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000092}
93
Shikha Panward8e35422021-10-11 13:51:27 +000094impl Interface for VirtualizationService {
95 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
96 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
97 let state = &mut *self.state.lock().unwrap();
98 let vms = state.vms();
99 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
100 for vm in vms {
101 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
102 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
103 .or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\tPayload state {:?}", vm.payload_state())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
108 .or(Err(StatusCode::UNKNOWN_ERROR))?;
109 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
110 .or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 }
116 Ok(())
117 }
118}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000119
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000120impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
122 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123 ///
124 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000125 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000126 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000127 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900128 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000129 log_fd: Option<&ParcelFileDescriptor>,
130 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000131 let mut is_protected = false;
132 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000133 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000134 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000135 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000136
Andrew Walbrandff3b942021-06-09 15:20:36 +0000137 /// Initialise an empty partition image of the given size to be used as a writable partition.
138 fn initializeWritablePartition(
139 &self,
140 image_fd: &ParcelFileDescriptor,
141 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900142 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000143 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900144 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000145 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000146 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000147 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100148 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000149 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000150 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000151 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900152 // initialize the file. Any data in the file will be erased.
153 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000154 Status::new_service_specific_error_str(
155 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100156 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900157 )
158 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900159 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000160 Status::new_service_specific_error_str(
161 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100162 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000163 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000164 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000165
Jiyong Park9dd389e2021-08-23 20:42:59 +0900166 match partition_type {
167 PartitionType::RAW => Ok(()),
168 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
169 _ => Err(Error::new(
170 ErrorKind::Unsupported,
171 format!("Unsupported partition type {:?}", partition_type),
172 )),
173 }
174 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000175 Status::new_service_specific_error_str(
176 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100177 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900178 )
179 })?;
180
Andrew Walbrandff3b942021-06-09 15:20:36 +0000181 Ok(())
182 }
183
Jiyong Park0a248432021-08-20 23:32:39 +0900184 /// Creates or update the idsig file by digesting the input APK file.
185 fn createOrUpdateIdsigFile(
186 &self,
187 input_fd: &ParcelFileDescriptor,
188 idsig_fd: &ParcelFileDescriptor,
189 ) -> binder::Result<()> {
190 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
191 // idsig_fd is different from APK digest in input_fd
192
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900193 check_manage_access()?;
194
Jiyong Park0a248432021-08-20 23:32:39 +0900195 let mut input = clone_file(input_fd)?;
196 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
197
198 let mut output = clone_file(idsig_fd)?;
199 output.set_len(0).unwrap();
200 sig.write_into(&mut output).unwrap();
201 Ok(())
202 }
203
Andrew Walbran320b5602021-03-04 16:11:12 +0000204 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
205 /// and as such is only permitted from the shell user.
206 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000207 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000208
209 let state = &mut *self.state.lock().unwrap();
210 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000211 let cids = vms
212 .into_iter()
213 .map(|vm| VirtualMachineDebugInfo {
214 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000215 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000216 requesterUid: vm.requester_uid as i32,
217 requesterSid: vm.requester_sid.clone(),
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<()> {
268 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
269 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();
346 let requester_sid = get_calling_sid()?;
347 let requester_debug_pid = ThreadState::get_calling_pid();
348 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
349
350 // Counter to generate unique IDs for temporary image files.
351 let mut next_temporary_image_id = 0;
352 // Files which are referred to from composite images. These must be mapped to the crosvm
353 // child process, and not closed before it is started.
354 let mut indirect_files = vec![];
355
356 // Make directory for temporary files.
357 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
358 create_dir(&temporary_directory).map_err(|e| {
359 // At this point, we do not know the protected status of Vm
360 // setting it to false, though this may not be correct.
361 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100362 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000363 temporary_directory, e
364 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000365 Status::new_service_specific_error_str(
366 -1,
367 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100368 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000369 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000370 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000371 )
372 })?;
373
374 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
375
376 let config = match config {
377 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
378 load_app_config(config, &temporary_directory).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100379 error!("Failed to load app config from {}: {:?}", &config.configPath, e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000380 *is_protected = config.protectedVm;
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000381 Status::new_service_specific_error_str(
382 -1,
383 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100384 "Failed to load app config from {}: {:?}",
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000385 &config.configPath, e
386 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000387 )
388 })?,
389 ),
390 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
391 };
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),
462 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900463 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000464 console_fd,
465 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900466 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000467 indirect_files,
468 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900469 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470 };
471 let instance = Arc::new(
472 VmInstance::new(
473 crosvm_config,
474 temporary_directory,
475 requester_uid,
476 requester_sid,
477 requester_debug_pid,
478 )
479 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100480 error!("Failed to create VM with config {:?}: {:?}", config, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000481 Status::new_service_specific_error_str(
482 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100483 Some(format!("Failed to create VM: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000484 )
485 })?,
486 );
487 state.add_vm(Arc::downgrade(&instance));
488 Ok(VirtualMachine::create(instance))
489 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900490}
491
Andrew Walbran6b650662021-09-07 13:13:23 +0000492/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
493/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900494fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900495 let listener =
496 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900497 for stream in listener.incoming() {
498 let stream = match stream {
499 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100500 warn!("invalid incoming connection: {:?}", e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900501 continue;
502 }
503 Ok(s) => s,
504 };
505 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
506 let cid = addr.cid();
507 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900508 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900509 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700510 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900511 } else {
512 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900513 }
514 }
515 }
516 Ok(())
517}
518
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000519fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900520 let file = OpenOptions::new()
521 .create_new(true)
522 .read(true)
523 .write(true)
524 .open(zero_filler_path)
525 .with_context(|| "Failed to create zero.img")?;
526 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000527 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900528}
529
Jiyong Park9dd389e2021-08-23 20:42:59 +0900530fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
531 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
532 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
533 part.flush()
534}
535
Jiyong Parke558ab12022-07-07 20:18:55 +0900536fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
537 File::create(&ramdump_path)
538 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
539}
540
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
542///
543/// This may involve assembling a composite disk from a set of partition images.
544fn assemble_disk_image(
545 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900546 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000547 temporary_directory: &Path,
548 next_temporary_image_id: &mut u64,
549 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000550) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000551 let image = if !disk.partitions.is_empty() {
552 if disk.image.is_some() {
553 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000554 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000555 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000556 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000557 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558 }
559
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000560 let composite_image_filenames =
561 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
562 let (image, partition_files) = make_composite_image(
563 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900564 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000565 &composite_image_filenames.composite,
566 &composite_image_filenames.header,
567 &composite_image_filenames.footer,
568 )
569 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100570 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000571 Status::new_service_specific_error_str(
572 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100573 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000574 )
575 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000576
577 // Pass the file descriptors for the various partition files to crosvm when it
578 // is run.
579 indirect_files.extend(partition_files);
580
581 image
582 } else if let Some(image) = &disk.image {
583 clone_file(image)?
584 } else {
585 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000586 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000587 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000588 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000589 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590 };
591
592 Ok(DiskFile { image, writable: disk.writable })
593}
594
Jooyung Han21e9b922021-06-26 04:14:16 +0900595fn load_app_config(
596 config: &VirtualMachineAppConfig,
597 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900598) -> Result<VirtualMachineRawConfig> {
Alan Stokes82f389c2022-09-08 12:23:52 +0100599 // Controlling CPUs is reserved for platform apps only, even when using
600 // VirtualMachineAppConfig.
601 if config.cpuAffinity.is_some() || !config.taskProfiles.is_empty() {
602 check_use_custom_virtual_machine()?
603 }
604
Andrew Walbrancc0db522021-07-12 17:03:42 +0000605 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
606 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900607 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900608 let config_path = &config.configPath;
609
Andrew Walbrancc0db522021-07-12 17:03:42 +0000610 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900611 let config_file = apk_zip.by_name(config_path)?;
612 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
613
614 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000615
Jooyung Han35edb8f2021-07-01 16:17:16 +0900616 // For now, the only supported "os" value is "microdroid"
617 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000618 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900619 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000620
621 // It is safe to construct a filename based on the os_name because we've already checked that it
622 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900623 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
624 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000625 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900626
Andrew Walbrancc045902021-07-27 16:06:17 +0000627 if config.memoryMib > 0 {
628 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000629 }
630
Seungjae Yoo62085c02022-08-12 04:44:52 +0000631 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000632 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900633 vm_config.numCpus = config.numCpus;
634 vm_config.cpuAffinity = config.cpuAffinity.clone();
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900635 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900636
Andrew Walbrancc0db522021-07-12 17:03:42 +0000637 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900638 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000639 add_microdroid_images(
640 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900641 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000642 apk_file,
643 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900644 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900645 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000646 &mut vm_config,
647 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900648 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900649
Andrew Walbrancc0db522021-07-12 17:03:42 +0000650 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900651}
652
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000653/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000654fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000655 temporary_directory: &Path,
656 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000657) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000658 let id = *next_temporary_image_id;
659 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000660 CompositeImageFilenames {
661 composite: temporary_directory.join(format!("composite-{}.img", id)),
662 header: temporary_directory.join(format!("composite-{}-header.img", id)),
663 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
664 }
665}
666
667/// Filenames for a composite disk image, including header and footer partitions.
668#[derive(Clone, Debug, Eq, PartialEq)]
669struct CompositeImageFilenames {
670 /// The composite disk image itself.
671 composite: PathBuf,
672 /// The header partition image.
673 header: PathBuf,
674 /// The footer partition image.
675 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000676}
677
678/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000679fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000680 ThreadState::with_calling_sid(|sid| {
681 if let Some(sid) = sid {
682 match sid.to_str() {
683 Ok(sid) => Ok(sid.to_owned()),
684 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000685 error!("SID was not valid UTF-8: {}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000686 Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000687 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000688 Some(format!("SID was not valid UTF-8: {}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000689 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000690 }
691 }
692 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000693 error!("Missing SID on createVm");
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000694 Err(Status::new_exception_str(ExceptionCode::SECURITY, Some("Missing SID on createVm")))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000695 }
696 })
697}
698
Jiyong Park753553b2021-07-12 21:21:09 +0900699/// Checks whether the caller has a specific permission
700fn check_permission(perm: &str) -> binder::Result<()> {
701 let calling_pid = ThreadState::get_calling_pid();
702 let calling_uid = ThreadState::get_calling_uid();
703 // Root can do anything
704 if calling_uid == 0 {
705 return Ok(());
706 }
707 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
708 binder::get_interface("permission")?;
709 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000710 Ok(())
711 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000712 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900713 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000714 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900715 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000716 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000717}
718
Jiyong Park753553b2021-07-12 21:21:09 +0900719/// Check whether the caller of the current Binder method is allowed to call debug methods.
720fn check_debug_access() -> binder::Result<()> {
721 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
722}
723
724/// Check whether the caller of the current Binder method is allowed to manage VMs
725fn check_manage_access() -> binder::Result<()> {
726 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
727}
728
Inseob Kim1119d702022-05-02 18:01:58 +0900729/// Check whether the caller of the current Binder method is allowed to create custom VMs
730fn check_use_custom_virtual_machine() -> binder::Result<()> {
731 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
732}
733
Jiyong Park029977d2021-11-24 21:56:49 +0900734/// Check if a partition has selinux labels that are not allowed
735fn check_label_for_partition(partition: &Partition) -> Result<()> {
736 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100737 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
738}
739
740// Return whether a partition is exempt from selinux label checks, because we know that it does
741// not contain code and is likely to be generated in an app-writable directory.
742fn is_safe_app_partition(label: &str) -> bool {
743 // See make_payload_disk in payload.rs.
744 label == "vm-instance"
745 || label == "microdroid-apk-idsig"
746 || label == "payload-metadata"
747 || label.starts_with("extra-idsig-")
748}
749
750fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
751 // We only want to allow code in a VM payload to be sourced from places that apps, and the
752 // system, do not have write access to.
753 // (Note that sepolicy must also grant read access for these types to both virtualization
754 // service and crosvm.)
755 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
756 // user devices (W^X).
757 match ctx.selinux_type()? {
758 | "system_file" // immutable dm-verity protected partition
759 | "apk_data_file" // APKs of an installed app
760 | "staging_data_file" // updated/staged APEX imagess
761 | "shell_data_file" // test files created via adb shell
762 => Ok(()),
763 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900764 }
765}
766
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000767/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
768#[derive(Debug)]
769struct VirtualMachine {
770 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100771 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800772 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100773 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000774}
775
776impl VirtualMachine {
777 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100778 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000779 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000780 }
781}
782
783impl Interface for VirtualMachine {}
784
785impl IVirtualMachine for VirtualMachine {
786 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900787 // Don't check permission. The owner of the VM might have passed this binder object to
788 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000789 Ok(self.instance.cid as i32)
790 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000791
Andrew Walbran6b650662021-09-07 13:13:23 +0000792 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900793 // Don't check permission. The owner of the VM might have passed this binder object to
794 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000795 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000796 }
797
798 fn registerCallback(
799 &self,
800 callback: &Strong<dyn IVirtualMachineCallback>,
801 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900802 // Don't check permission. The owner of the VM might have passed this binder object to
803 // others.
804 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000805 // TODO: Should this give an error if the VM is already dead?
806 self.instance.callbacks.add(callback.clone());
807 Ok(())
808 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000809
Andrew Walbranf8d94112021-09-07 11:45:36 +0000810 fn start(&self) -> binder::Result<()> {
811 self.instance.start().map_err(|e| {
812 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000813 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000814 })
815 }
816
Inseob Kima446f802022-07-11 19:46:37 +0900817 fn stop(&self) -> binder::Result<()> {
818 self.instance.kill().map_err(|e| {
819 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000820 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900821 })
822 }
823
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000824 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000825 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000826 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000827 }
828 let stream =
829 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000830 Status::new_service_specific_error_str(
831 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100832 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000833 )
834 })?;
835 Ok(vsock_stream_to_pfd(stream))
836 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000837}
838
839impl Drop for VirtualMachine {
840 fn drop(&mut self) {
841 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900842 if let Err(e) = self.instance.kill() {
843 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
844 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000845 }
846}
847
848/// A set of Binders to be called back in response to various events on the VM, such as when it
849/// dies.
850#[derive(Debug, Default)]
851pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
852
853impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900854 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900855 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900856 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900857 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900858 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900859 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100860 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900861 }
862 }
863 }
864
Inseob Kim14cb8692021-08-31 21:50:39 +0900865 /// Call all registered callbacks to notify that the payload is ready to serve.
866 pub fn notify_payload_ready(&self, cid: Cid) {
867 let callbacks = &*self.0.lock().unwrap();
868 for callback in callbacks {
869 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100870 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900871 }
872 }
873 }
874
Inseob Kim2444af92021-08-31 01:22:50 +0900875 /// Call all registered callbacks to notify that the payload has finished.
876 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
877 let callbacks = &*self.0.lock().unwrap();
878 for callback in callbacks {
879 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100880 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900881 }
882 }
883 }
884
Jooyung Handd0a1732021-11-23 15:26:20 +0900885 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100886 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900887 let callbacks = &*self.0.lock().unwrap();
888 for callback in callbacks {
889 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100890 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900891 }
892 }
893 }
894
Andrew Walbrandae07162021-03-12 17:05:20 +0000895 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000896 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000897 let callbacks = &*self.0.lock().unwrap();
898 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000899 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100900 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000901 }
902 }
903 }
904
Jiyong Parke558ab12022-07-07 20:18:55 +0900905 /// Call all registered callbacks to say that there was a ramdump to download.
906 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
907 let callbacks = &*self.0.lock().unwrap();
908 let pfd = ParcelFileDescriptor::new(ramdump);
909 for callback in callbacks {
910 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100911 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +0900912 }
913 }
914 }
915
Andrew Walbrandae07162021-03-12 17:05:20 +0000916 /// Add a new callback to the set.
917 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
918 self.0.lock().unwrap().push(callback);
919 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000920}
921
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000922/// The mutable state of the VirtualizationService. There should only be one instance of this
923/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800924#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000925struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000926 /// The VMs which have been started. When VMs are started a weak reference is added to this list
927 /// while a strong reference is returned to the caller over Binder. Once all copies of the
928 /// Binder client are dropped the weak reference here will become invalid, and will be removed
929 /// from the list opportunistically the next time `add_vm` is called.
930 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000931
932 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
933 /// This is only used for debugging purposes.
934 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000935}
936
937impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000938 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000939 fn vms(&self) -> Vec<Arc<VmInstance>> {
940 // Attempt to upgrade the weak pointers to strong pointers.
941 self.vms.iter().filter_map(Weak::upgrade).collect()
942 }
943
944 /// Add a new VM to the list.
945 fn add_vm(&mut self, vm: Weak<VmInstance>) {
946 // Garbage collect any entries from the stored list which no longer exist.
947 self.vms.retain(|vm| vm.strong_count() > 0);
948
949 // Actually add the new VM.
950 self.vms.push(vm);
951 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000952
Jiyong Park8611a6c2021-07-09 18:17:44 +0900953 /// Get a VM that corresponds to the given cid
954 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
955 self.vms().into_iter().find(|vm| vm.cid == cid)
956 }
957
David Brazdil3c2ddef2021-03-18 13:09:57 +0000958 /// Store a strong VM reference.
959 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
960 self.debug_held_vms.push(vm);
961 }
962
963 /// Retrieve and remove a strong VM reference.
964 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
965 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100966 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100967 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000968 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000969}
970
Jiyong Parkd50a0242021-09-16 21:00:14 +0900971/// Get the next available CID, or an error if we have run out. The last CID used is stored in
972/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
973/// Android is up.
974fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000975 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900976 if let Ok(num) = val.parse::<u32>() {
977 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
978 } else {
979 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
980 FIRST_GUEST_CID
981 }
982 } else {
983 // First VM since the boot
984 FIRST_GUEST_CID
985 };
986 // Persist the last value for next use
987 let str_val = format!("{}", next);
988 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
989 Ok(next)
990}
991
Andrew Walbran6b650662021-09-07 13:13:23 +0000992/// Gets the `VirtualMachineState` of the given `VmInstance`.
993fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000994 match &*instance.vm_state.lock().unwrap() {
995 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
996 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000997 PayloadState::Starting => VirtualMachineState::STARTING,
998 PayloadState::Started => VirtualMachineState::STARTED,
999 PayloadState::Ready => VirtualMachineState::READY,
1000 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001001 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001002 },
1003 VmState::Dead => VirtualMachineState::DEAD,
1004 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001005 }
1006}
1007
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001008/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001009pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001010 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001011 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001012 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001013 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001014 )
1015 })
1016}
1017
Andrew Walbrand3a84182021-09-07 14:48:52 +00001018/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1019fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1020 file.as_ref().map(clone_file).transpose()
1021}
1022
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001023/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1024fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1025 // SAFETY: ownership is transferred from stream to f
1026 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1027 ParcelFileDescriptor::new(f)
1028}
1029
Jiyong Parkdcf17412022-02-08 15:07:23 +09001030/// Parses the platform version requirement string.
1031fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1032 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001033 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001034 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001035 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001036 )
1037 })
1038}
1039
Jooyung Han35edb8f2021-07-01 16:17:16 +09001040/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1041/// it doesn't require that T implements Clone.
1042enum BorrowedOrOwned<'a, T> {
1043 Borrowed(&'a T),
1044 Owned(T),
1045}
1046
1047impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1048 fn as_ref(&self) -> &T {
1049 match self {
1050 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001051 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001052 }
1053 }
1054}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001055
1056/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1057#[derive(Debug, Default)]
1058struct VirtualMachineService {
1059 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001060 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001061}
1062
1063impl Interface for VirtualMachineService {}
1064
1065impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001066 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1067 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001068 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1069 info!("VM having CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001070 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1071 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1072 })?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001073 let stream = vm.stream.lock().unwrap().take();
1074 vm.callbacks.notify_payload_started(cid, stream);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001075
Seungjae Yoo2e7beea2022-08-24 16:09:12 +09001076 let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap();
1077 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001078 Ok(())
1079 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001080 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001081 Err(Status::new_service_specific_error_str(
1082 -1,
1083 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001084 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001085 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001086 }
Inseob Kim2444af92021-08-31 01:22:50 +09001087
Inseob Kimc7d28c72021-10-25 14:28:10 +00001088 fn notifyPayloadReady(&self) -> binder::Result<()> {
1089 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001090 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1091 info!("VM having CID {} payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001092 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1093 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1094 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001095 vm.callbacks.notify_payload_ready(cid);
1096 Ok(())
1097 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001098 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001099 Err(Status::new_service_specific_error_str(
1100 -1,
1101 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001102 ))
1103 }
1104 }
1105
Inseob Kimc7d28c72021-10-25 14:28:10 +00001106 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1107 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001108 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1109 info!("VM having CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001110 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1111 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1112 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001113 vm.callbacks.notify_payload_finished(cid, exit_code);
1114 Ok(())
1115 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001116 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001117 Err(Status::new_service_specific_error_str(
1118 -1,
1119 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001120 ))
1121 }
1122 }
1123
Alan Stokes2bead0d2022-09-05 16:58:34 +01001124 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001125 let cid = self.cid;
1126 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1127 info!("VM having CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001128 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1129 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1130 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001131 vm.callbacks.notify_error(cid, error_code, message);
1132 Ok(())
1133 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001134 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001135 Err(Status::new_service_specific_error_str(
1136 -1,
1137 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001138 ))
1139 }
1140 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001141}
1142
1143impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001144 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001145 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1146 let mut vm_service = vm.vm_service.lock().unwrap();
1147 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001148 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001149 } else {
1150 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001151 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001152 }
1153 }
1154
1155 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001156 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001157 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001158 BinderFeatures::default(),
1159 )
1160 }
1161}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001162
1163#[cfg(test)]
1164mod tests {
1165 use super::*;
1166
1167 #[test]
1168 fn test_is_allowed_label_for_partition() -> Result<()> {
1169 let expected_results = vec![
1170 ("u:object_r:system_file:s0", true),
1171 ("u:object_r:apk_data_file:s0", true),
1172 ("u:object_r:app_data_file:s0", false),
1173 ("u:object_r:app_data_file:s0:c512,c768", false),
1174 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1175 ("invalid", false),
1176 ("user:role:apk_data_file:severity:categories", true),
1177 ("user:role:apk_data_file:severity:categories:extraneous", false),
1178 ];
1179
1180 for (label, expected_valid) in expected_results {
1181 let context = SeContext::new(label)?;
1182 let result = check_label_is_allowed(&context);
1183 if expected_valid {
1184 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1185 } else if result.is_ok() {
1186 bail!("Expected label {} to be disallowed", label);
1187 }
1188 }
1189 Ok(())
1190 }
1191}