blob: 33102eb73f579358cf5eef4d6cf6b3062f7ae771 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoofd9a0622022-10-14 10:01:29 +090017use crate::atom::{
18 write_vm_booted_stats, write_vm_cpu_status_stats, write_vm_creation_stats,
19 write_vm_mem_status_stats,
20};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000021use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000022use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Parkd50a0242021-09-16 21:00:14 +090025use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID};
Jiyong Park753553b2021-07-12 21:21:09 +090026use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Seungjae Yoofd9a0622022-10-14 10:01:29 +090027use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
Jooyung Han21e9b922021-06-26 04:14:16 +090028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000029 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000030 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010031 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000032 IVirtualMachineCallback::IVirtualMachineCallback,
33 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090034 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090036 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090037 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000038 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010039 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090040 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090042};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
44 IVirtualMachineService::{
45 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
46 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
47 },
48 VirtualMachineCpuStatus::VirtualMachineCpuStatus,
49 VirtualMachineMemStatus::VirtualMachineMemStatus,
50};
51use anyhow::{anyhow, bail, Context, Result};
52use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010053use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000054 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
55 SpIBinder, Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000056};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000057use disk::QcowFile;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000058use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090059use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
60use rpcbinder::run_rpc_server_with_factory;
Jiyong Parkd50a0242021-09-16 21:00:14 +090061use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090062use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000063use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000064use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010065use std::fs::{create_dir, File, OpenOptions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090066use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000067use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000068use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000070use std::sync::{Arc, Mutex, Weak};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090071use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000072use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000073use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090074use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000075
Andrew Walbranf6bf6862021-05-21 12:41:13 +000076pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000079pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000080
Jiyong Park8611a6c2021-07-09 18:17:44 +090081/// The CID representing the host VM
82const VMADDR_CID_HOST: u32 = 2;
83
Jooyung Han95884632021-07-06 22:27:54 +090084/// The size of zero.img.
85/// Gaps in composite disk images are filled with a shared zero.img.
86const ZERO_FILLER_SIZE: u64 = 4096;
87
Jiyong Park9dd389e2021-08-23 20:42:59 +090088/// Magic string for the instance image
89const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
90
91/// Version of the instance image format
92const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
93
Shikha Panwar7afc1392022-03-24 08:54:43 +000094const CHUNK_RECV_MAX_LEN: usize = 1024;
95
Alan Stokes0d1ef782022-09-27 13:46:35 +010096const MICRODROID_OS_NAME: &str = "microdroid";
97
Andrew Walbranf6bf6862021-05-21 12:41:13 +000098/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090099#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000100pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900101 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000102}
103
Shikha Panward8e35422021-10-11 13:51:27 +0000104impl Interface for VirtualizationService {
105 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
106 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
107 let state = &mut *self.state.lock().unwrap();
108 let vms = state.vms();
109 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
110 for vm in vms {
111 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
112 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
113 .or(Err(StatusCode::UNKNOWN_ERROR))?;
114 writeln!(file, "\tPayload state {:?}", vm.payload_state())
115 .or(Err(StatusCode::UNKNOWN_ERROR))?;
116 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
117 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
118 .or(Err(StatusCode::UNKNOWN_ERROR))?;
119 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
120 .or(Err(StatusCode::UNKNOWN_ERROR))?;
121 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
122 .or(Err(StatusCode::UNKNOWN_ERROR))?;
123 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
124 .or(Err(StatusCode::UNKNOWN_ERROR))?;
125 }
126 Ok(())
127 }
128}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000129
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000130impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000131 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
132 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000133 ///
134 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000135 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000136 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000137 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900138 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000139 log_fd: Option<&ParcelFileDescriptor>,
140 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000141 let mut is_protected = false;
142 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000143 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000144 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000145 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000146
Andrew Walbrandff3b942021-06-09 15:20:36 +0000147 /// Initialise an empty partition image of the given size to be used as a writable partition.
148 fn initializeWritablePartition(
149 &self,
150 image_fd: &ParcelFileDescriptor,
151 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900152 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000153 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900154 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000155 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000156 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000157 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100158 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000159 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000160 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000161 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900162 // initialize the file. Any data in the file will be erased.
163 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000164 Status::new_service_specific_error_str(
165 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100166 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900167 )
168 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900169 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000170 Status::new_service_specific_error_str(
171 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100172 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000173 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000174 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000175
Jiyong Park9dd389e2021-08-23 20:42:59 +0900176 match partition_type {
177 PartitionType::RAW => Ok(()),
178 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
179 _ => Err(Error::new(
180 ErrorKind::Unsupported,
181 format!("Unsupported partition type {:?}", partition_type),
182 )),
183 }
184 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000185 Status::new_service_specific_error_str(
186 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100187 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900188 )
189 })?;
190
Andrew Walbrandff3b942021-06-09 15:20:36 +0000191 Ok(())
192 }
193
Jiyong Park0a248432021-08-20 23:32:39 +0900194 /// Creates or update the idsig file by digesting the input APK file.
195 fn createOrUpdateIdsigFile(
196 &self,
197 input_fd: &ParcelFileDescriptor,
198 idsig_fd: &ParcelFileDescriptor,
199 ) -> binder::Result<()> {
200 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
201 // idsig_fd is different from APK digest in input_fd
202
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900203 check_manage_access()?;
204
Jiyong Park0a248432021-08-20 23:32:39 +0900205 let mut input = clone_file(input_fd)?;
206 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
207
208 let mut output = clone_file(idsig_fd)?;
209 output.set_len(0).unwrap();
210 sig.write_into(&mut output).unwrap();
211 Ok(())
212 }
213
Andrew Walbran320b5602021-03-04 16:11:12 +0000214 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
215 /// and as such is only permitted from the shell user.
216 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000217 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000218
219 let state = &mut *self.state.lock().unwrap();
220 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000221 let cids = vms
222 .into_iter()
223 .map(|vm| VirtualMachineDebugInfo {
224 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000225 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000226 requesterUid: vm.requester_uid as i32,
227 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000228 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000229 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000230 })
231 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000232 Ok(cids)
233 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000234
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000235 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
236 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000237 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000238 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000239
David Brazdil3c2ddef2021-03-18 13:09:57 +0000240 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000241 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242 Ok(())
243 }
244
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000245 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
246 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
247 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000248 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000249 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000250
251 let state = &mut *self.state.lock().unwrap();
252 Ok(state.debug_drop_vm(cid))
253 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000254}
255
Shikha Panwar7afc1392022-03-24 08:54:43 +0000256fn handle_stream_connection_tombstoned() -> Result<()> {
257 let listener =
258 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
259 info!("Listening to tombstones from guests ...");
260 for incoming_stream in listener.incoming() {
261 let mut incoming_stream = match incoming_stream {
262 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100263 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000264 continue;
265 }
266 Ok(s) => s,
267 };
268 std::thread::spawn(move || {
269 if let Err(e) = handle_tombstone(&mut incoming_stream) {
270 error!("Failed to write tombstone- {:?}", e);
271 }
272 });
273 }
274 Ok(())
275}
276
277fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000278 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000279 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
280 }
281 let tb_connection =
282 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
283 .context("Failed to connect to tombstoned")?;
284 let mut text_output = tb_connection
285 .text_output
286 .as_ref()
287 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
288 let mut num_bytes_read = 0;
289 loop {
290 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
291 let n = stream
292 .read(&mut chunk_recv)
293 .context("Failed to read tombstone data from Vsock stream")?;
294 if n == 0 {
295 break;
296 }
297 num_bytes_read += n;
298 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
299 }
300 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
301 tb_connection.notify_completion()?;
302 Ok(())
303}
304
Jiyong Park8611a6c2021-07-09 18:17:44 +0900305impl VirtualizationService {
306 pub fn init() -> VirtualizationService {
307 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900308
309 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900310 let state = service.state.clone(); // reference to state (not the state itself) is copied
311 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900312 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900313 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900314
Shikha Panwar7afc1392022-03-24 08:54:43 +0000315 std::thread::spawn(|| {
316 if let Err(e) = handle_stream_connection_tombstoned() {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100317 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000318 }
319 });
320
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900321 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000322 // reference to state (not the state itself) is copied
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000323 let state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900324 std::thread::spawn(move || {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000325 debug!("VirtualMachineService is starting as an RPC service.");
326 if run_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| {
327 VirtualMachineService::factory(cid, &state)
328 }) {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900329 debug!("RPC server has shut down gracefully");
330 } else {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000331 panic!("Premature termination of RPC server");
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900332 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900333 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900334 service
335 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000336
337 fn create_vm_internal(
338 &self,
339 config: &VirtualMachineConfig,
340 console_fd: Option<&ParcelFileDescriptor>,
341 log_fd: Option<&ParcelFileDescriptor>,
342 is_protected: &mut bool,
343 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
344 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900345
346 if let VirtualMachineConfig::RawConfig(config) = config {
347 if config.protectedVm {
348 check_use_custom_virtual_machine()?;
349 }
350 }
351
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000352 let state = &mut *self.state.lock().unwrap();
353 let console_fd = console_fd.map(clone_file).transpose()?;
354 let log_fd = log_fd.map(clone_file).transpose()?;
355 let requester_uid = ThreadState::get_calling_uid();
356 let requester_sid = get_calling_sid()?;
357 let requester_debug_pid = ThreadState::get_calling_pid();
358 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
359
360 // Counter to generate unique IDs for temporary image files.
361 let mut next_temporary_image_id = 0;
362 // Files which are referred to from composite images. These must be mapped to the crosvm
363 // child process, and not closed before it is started.
364 let mut indirect_files = vec![];
365
366 // Make directory for temporary files.
367 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
368 create_dir(&temporary_directory).map_err(|e| {
369 // At this point, we do not know the protected status of Vm
370 // setting it to false, though this may not be correct.
371 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100372 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000373 temporary_directory, e
374 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000375 Status::new_service_specific_error_str(
376 -1,
377 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100378 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000379 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000380 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000381 )
382 })?;
383
384 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
385
386 let config = match config {
387 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
388 load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000389 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100390 let message = format!("Failed to load app config: {:?}", e);
391 error!("{}", message);
392 Status::new_service_specific_error_str(-1, Some(message))
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000393 })?,
394 ),
395 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
396 };
397 let config = config.as_ref();
398 *is_protected = config.protectedVm;
399
400 // Check if partition images are labeled incorrectly. This is to prevent random images
401 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100402 // being loaded in a pVM. This applies to everything in the raw config, and everything but
403 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000404 config
405 .disks
406 .iter()
407 .flat_map(|disk| disk.partitions.iter())
408 .filter(|partition| {
409 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100410 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000411 } else {
412 true // all partitions are checked
413 }
414 })
415 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100416 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000417
418 let zero_filler_path = temporary_directory.join("zero.img");
419 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100420 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000421 Status::new_service_specific_error_str(
422 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100423 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000424 )
425 })?;
426
427 // Assemble disk images if needed.
428 let disks = config
429 .disks
430 .iter()
431 .map(|disk| {
432 assemble_disk_image(
433 disk,
434 &zero_filler_path,
435 &temporary_directory,
436 &mut next_temporary_image_id,
437 &mut indirect_files,
438 )
439 })
440 .collect::<Result<Vec<DiskFile>, _>>()?;
441
Jiyong Parke558ab12022-07-07 20:18:55 +0900442 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
443 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900444 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900445 // will be sent back to the client (i.e. the VM owner) for readout.
446 let ramdump_path = temporary_directory.join("ramdump");
447 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100448 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000449 Status::new_service_specific_error_str(
450 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100451 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900452 )
453 })?;
454
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000455 // Actually start the VM.
456 let crosvm_config = CrosvmConfig {
457 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000458 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000459 bootloader: maybe_clone_file(&config.bootloader)?,
460 kernel: maybe_clone_file(&config.kernel)?,
461 initrd: maybe_clone_file(&config.initrd)?,
462 disks,
463 params: config.params.to_owned(),
464 protected: *is_protected,
465 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
466 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900467 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000468 console_fd,
469 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900470 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000471 indirect_files,
472 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900473 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000474 };
475 let instance = Arc::new(
476 VmInstance::new(
477 crosvm_config,
478 temporary_directory,
479 requester_uid,
480 requester_sid,
481 requester_debug_pid,
482 )
483 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100484 error!("Failed to create VM with config {:?}: {:?}", config, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000485 Status::new_service_specific_error_str(
486 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100487 Some(format!("Failed to create VM: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000488 )
489 })?,
490 );
491 state.add_vm(Arc::downgrade(&instance));
492 Ok(VirtualMachine::create(instance))
493 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900494}
495
Andrew Walbran6b650662021-09-07 13:13:23 +0000496/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
497/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900498fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900499 let listener =
500 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900501 for stream in listener.incoming() {
502 let stream = match stream {
503 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100504 warn!("invalid incoming connection: {:?}", e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900505 continue;
506 }
507 Ok(s) => s,
508 };
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000509 if let Ok(addr) = stream.peer_addr() {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900510 let cid = addr.cid();
511 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900512 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900513 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700514 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900515 } else {
516 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900517 }
518 }
519 }
520 Ok(())
521}
522
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000523fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900524 let file = OpenOptions::new()
525 .create_new(true)
526 .read(true)
527 .write(true)
528 .open(zero_filler_path)
529 .with_context(|| "Failed to create zero.img")?;
530 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000531 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900532}
533
Jiyong Park9dd389e2021-08-23 20:42:59 +0900534fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
535 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
536 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
537 part.flush()
538}
539
Jiyong Parke558ab12022-07-07 20:18:55 +0900540fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
541 File::create(&ramdump_path)
542 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
543}
544
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000545/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
546///
547/// This may involve assembling a composite disk from a set of partition images.
548fn assemble_disk_image(
549 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900550 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000551 temporary_directory: &Path,
552 next_temporary_image_id: &mut u64,
553 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000554) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000555 let image = if !disk.partitions.is_empty() {
556 if disk.image.is_some() {
557 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000558 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000559 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000560 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000561 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000562 }
563
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000564 let composite_image_filenames =
565 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
566 let (image, partition_files) = make_composite_image(
567 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900568 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000569 &composite_image_filenames.composite,
570 &composite_image_filenames.header,
571 &composite_image_filenames.footer,
572 )
573 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100574 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000575 Status::new_service_specific_error_str(
576 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100577 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000578 )
579 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000580
581 // Pass the file descriptors for the various partition files to crosvm when it
582 // is run.
583 indirect_files.extend(partition_files);
584
585 image
586 } else if let Some(image) = &disk.image {
587 clone_file(image)?
588 } else {
589 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000590 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000591 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000592 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000593 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000594 };
595
596 Ok(DiskFile { image, writable: disk.writable })
597}
598
Jooyung Han21e9b922021-06-26 04:14:16 +0900599fn load_app_config(
600 config: &VirtualMachineAppConfig,
601 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900602) -> Result<VirtualMachineRawConfig> {
Alan Stokes82f389c2022-09-08 12:23:52 +0100603 // Controlling CPUs is reserved for platform apps only, even when using
604 // VirtualMachineAppConfig.
Victor Hsiehf219cd82022-09-09 13:13:11 -0700605 if !config.taskProfiles.is_empty() {
Alan Stokes82f389c2022-09-08 12:23:52 +0100606 check_use_custom_virtual_machine()?
607 }
608
Andrew Walbrancc0db522021-07-12 17:03:42 +0000609 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
610 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900611 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900612
Shikha Panwar22e70452022-10-10 18:32:55 +0000613 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
614 Some(clone_file(file)?)
615 } else {
616 None
617 };
618
Alan Stokes0d1ef782022-09-27 13:46:35 +0100619 let vm_payload_config = match &config.payload {
620 Payload::ConfigPath(config_path) => {
621 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
622 .with_context(|| format!("Couldn't read config from {}", config_path))?
623 }
624 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
625 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900626
Alan Stokes0d1ef782022-09-27 13:46:35 +0100627 // For now, the only supported OS is Microdroid
628 let os_name = vm_payload_config.os.name.as_str();
629 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000630 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900631 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000632
633 // It is safe to construct a filename based on the os_name because we've already checked that it
634 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900635 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
636 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000637 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900638
Andrew Walbrancc045902021-07-27 16:06:17 +0000639 if config.memoryMib > 0 {
640 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000641 }
642
Seungjae Yoo62085c02022-08-12 04:44:52 +0000643 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000644 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900645 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900646 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900647
Shikha Panwar22e70452022-10-10 18:32:55 +0000648 // Microdroid takes additional init ramdisk & (optionally) storage image
649 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
650
651 // Include Microdroid payload disk (contains apks, idsigs) in vm config
652 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100653 config,
654 temporary_directory,
655 apk_file,
656 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100657 &vm_payload_config,
658 &mut vm_config,
659 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900660
Andrew Walbrancc0db522021-07-12 17:03:42 +0000661 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900662}
663
Alan Stokes0d1ef782022-09-27 13:46:35 +0100664fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
665 let mut apk_zip = ZipArchive::new(apk_file)?;
666 let config_file = apk_zip.by_name(config_path)?;
667 Ok(serde_json::from_reader(config_file)?)
668}
669
670fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
671 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
672 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
673 // payload config that we send it via the metadata file.
674 let task = Task {
675 type_: TaskType::MicrodroidLauncher,
676 command: payload_config.payloadPath.clone(),
677 args: payload_config.args.clone(),
678 };
679 VmPayloadConfig {
680 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
681 task: Some(task),
682 apexes: vec![],
683 extra_apks: vec![],
684 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100685 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100686 enable_authfs: false,
687 }
688}
689
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000690/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000691fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000692 temporary_directory: &Path,
693 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000694) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000695 let id = *next_temporary_image_id;
696 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000697 CompositeImageFilenames {
698 composite: temporary_directory.join(format!("composite-{}.img", id)),
699 header: temporary_directory.join(format!("composite-{}-header.img", id)),
700 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
701 }
702}
703
704/// Filenames for a composite disk image, including header and footer partitions.
705#[derive(Clone, Debug, Eq, PartialEq)]
706struct CompositeImageFilenames {
707 /// The composite disk image itself.
708 composite: PathBuf,
709 /// The header partition image.
710 header: PathBuf,
711 /// The footer partition image.
712 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000713}
714
715/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000716fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000717 ThreadState::with_calling_sid(|sid| {
718 if let Some(sid) = sid {
719 match sid.to_str() {
720 Ok(sid) => Ok(sid.to_owned()),
721 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000722 error!("SID was not valid UTF-8: {}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000723 Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000724 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000725 Some(format!("SID was not valid UTF-8: {}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000726 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000727 }
728 }
729 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000730 error!("Missing SID on createVm");
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000731 Err(Status::new_exception_str(ExceptionCode::SECURITY, Some("Missing SID on createVm")))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000732 }
733 })
734}
735
Jiyong Park753553b2021-07-12 21:21:09 +0900736/// Checks whether the caller has a specific permission
737fn check_permission(perm: &str) -> binder::Result<()> {
738 let calling_pid = ThreadState::get_calling_pid();
739 let calling_uid = ThreadState::get_calling_uid();
740 // Root can do anything
741 if calling_uid == 0 {
742 return Ok(());
743 }
744 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
745 binder::get_interface("permission")?;
746 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000747 Ok(())
748 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000749 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900750 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000751 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900752 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000753 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000754}
755
Jiyong Park753553b2021-07-12 21:21:09 +0900756/// Check whether the caller of the current Binder method is allowed to call debug methods.
757fn check_debug_access() -> binder::Result<()> {
758 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
759}
760
761/// Check whether the caller of the current Binder method is allowed to manage VMs
762fn check_manage_access() -> binder::Result<()> {
763 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
764}
765
Inseob Kim1119d702022-05-02 18:01:58 +0900766/// Check whether the caller of the current Binder method is allowed to create custom VMs
767fn check_use_custom_virtual_machine() -> binder::Result<()> {
768 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
769}
770
Jiyong Park029977d2021-11-24 21:56:49 +0900771/// Check if a partition has selinux labels that are not allowed
772fn check_label_for_partition(partition: &Partition) -> Result<()> {
773 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100774 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
775}
776
777// Return whether a partition is exempt from selinux label checks, because we know that it does
778// not contain code and is likely to be generated in an app-writable directory.
779fn is_safe_app_partition(label: &str) -> bool {
780 // See make_payload_disk in payload.rs.
781 label == "vm-instance"
782 || label == "microdroid-apk-idsig"
783 || label == "payload-metadata"
784 || label.starts_with("extra-idsig-")
785}
786
787fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
788 // We only want to allow code in a VM payload to be sourced from places that apps, and the
789 // system, do not have write access to.
790 // (Note that sepolicy must also grant read access for these types to both virtualization
791 // service and crosvm.)
792 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
793 // user devices (W^X).
794 match ctx.selinux_type()? {
795 | "system_file" // immutable dm-verity protected partition
796 | "apk_data_file" // APKs of an installed app
797 | "staging_data_file" // updated/staged APEX imagess
798 | "shell_data_file" // test files created via adb shell
799 => Ok(()),
800 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900801 }
802}
803
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000804/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
805#[derive(Debug)]
806struct VirtualMachine {
807 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100808 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800809 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100810 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000811}
812
813impl VirtualMachine {
814 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100815 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000816 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000817 }
818}
819
820impl Interface for VirtualMachine {}
821
822impl IVirtualMachine for VirtualMachine {
823 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900824 // Don't check permission. The owner of the VM might have passed this binder object to
825 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000826 Ok(self.instance.cid as i32)
827 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000828
Andrew Walbran6b650662021-09-07 13:13:23 +0000829 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900830 // Don't check permission. The owner of the VM might have passed this binder object to
831 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000832 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000833 }
834
835 fn registerCallback(
836 &self,
837 callback: &Strong<dyn IVirtualMachineCallback>,
838 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900839 // Don't check permission. The owner of the VM might have passed this binder object to
840 // others.
841 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000842 // TODO: Should this give an error if the VM is already dead?
843 self.instance.callbacks.add(callback.clone());
844 Ok(())
845 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000846
Andrew Walbranf8d94112021-09-07 11:45:36 +0000847 fn start(&self) -> binder::Result<()> {
848 self.instance.start().map_err(|e| {
849 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000850 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000851 })
852 }
853
Inseob Kima446f802022-07-11 19:46:37 +0900854 fn stop(&self) -> binder::Result<()> {
855 self.instance.kill().map_err(|e| {
856 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000857 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900858 })
859 }
860
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000861 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000862 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000863 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000864 }
865 let stream =
866 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000867 Status::new_service_specific_error_str(
868 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100869 Some(format!("Failed to connect: {:?}", e)),
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000870 )
871 })?;
872 Ok(vsock_stream_to_pfd(stream))
873 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000874}
875
876impl Drop for VirtualMachine {
877 fn drop(&mut self) {
878 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900879 if let Err(e) = self.instance.kill() {
880 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
881 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000882 }
883}
884
885/// A set of Binders to be called back in response to various events on the VM, such as when it
886/// dies.
887#[derive(Debug, Default)]
888pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
889
890impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900891 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900892 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900893 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900894 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900895 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900896 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100897 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900898 }
899 }
900 }
901
Inseob Kim14cb8692021-08-31 21:50:39 +0900902 /// Call all registered callbacks to notify that the payload is ready to serve.
903 pub fn notify_payload_ready(&self, cid: Cid) {
904 let callbacks = &*self.0.lock().unwrap();
905 for callback in callbacks {
906 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100907 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900908 }
909 }
910 }
911
Inseob Kim2444af92021-08-31 01:22:50 +0900912 /// Call all registered callbacks to notify that the payload has finished.
913 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
914 let callbacks = &*self.0.lock().unwrap();
915 for callback in callbacks {
916 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100917 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900918 }
919 }
920 }
921
Jooyung Handd0a1732021-11-23 15:26:20 +0900922 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100923 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900924 let callbacks = &*self.0.lock().unwrap();
925 for callback in callbacks {
926 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100927 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900928 }
929 }
930 }
931
Andrew Walbrandae07162021-03-12 17:05:20 +0000932 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000933 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000934 let callbacks = &*self.0.lock().unwrap();
935 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000936 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100937 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000938 }
939 }
940 }
941
Jiyong Parke558ab12022-07-07 20:18:55 +0900942 /// Call all registered callbacks to say that there was a ramdump to download.
943 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
944 let callbacks = &*self.0.lock().unwrap();
945 let pfd = ParcelFileDescriptor::new(ramdump);
946 for callback in callbacks {
947 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100948 error!("Error notifying ramdump of VM CID {}: {:?}", cid, e);
Jiyong Parke558ab12022-07-07 20:18:55 +0900949 }
950 }
951 }
952
Andrew Walbrandae07162021-03-12 17:05:20 +0000953 /// Add a new callback to the set.
954 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
955 self.0.lock().unwrap().push(callback);
956 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000957}
958
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000959/// The mutable state of the VirtualizationService. There should only be one instance of this
960/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800961#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000962struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000963 /// The VMs which have been started. When VMs are started a weak reference is added to this list
964 /// while a strong reference is returned to the caller over Binder. Once all copies of the
965 /// Binder client are dropped the weak reference here will become invalid, and will be removed
966 /// from the list opportunistically the next time `add_vm` is called.
967 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000968
969 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
970 /// This is only used for debugging purposes.
971 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000972}
973
974impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000975 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000976 fn vms(&self) -> Vec<Arc<VmInstance>> {
977 // Attempt to upgrade the weak pointers to strong pointers.
978 self.vms.iter().filter_map(Weak::upgrade).collect()
979 }
980
981 /// Add a new VM to the list.
982 fn add_vm(&mut self, vm: Weak<VmInstance>) {
983 // Garbage collect any entries from the stored list which no longer exist.
984 self.vms.retain(|vm| vm.strong_count() > 0);
985
986 // Actually add the new VM.
987 self.vms.push(vm);
988 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000989
Jiyong Park8611a6c2021-07-09 18:17:44 +0900990 /// Get a VM that corresponds to the given cid
991 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
992 self.vms().into_iter().find(|vm| vm.cid == cid)
993 }
994
David Brazdil3c2ddef2021-03-18 13:09:57 +0000995 /// Store a strong VM reference.
996 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
997 self.debug_held_vms.push(vm);
998 }
999
1000 /// Retrieve and remove a strong VM reference.
1001 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1002 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001003 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001004 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001005 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001006}
1007
Jiyong Parkd50a0242021-09-16 21:00:14 +09001008/// Get the next available CID, or an error if we have run out. The last CID used is stored in
1009/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
1010/// Android is up.
1011fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +00001012 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +09001013 if let Ok(num) = val.parse::<u32>() {
1014 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
1015 } else {
1016 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
1017 FIRST_GUEST_CID
1018 }
1019 } else {
1020 // First VM since the boot
1021 FIRST_GUEST_CID
1022 };
1023 // Persist the last value for next use
1024 let str_val = format!("{}", next);
1025 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
1026 Ok(next)
1027}
1028
Andrew Walbran6b650662021-09-07 13:13:23 +00001029/// Gets the `VirtualMachineState` of the given `VmInstance`.
1030fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001031 match &*instance.vm_state.lock().unwrap() {
1032 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1033 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001034 PayloadState::Starting => VirtualMachineState::STARTING,
1035 PayloadState::Started => VirtualMachineState::STARTED,
1036 PayloadState::Ready => VirtualMachineState::READY,
1037 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001038 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001039 },
1040 VmState::Dead => VirtualMachineState::DEAD,
1041 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001042 }
1043}
1044
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001045/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001046pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001047 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001048 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001049 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001050 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001051 )
1052 })
1053}
1054
Andrew Walbrand3a84182021-09-07 14:48:52 +00001055/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1056fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1057 file.as_ref().map(clone_file).transpose()
1058}
1059
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001060/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1061fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1062 // SAFETY: ownership is transferred from stream to f
1063 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1064 ParcelFileDescriptor::new(f)
1065}
1066
Jiyong Parkdcf17412022-02-08 15:07:23 +09001067/// Parses the platform version requirement string.
1068fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1069 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001070 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001071 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001072 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001073 )
1074 })
1075}
1076
Jooyung Han35edb8f2021-07-01 16:17:16 +09001077/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1078/// it doesn't require that T implements Clone.
1079enum BorrowedOrOwned<'a, T> {
1080 Borrowed(&'a T),
1081 Owned(T),
1082}
1083
1084impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1085 fn as_ref(&self) -> &T {
1086 match self {
1087 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001088 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001089 }
1090 }
1091}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001092
1093/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1094#[derive(Debug, Default)]
1095struct VirtualMachineService {
1096 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001097 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001098}
1099
1100impl Interface for VirtualMachineService {}
1101
1102impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001103 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1104 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001105 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1106 info!("VM having CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001107 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1108 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1109 })?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001110 let stream = vm.stream.lock().unwrap().take();
1111 vm.callbacks.notify_payload_started(cid, stream);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001112
Seungjae Yoo2e7beea2022-08-24 16:09:12 +09001113 let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap();
1114 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001115 Ok(())
1116 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001117 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001118 Err(Status::new_service_specific_error_str(
1119 -1,
1120 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001121 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001122 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001123 }
Inseob Kim2444af92021-08-31 01:22:50 +09001124
Inseob Kimc7d28c72021-10-25 14:28:10 +00001125 fn notifyPayloadReady(&self) -> binder::Result<()> {
1126 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001127 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1128 info!("VM having CID {} payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001129 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1130 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1131 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001132 vm.callbacks.notify_payload_ready(cid);
1133 Ok(())
1134 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001135 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001136 Err(Status::new_service_specific_error_str(
1137 -1,
1138 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001139 ))
1140 }
1141 }
1142
Inseob Kimc7d28c72021-10-25 14:28:10 +00001143 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1144 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001145 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1146 info!("VM having CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001147 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1148 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1149 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001150 vm.callbacks.notify_payload_finished(cid, exit_code);
1151 Ok(())
1152 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001153 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001154 Err(Status::new_service_specific_error_str(
1155 -1,
1156 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001157 ))
1158 }
1159 }
1160
Alan Stokes2bead0d2022-09-05 16:58:34 +01001161 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001162 let cid = self.cid;
1163 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1164 info!("VM having CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001165 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1166 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1167 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001168 vm.callbacks.notify_error(cid, error_code, message);
1169 Ok(())
1170 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001171 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001172 Err(Status::new_service_specific_error_str(
1173 -1,
1174 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001175 ))
1176 }
1177 }
Seungjae Yoofd9a0622022-10-14 10:01:29 +09001178
1179 fn notifyCpuStatus(&self, status: &VirtualMachineCpuStatus) -> binder::Result<()> {
1180 let cid = self.cid;
1181 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1182 info!("VM having CID {} encountered an error", cid);
1183 write_vm_cpu_status_stats(vm.requester_uid as i32, &vm.name, status);
1184 Ok(())
1185 } else {
1186 error!("notifyCurrentStatus is called from an unknown CID {}", cid);
1187 Err(Status::new_service_specific_error_str(
1188 -1,
1189 Some(format!("cannot find a VM with CID {}", cid)),
1190 ))
1191 }
1192 }
1193
1194 fn notifyMemStatus(&self, status: &VirtualMachineMemStatus) -> binder::Result<()> {
1195 let cid = self.cid;
1196 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1197 info!("VM having CID {} encountered an error", cid);
1198 write_vm_mem_status_stats(vm.requester_uid as i32, &vm.name, status);
1199 Ok(())
1200 } else {
1201 error!("notifyCurrentStatus is called from an unknown CID {}", cid);
1202 Err(Status::new_service_specific_error_str(
1203 -1,
1204 Some(format!("cannot find a VM with CID {}", cid)),
1205 ))
1206 }
1207 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001208}
1209
1210impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001211 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001212 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1213 let mut vm_service = vm.vm_service.lock().unwrap();
1214 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001215 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001216 } else {
1217 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001218 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001219 }
1220 }
1221
1222 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001223 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001224 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001225 BinderFeatures::default(),
1226 )
1227 }
1228}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001229
1230#[cfg(test)]
1231mod tests {
1232 use super::*;
1233
1234 #[test]
1235 fn test_is_allowed_label_for_partition() -> Result<()> {
1236 let expected_results = vec![
1237 ("u:object_r:system_file:s0", true),
1238 ("u:object_r:apk_data_file:s0", true),
1239 ("u:object_r:app_data_file:s0", false),
1240 ("u:object_r:app_data_file:s0:c512,c768", false),
1241 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1242 ("invalid", false),
1243 ("user:role:apk_data_file:severity:categories", true),
1244 ("user:role:apk_data_file:severity:categories:extraneous", false),
1245 ];
1246
1247 for (label, expected_valid) in expected_results {
1248 let context = SeContext::new(label)?;
1249 let result = check_label_is_allowed(&context);
1250 if expected_valid {
1251 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1252 } else if result.is_ok() {
1253 bail!("Expected label {} to be disallowed", label);
1254 }
1255 }
1256 Ok(())
1257 }
1258}