Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // 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 Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 15 | //! Implementation of the AIDL interface of the VirtualizationService. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 16 | |
Seungjae Yoo | acf559a | 2022-08-12 04:44:51 +0000 | [diff] [blame] | 17 | use crate::atom::{write_vm_booted_stats, write_vm_creation_stats}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 18 | use crate::composite::make_composite_image; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 19 | use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 20 | use crate::payload::add_microdroid_images; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 21 | use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID}; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 22 | use crate::selinux::{SeContext, getfilecon}; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 23 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 24 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 25 | DeathReason::DeathReason, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 26 | DiskImage::DiskImage, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 27 | IVirtualMachine::{BnVirtualMachine, IVirtualMachine}, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 28 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 29 | IVirtualizationService::IVirtualizationService, |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 30 | Partition::Partition, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 31 | PartitionType::PartitionType, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 32 | VirtualMachineAppConfig::{VirtualMachineAppConfig, Payload::Payload}, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 33 | VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 34 | VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 35 | VirtualMachinePayloadConfig::VirtualMachinePayloadConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 36 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 37 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 38 | }; |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 39 | use binder::{ |
Andrew Walbran | 46999c9 | 2022-08-04 17:33:46 +0000 | [diff] [blame] | 40 | self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor, |
| 41 | SpIBinder, Status, StatusCode, Strong, ThreadState, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 42 | }; |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 43 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{ |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 44 | BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT, |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 45 | VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 46 | }; |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 47 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 48 | use anyhow::{anyhow, bail, Context, Result}; |
Andrew Walbran | 7eb5ca4 | 2022-08-08 15:33:34 +0000 | [diff] [blame] | 49 | use rpcbinder::run_rpc_server_with_factory; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 50 | use disk::QcowFile; |
Alice Wang | 1bf3d78 | 2022-09-28 07:56:36 +0000 | [diff] [blame] | 51 | use apkverify::{HashAlgorithm, V4Signature}; |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 52 | use log::{debug, error, info, warn}; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 53 | use microdroid_payload_config::{VmPayloadConfig, OsConfig, Task, TaskType}; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 54 | use rustutils::system_properties; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 55 | use semver::VersionReq; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 56 | use std::convert::TryInto; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 57 | use std::ffi::CStr; |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 58 | use std::fs::{create_dir, File, OpenOptions}; |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 59 | use std::io::{Error, ErrorKind, Write, Read}; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 60 | use std::num::NonZeroU32; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 61 | use std::os::unix::io::{FromRawFd, IntoRawFd}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 62 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 63 | use std::sync::{Arc, Mutex, Weak}; |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 64 | use tombstoned_client::{TombstonedConnection, DebuggerdDumpType}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 65 | use vmconfig::VmConfig; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 66 | use vsock::{SockAddr, VsockListener, VsockStream}; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 67 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 68 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 69 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 70 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 71 | /// Directory in which to write disk image files used while running VMs. |
Andrew Walbran | 488bd07 | 2021-07-14 13:29:51 +0000 | [diff] [blame] | 72 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 73 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 74 | /// The CID representing the host VM |
| 75 | const VMADDR_CID_HOST: u32 = 2; |
| 76 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 77 | /// The size of zero.img. |
| 78 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 79 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 80 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 81 | /// Magic string for the instance image |
| 82 | const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance"; |
| 83 | |
| 84 | /// Version of the instance image format |
| 85 | const ANDROID_VM_INSTANCE_VERSION: u16 = 1; |
| 86 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 87 | const CHUNK_RECV_MAX_LEN: usize = 1024; |
| 88 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 89 | const MICRODROID_OS_NAME: &str = "microdroid"; |
| 90 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 91 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame] | 92 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 93 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 94 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 95 | } |
| 96 | |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 97 | impl Interface for VirtualizationService { |
| 98 | fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> { |
| 99 | check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?; |
| 100 | let state = &mut *self.state.lock().unwrap(); |
| 101 | let vms = state.vms(); |
| 102 | writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 103 | for vm in vms { |
| 104 | writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 105 | writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap()) |
| 106 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 107 | writeln!(file, "\tPayload state {:?}", vm.payload_state()) |
| 108 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 109 | writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 110 | writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy()) |
| 111 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 112 | writeln!(file, "\trequester_uid: {}", vm.requester_uid) |
| 113 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 114 | writeln!(file, "\trequester_sid: {}", vm.requester_sid) |
| 115 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 116 | writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid) |
| 117 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 118 | } |
| 119 | Ok(()) |
| 120 | } |
| 121 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 122 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 123 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 124 | /// Creates (but does not start) a new VM with the given configuration, assigning it the next |
| 125 | /// available CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 126 | /// |
| 127 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 128 | fn createVm( |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 129 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 130 | config: &VirtualMachineConfig, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 131 | console_fd: Option<&ParcelFileDescriptor>, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 132 | log_fd: Option<&ParcelFileDescriptor>, |
| 133 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 134 | let mut is_protected = false; |
| 135 | let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected); |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 136 | write_vm_creation_stats(config, is_protected, &ret); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 137 | ret |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 138 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 139 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 140 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 141 | fn initializeWritablePartition( |
| 142 | &self, |
| 143 | image_fd: &ParcelFileDescriptor, |
| 144 | size: i64, |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 145 | partition_type: PartitionType, |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 146 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 147 | check_manage_access()?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 148 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 149 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 150 | ExceptionCode::ILLEGAL_ARGUMENT, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 151 | Some(format!("Invalid size {}: {:?}", size, e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 152 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 153 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 154 | let image = clone_file(image_fd)?; |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 155 | // initialize the file. Any data in the file will be erased. |
| 156 | image.set_len(0).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 157 | Status::new_service_specific_error_str( |
| 158 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 159 | Some(format!("Failed to reset a file: {:?}", e)), |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 160 | ) |
| 161 | })?; |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 162 | let mut part = QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 163 | Status::new_service_specific_error_str( |
| 164 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 165 | Some(format!("Failed to create QCOW2 image: {:?}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 166 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 167 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 168 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 169 | match partition_type { |
| 170 | PartitionType::RAW => Ok(()), |
| 171 | PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part), |
| 172 | _ => Err(Error::new( |
| 173 | ErrorKind::Unsupported, |
| 174 | format!("Unsupported partition type {:?}", partition_type), |
| 175 | )), |
| 176 | } |
| 177 | .map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 178 | Status::new_service_specific_error_str( |
| 179 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 180 | Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)), |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 181 | ) |
| 182 | })?; |
| 183 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 184 | Ok(()) |
| 185 | } |
| 186 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 187 | /// Creates or update the idsig file by digesting the input APK file. |
| 188 | fn createOrUpdateIdsigFile( |
| 189 | &self, |
| 190 | input_fd: &ParcelFileDescriptor, |
| 191 | idsig_fd: &ParcelFileDescriptor, |
| 192 | ) -> binder::Result<()> { |
| 193 | // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in |
| 194 | // idsig_fd is different from APK digest in input_fd |
| 195 | |
Jiyong Park | c3ca24f | 2022-06-28 10:45:15 +0900 | [diff] [blame] | 196 | check_manage_access()?; |
| 197 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 198 | let mut input = clone_file(input_fd)?; |
| 199 | let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap(); |
| 200 | |
| 201 | let mut output = clone_file(idsig_fd)?; |
| 202 | output.set_len(0).unwrap(); |
| 203 | sig.write_into(&mut output).unwrap(); |
| 204 | Ok(()) |
| 205 | } |
| 206 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 207 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 208 | /// and as such is only permitted from the shell user. |
| 209 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 210 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 211 | |
| 212 | let state = &mut *self.state.lock().unwrap(); |
| 213 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 214 | let cids = vms |
| 215 | .into_iter() |
| 216 | .map(|vm| VirtualMachineDebugInfo { |
| 217 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 218 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 219 | requesterUid: vm.requester_uid as i32, |
| 220 | requesterSid: vm.requester_sid.clone(), |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 221 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 222 | state: get_state(&vm), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 223 | }) |
| 224 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 225 | Ok(cids) |
| 226 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 227 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 228 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 229 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 230 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 231 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 232 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 233 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 234 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 235 | Ok(()) |
| 236 | } |
| 237 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 238 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 239 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 240 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 241 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 242 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 243 | |
| 244 | let state = &mut *self.state.lock().unwrap(); |
| 245 | Ok(state.debug_drop_vm(cid)) |
| 246 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 247 | } |
| 248 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 249 | fn handle_stream_connection_tombstoned() -> Result<()> { |
| 250 | let listener = |
| 251 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?; |
| 252 | info!("Listening to tombstones from guests ..."); |
| 253 | for incoming_stream in listener.incoming() { |
| 254 | let mut incoming_stream = match incoming_stream { |
| 255 | Err(e) => { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 256 | warn!("invalid incoming connection: {:?}", e); |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 257 | continue; |
| 258 | } |
| 259 | Ok(s) => s, |
| 260 | }; |
| 261 | std::thread::spawn(move || { |
| 262 | if let Err(e) = handle_tombstone(&mut incoming_stream) { |
| 263 | error!("Failed to write tombstone- {:?}", e); |
| 264 | } |
| 265 | }); |
| 266 | } |
| 267 | Ok(()) |
| 268 | } |
| 269 | |
| 270 | fn handle_tombstone(stream: &mut VsockStream) -> Result<()> { |
| 271 | if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() { |
| 272 | info!("Vsock Stream connected to cid={} for tombstones", addr.cid()); |
| 273 | } |
| 274 | let tb_connection = |
| 275 | TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone) |
| 276 | .context("Failed to connect to tombstoned")?; |
| 277 | let mut text_output = tb_connection |
| 278 | .text_output |
| 279 | .as_ref() |
| 280 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 281 | let mut num_bytes_read = 0; |
| 282 | loop { |
| 283 | let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN]; |
| 284 | let n = stream |
| 285 | .read(&mut chunk_recv) |
| 286 | .context("Failed to read tombstone data from Vsock stream")?; |
| 287 | if n == 0 { |
| 288 | break; |
| 289 | } |
| 290 | num_bytes_read += n; |
| 291 | text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?; |
| 292 | } |
| 293 | info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read); |
| 294 | tb_connection.notify_completion()?; |
| 295 | Ok(()) |
| 296 | } |
| 297 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 298 | impl VirtualizationService { |
| 299 | pub fn init() -> VirtualizationService { |
| 300 | let service = VirtualizationService::default(); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 301 | |
| 302 | // server for payload output |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 303 | let state = service.state.clone(); // reference to state (not the state itself) is copied |
| 304 | std::thread::spawn(move || { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 305 | handle_stream_connection_from_vm(state).unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 306 | }); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 307 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 308 | std::thread::spawn(|| { |
| 309 | if let Err(e) = handle_stream_connection_tombstoned() { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 310 | warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e); |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 311 | } |
| 312 | }); |
| 313 | |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 314 | // binder server for vm |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 315 | // reference to state (not the state itself) is copied |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 316 | let state = service.state.clone(); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 317 | std::thread::spawn(move || { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 318 | debug!("VirtualMachineService is starting as an RPC service."); |
| 319 | if run_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| { |
| 320 | VirtualMachineService::factory(cid, &state) |
| 321 | }) { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 322 | debug!("RPC server has shut down gracefully"); |
| 323 | } else { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 324 | panic!("Premature termination of RPC server"); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 325 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 326 | }); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 327 | service |
| 328 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 329 | |
| 330 | fn create_vm_internal( |
| 331 | &self, |
| 332 | config: &VirtualMachineConfig, |
| 333 | console_fd: Option<&ParcelFileDescriptor>, |
| 334 | log_fd: Option<&ParcelFileDescriptor>, |
| 335 | is_protected: &mut bool, |
| 336 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
| 337 | check_manage_access()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 338 | |
| 339 | if let VirtualMachineConfig::RawConfig(config) = config { |
| 340 | if config.protectedVm { |
| 341 | check_use_custom_virtual_machine()?; |
| 342 | } |
| 343 | } |
| 344 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 345 | let state = &mut *self.state.lock().unwrap(); |
| 346 | let console_fd = console_fd.map(clone_file).transpose()?; |
| 347 | let log_fd = log_fd.map(clone_file).transpose()?; |
| 348 | let requester_uid = ThreadState::get_calling_uid(); |
| 349 | let requester_sid = get_calling_sid()?; |
| 350 | let requester_debug_pid = ThreadState::get_calling_pid(); |
| 351 | let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?; |
| 352 | |
| 353 | // Counter to generate unique IDs for temporary image files. |
| 354 | let mut next_temporary_image_id = 0; |
| 355 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 356 | // child process, and not closed before it is started. |
| 357 | let mut indirect_files = vec![]; |
| 358 | |
| 359 | // Make directory for temporary files. |
| 360 | let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 361 | create_dir(&temporary_directory).map_err(|e| { |
| 362 | // At this point, we do not know the protected status of Vm |
| 363 | // setting it to false, though this may not be correct. |
| 364 | error!( |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 365 | "Failed to create temporary directory {:?} for VM files: {:?}", |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 366 | temporary_directory, e |
| 367 | ); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 368 | Status::new_service_specific_error_str( |
| 369 | -1, |
| 370 | Some(format!( |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 371 | "Failed to create temporary directory {:?} for VM files: {:?}", |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 372 | temporary_directory, e |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 373 | )), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 374 | ) |
| 375 | })?; |
| 376 | |
| 377 | let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_)); |
| 378 | |
| 379 | let config = match config { |
| 380 | VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned( |
| 381 | load_app_config(config, &temporary_directory).map_err(|e| { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 382 | *is_protected = config.protectedVm; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 383 | let message = format!("Failed to load app config: {:?}", e); |
| 384 | error!("{}", message); |
| 385 | Status::new_service_specific_error_str(-1, Some(message)) |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 386 | })?, |
| 387 | ), |
| 388 | VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config), |
| 389 | }; |
| 390 | let config = config.as_ref(); |
| 391 | *is_protected = config.protectedVm; |
| 392 | |
| 393 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 394 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 395 | // being loaded in a pVM. This applies to everything in the raw config, and everything but |
| 396 | // the non-executable, generated partitions in the app config. |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 397 | config |
| 398 | .disks |
| 399 | .iter() |
| 400 | .flat_map(|disk| disk.partitions.iter()) |
| 401 | .filter(|partition| { |
| 402 | if is_app_config { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 403 | !is_safe_app_partition(&partition.label) |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 404 | } else { |
| 405 | true // all partitions are checked |
| 406 | } |
| 407 | }) |
| 408 | .try_for_each(check_label_for_partition) |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 409 | .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 410 | |
| 411 | let zero_filler_path = temporary_directory.join("zero.img"); |
| 412 | write_zero_filler(&zero_filler_path).map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 413 | error!("Failed to make composite image: {:?}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 414 | Status::new_service_specific_error_str( |
| 415 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 416 | Some(format!("Failed to make composite image: {:?}", e)), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 417 | ) |
| 418 | })?; |
| 419 | |
| 420 | // Assemble disk images if needed. |
| 421 | let disks = config |
| 422 | .disks |
| 423 | .iter() |
| 424 | .map(|disk| { |
| 425 | assemble_disk_image( |
| 426 | disk, |
| 427 | &zero_filler_path, |
| 428 | &temporary_directory, |
| 429 | &mut next_temporary_image_id, |
| 430 | &mut indirect_files, |
| 431 | ) |
| 432 | }) |
| 433 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 434 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 435 | // Creating this ramdump file unconditionally is not harmful as ramdump will be created |
| 436 | // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 437 | // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read` |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 438 | // will be sent back to the client (i.e. the VM owner) for readout. |
| 439 | let ramdump_path = temporary_directory.join("ramdump"); |
| 440 | let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 441 | error!("Failed to prepare ramdump file: {:?}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 442 | Status::new_service_specific_error_str( |
| 443 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 444 | Some(format!("Failed to prepare ramdump file: {:?}", e)), |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 445 | ) |
| 446 | })?; |
| 447 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 448 | // Actually start the VM. |
| 449 | let crosvm_config = CrosvmConfig { |
| 450 | cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 451 | name: config.name.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 452 | bootloader: maybe_clone_file(&config.bootloader)?, |
| 453 | kernel: maybe_clone_file(&config.kernel)?, |
| 454 | initrd: maybe_clone_file(&config.initrd)?, |
| 455 | disks, |
| 456 | params: config.params.to_owned(), |
| 457 | protected: *is_protected, |
| 458 | memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new), |
| 459 | cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new), |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 460 | task_profiles: config.taskProfiles.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 461 | console_fd, |
| 462 | log_fd, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 463 | ramdump: Some(ramdump), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 464 | indirect_files, |
| 465 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 466 | detect_hangup: is_app_config, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 467 | }; |
| 468 | let instance = Arc::new( |
| 469 | VmInstance::new( |
| 470 | crosvm_config, |
| 471 | temporary_directory, |
| 472 | requester_uid, |
| 473 | requester_sid, |
| 474 | requester_debug_pid, |
| 475 | ) |
| 476 | .map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 477 | error!("Failed to create VM with config {:?}: {:?}", config, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 478 | Status::new_service_specific_error_str( |
| 479 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 480 | Some(format!("Failed to create VM: {:?}", e)), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 481 | ) |
| 482 | })?, |
| 483 | ); |
| 484 | state.add_vm(Arc::downgrade(&instance)); |
| 485 | Ok(VirtualMachine::create(instance)) |
| 486 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 487 | } |
| 488 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 489 | /// Waits for incoming connections from VM. If a new connection is made, stores the stream in the |
| 490 | /// corresponding `VmInstance`. |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 491 | fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> { |
Inseob Kim | d058756 | 2021-09-01 21:27:32 +0900 | [diff] [blame] | 492 | let listener = |
| 493 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 494 | for stream in listener.incoming() { |
| 495 | let stream = match stream { |
| 496 | Err(e) => { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 497 | warn!("invalid incoming connection: {:?}", e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 498 | continue; |
| 499 | } |
| 500 | Ok(s) => s, |
| 501 | }; |
| 502 | if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() { |
| 503 | let cid = addr.cid(); |
| 504 | let port = addr.port(); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 505 | info!("payload stream connected from cid={}, port={}", cid, port); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 506 | if let Some(vm) = state.lock().unwrap().get_vm(cid) { |
Chris Wailes | 8bbb893 | 2021-09-10 14:14:19 -0700 | [diff] [blame] | 507 | *vm.stream.lock().unwrap() = Some(stream); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 508 | } else { |
| 509 | error!("connection from cid={} is not from a guest VM", cid); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 510 | } |
| 511 | } |
| 512 | } |
| 513 | Ok(()) |
| 514 | } |
| 515 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 516 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 517 | let file = OpenOptions::new() |
| 518 | .create_new(true) |
| 519 | .read(true) |
| 520 | .write(true) |
| 521 | .open(zero_filler_path) |
| 522 | .with_context(|| "Failed to create zero.img")?; |
| 523 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 524 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 525 | } |
| 526 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 527 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 528 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 529 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 530 | part.flush() |
| 531 | } |
| 532 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 533 | fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> { |
| 534 | File::create(&ramdump_path) |
| 535 | .context(format!("Failed to create ramdump file {:?}", &ramdump_path)) |
| 536 | } |
| 537 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 538 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 539 | /// |
| 540 | /// This may involve assembling a composite disk from a set of partition images. |
| 541 | fn assemble_disk_image( |
| 542 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 543 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 544 | temporary_directory: &Path, |
| 545 | next_temporary_image_id: &mut u64, |
| 546 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 547 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 548 | let image = if !disk.partitions.is_empty() { |
| 549 | if disk.image.is_some() { |
| 550 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 551 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 552 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 553 | Some("DiskImage contains both image and partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 554 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 555 | } |
| 556 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 557 | let composite_image_filenames = |
| 558 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 559 | let (image, partition_files) = make_composite_image( |
| 560 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 561 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 562 | &composite_image_filenames.composite, |
| 563 | &composite_image_filenames.header, |
| 564 | &composite_image_filenames.footer, |
| 565 | ) |
| 566 | .map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 567 | error!("Failed to make composite image with config {:?}: {:?}", disk, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 568 | Status::new_service_specific_error_str( |
| 569 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 570 | Some(format!("Failed to make composite image: {:?}", e)), |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 571 | ) |
| 572 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 573 | |
| 574 | // Pass the file descriptors for the various partition files to crosvm when it |
| 575 | // is run. |
| 576 | indirect_files.extend(partition_files); |
| 577 | |
| 578 | image |
| 579 | } else if let Some(image) = &disk.image { |
| 580 | clone_file(image)? |
| 581 | } else { |
| 582 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 583 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 584 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 585 | Some("DiskImage didn't contain image or partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 586 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 587 | }; |
| 588 | |
| 589 | Ok(DiskFile { image, writable: disk.writable }) |
| 590 | } |
| 591 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 592 | fn load_app_config( |
| 593 | config: &VirtualMachineAppConfig, |
| 594 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 595 | ) -> Result<VirtualMachineRawConfig> { |
Alan Stokes | 82f389c | 2022-09-08 12:23:52 +0100 | [diff] [blame] | 596 | // Controlling CPUs is reserved for platform apps only, even when using |
| 597 | // VirtualMachineAppConfig. |
Victor Hsieh | f219cd8 | 2022-09-09 13:13:11 -0700 | [diff] [blame] | 598 | if !config.taskProfiles.is_empty() { |
Alan Stokes | 82f389c | 2022-09-08 12:23:52 +0100 | [diff] [blame] | 599 | check_use_custom_virtual_machine()? |
| 600 | } |
| 601 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 602 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 603 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 604 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 605 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 606 | let vm_payload_config = match &config.payload { |
| 607 | Payload::ConfigPath(config_path) => { |
| 608 | load_vm_payload_config_from_file(&apk_file, config_path.as_str()) |
| 609 | .with_context(|| format!("Couldn't read config from {}", config_path))? |
| 610 | } |
| 611 | Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config), |
| 612 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 613 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 614 | // For now, the only supported OS is Microdroid |
| 615 | let os_name = vm_payload_config.os.name.as_str(); |
| 616 | if os_name != MICRODROID_OS_NAME { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 617 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 618 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 619 | |
| 620 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 621 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 622 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 623 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 624 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 625 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 626 | if config.memoryMib > 0 { |
| 627 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 628 | } |
| 629 | |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 630 | vm_config.name = config.name.clone(); |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 631 | vm_config.protectedVm = config.protectedVm; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 632 | vm_config.numCpus = config.numCpus; |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 633 | vm_config.taskProfiles = config.taskProfiles.clone(); |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 634 | |
Shikha Panwar | ed8ace4 | 2022-09-28 12:52:16 +0000 | [diff] [blame] | 635 | // Microdroid requires an additional init ramdisk & payload disk image |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 636 | add_microdroid_images( |
| 637 | config, |
| 638 | temporary_directory, |
| 639 | apk_file, |
| 640 | idsig_file, |
| 641 | instance_file, |
| 642 | &vm_payload_config, |
| 643 | &mut vm_config, |
| 644 | )?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 645 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 646 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 647 | } |
| 648 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 649 | fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> { |
| 650 | let mut apk_zip = ZipArchive::new(apk_file)?; |
| 651 | let config_file = apk_zip.by_name(config_path)?; |
| 652 | Ok(serde_json::from_reader(config_file)?) |
| 653 | } |
| 654 | |
| 655 | fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig { |
| 656 | // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit |
| 657 | // parameters we've been given. Microdroid will do something equivalent inside the VM using the |
| 658 | // payload config that we send it via the metadata file. |
| 659 | let task = Task { |
| 660 | type_: TaskType::MicrodroidLauncher, |
| 661 | command: payload_config.payloadPath.clone(), |
| 662 | args: payload_config.args.clone(), |
| 663 | }; |
| 664 | VmPayloadConfig { |
| 665 | os: OsConfig { name: MICRODROID_OS_NAME.to_owned() }, |
| 666 | task: Some(task), |
| 667 | apexes: vec![], |
| 668 | extra_apks: vec![], |
| 669 | prefer_staged: false, |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 670 | export_tombstones: false, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 671 | enable_authfs: false, |
| 672 | } |
| 673 | } |
| 674 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 675 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 676 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 677 | temporary_directory: &Path, |
| 678 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 679 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 680 | let id = *next_temporary_image_id; |
| 681 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 682 | CompositeImageFilenames { |
| 683 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 684 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 685 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | /// Filenames for a composite disk image, including header and footer partitions. |
| 690 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 691 | struct CompositeImageFilenames { |
| 692 | /// The composite disk image itself. |
| 693 | composite: PathBuf, |
| 694 | /// The header partition image. |
| 695 | header: PathBuf, |
| 696 | /// The footer partition image. |
| 697 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 698 | } |
| 699 | |
| 700 | /// Gets the calling SID of the current Binder thread. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 701 | fn get_calling_sid() -> Result<String, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 702 | ThreadState::with_calling_sid(|sid| { |
| 703 | if let Some(sid) = sid { |
| 704 | match sid.to_str() { |
| 705 | Ok(sid) => Ok(sid.to_owned()), |
| 706 | Err(e) => { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 707 | error!("SID was not valid UTF-8: {}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 708 | Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 709 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 710 | Some(format!("SID was not valid UTF-8: {}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 711 | )) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 712 | } |
| 713 | } |
| 714 | } else { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 715 | error!("Missing SID on createVm"); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 716 | Err(Status::new_exception_str(ExceptionCode::SECURITY, Some("Missing SID on createVm"))) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 717 | } |
| 718 | }) |
| 719 | } |
| 720 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 721 | /// Checks whether the caller has a specific permission |
| 722 | fn check_permission(perm: &str) -> binder::Result<()> { |
| 723 | let calling_pid = ThreadState::get_calling_pid(); |
| 724 | let calling_uid = ThreadState::get_calling_uid(); |
| 725 | // Root can do anything |
| 726 | if calling_uid == 0 { |
| 727 | return Ok(()); |
| 728 | } |
| 729 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 730 | binder::get_interface("permission")?; |
| 731 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 732 | Ok(()) |
| 733 | } else { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 734 | Err(Status::new_exception_str( |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 735 | ExceptionCode::SECURITY, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 736 | Some(format!("does not have the {} permission", perm)), |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 737 | )) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 738 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 739 | } |
| 740 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 741 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 742 | fn check_debug_access() -> binder::Result<()> { |
| 743 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 744 | } |
| 745 | |
| 746 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 747 | fn check_manage_access() -> binder::Result<()> { |
| 748 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 749 | } |
| 750 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 751 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 752 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 753 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 754 | } |
| 755 | |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 756 | /// Check if a partition has selinux labels that are not allowed |
| 757 | fn check_label_for_partition(partition: &Partition) -> Result<()> { |
| 758 | let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?; |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 759 | check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label)) |
| 760 | } |
| 761 | |
| 762 | // Return whether a partition is exempt from selinux label checks, because we know that it does |
| 763 | // not contain code and is likely to be generated in an app-writable directory. |
| 764 | fn is_safe_app_partition(label: &str) -> bool { |
| 765 | // See make_payload_disk in payload.rs. |
| 766 | label == "vm-instance" |
| 767 | || label == "microdroid-apk-idsig" |
| 768 | || label == "payload-metadata" |
| 769 | || label.starts_with("extra-idsig-") |
| 770 | } |
| 771 | |
| 772 | fn check_label_is_allowed(ctx: &SeContext) -> Result<()> { |
| 773 | // We only want to allow code in a VM payload to be sourced from places that apps, and the |
| 774 | // system, do not have write access to. |
| 775 | // (Note that sepolicy must also grant read access for these types to both virtualization |
| 776 | // service and crosvm.) |
| 777 | // App private data files are deliberately excluded, to avoid arbitrary payloads being run on |
| 778 | // user devices (W^X). |
| 779 | match ctx.selinux_type()? { |
| 780 | | "system_file" // immutable dm-verity protected partition |
| 781 | | "apk_data_file" // APKs of an installed app |
| 782 | | "staging_data_file" // updated/staged APEX imagess |
| 783 | | "shell_data_file" // test files created via adb shell |
| 784 | => Ok(()), |
| 785 | _ => bail!("Label {} is not allowed", ctx), |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 786 | } |
| 787 | } |
| 788 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 789 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 790 | #[derive(Debug)] |
| 791 | struct VirtualMachine { |
| 792 | instance: Arc<VmInstance>, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 793 | /// Keeps our service process running as long as this VM instance exists. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 794 | #[allow(dead_code)] |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 795 | lazy_service_guard: LazyServiceGuard, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 796 | } |
| 797 | |
| 798 | impl VirtualMachine { |
| 799 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 800 | let binder = VirtualMachine { instance, lazy_service_guard: Default::default() }; |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 801 | BnVirtualMachine::new_binder(binder, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 802 | } |
| 803 | } |
| 804 | |
| 805 | impl Interface for VirtualMachine {} |
| 806 | |
| 807 | impl IVirtualMachine for VirtualMachine { |
| 808 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 809 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 810 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 811 | Ok(self.instance.cid as i32) |
| 812 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 813 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 814 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 815 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 816 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 817 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 818 | } |
| 819 | |
| 820 | fn registerCallback( |
| 821 | &self, |
| 822 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 823 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 824 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 825 | // others. |
| 826 | // |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 827 | // TODO: Should this give an error if the VM is already dead? |
| 828 | self.instance.callbacks.add(callback.clone()); |
| 829 | Ok(()) |
| 830 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 831 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 832 | fn start(&self) -> binder::Result<()> { |
| 833 | self.instance.start().map_err(|e| { |
| 834 | error!("Error starting VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 835 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 836 | }) |
| 837 | } |
| 838 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 839 | fn stop(&self) -> binder::Result<()> { |
| 840 | self.instance.kill().map_err(|e| { |
| 841 | error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 842 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 843 | }) |
| 844 | } |
| 845 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 846 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 847 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 848 | return Err(Status::new_service_specific_error_str(-1, Some("VM is not running"))); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 849 | } |
| 850 | let stream = |
| 851 | VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 852 | Status::new_service_specific_error_str( |
| 853 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 854 | Some(format!("Failed to connect: {:?}", e)), |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 855 | ) |
| 856 | })?; |
| 857 | Ok(vsock_stream_to_pfd(stream)) |
| 858 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 859 | } |
| 860 | |
| 861 | impl Drop for VirtualMachine { |
| 862 | fn drop(&mut self) { |
| 863 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 864 | if let Err(e) = self.instance.kill() { |
| 865 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 866 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 867 | } |
| 868 | } |
| 869 | |
| 870 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 871 | /// dies. |
| 872 | #[derive(Debug, Default)] |
| 873 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 874 | |
| 875 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 876 | /// Call all registered callbacks to notify that the payload has started. |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 877 | pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 878 | let callbacks = &*self.0.lock().unwrap(); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 879 | let pfd = stream.map(vsock_stream_to_pfd); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 880 | for callback in callbacks { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 881 | if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 882 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 883 | } |
| 884 | } |
| 885 | } |
| 886 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 887 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 888 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 889 | let callbacks = &*self.0.lock().unwrap(); |
| 890 | for callback in callbacks { |
| 891 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 892 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 893 | } |
| 894 | } |
| 895 | } |
| 896 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 897 | /// Call all registered callbacks to notify that the payload has finished. |
| 898 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 899 | let callbacks = &*self.0.lock().unwrap(); |
| 900 | for callback in callbacks { |
| 901 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 902 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 903 | } |
| 904 | } |
| 905 | } |
| 906 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 907 | /// Call all registered callbacks to say that the VM encountered an error. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 908 | pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 909 | let callbacks = &*self.0.lock().unwrap(); |
| 910 | for callback in callbacks { |
| 911 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 912 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 913 | } |
| 914 | } |
| 915 | } |
| 916 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 917 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 918 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 919 | let callbacks = &*self.0.lock().unwrap(); |
| 920 | for callback in callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 921 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 922 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 923 | } |
| 924 | } |
| 925 | } |
| 926 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 927 | /// Call all registered callbacks to say that there was a ramdump to download. |
| 928 | pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) { |
| 929 | let callbacks = &*self.0.lock().unwrap(); |
| 930 | let pfd = ParcelFileDescriptor::new(ramdump); |
| 931 | for callback in callbacks { |
| 932 | if let Err(e) = callback.onRamdump(cid as i32, &pfd) { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 933 | error!("Error notifying ramdump of VM CID {}: {:?}", cid, e); |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 934 | } |
| 935 | } |
| 936 | } |
| 937 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 938 | /// Add a new callback to the set. |
| 939 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 940 | self.0.lock().unwrap().push(callback); |
| 941 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 942 | } |
| 943 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 944 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 945 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 946 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 947 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 948 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 949 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 950 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 951 | /// from the list opportunistically the next time `add_vm` is called. |
| 952 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 953 | |
| 954 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 955 | /// This is only used for debugging purposes. |
| 956 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 957 | } |
| 958 | |
| 959 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 960 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 961 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 962 | // Attempt to upgrade the weak pointers to strong pointers. |
| 963 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 964 | } |
| 965 | |
| 966 | /// Add a new VM to the list. |
| 967 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 968 | // Garbage collect any entries from the stored list which no longer exist. |
| 969 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 970 | |
| 971 | // Actually add the new VM. |
| 972 | self.vms.push(vm); |
| 973 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 974 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 975 | /// Get a VM that corresponds to the given cid |
| 976 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 977 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 978 | } |
| 979 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 980 | /// Store a strong VM reference. |
| 981 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 982 | self.debug_held_vms.push(vm); |
| 983 | } |
| 984 | |
| 985 | /// Retrieve and remove a strong VM reference. |
| 986 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 987 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 988 | let vm = self.debug_held_vms.swap_remove(pos); |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 989 | Some(vm) |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 990 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 991 | } |
| 992 | |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 993 | /// Get the next available CID, or an error if we have run out. The last CID used is stored in |
| 994 | /// a system property so that restart of virtualizationservice doesn't reuse CID while the host |
| 995 | /// Android is up. |
| 996 | fn next_cid() -> Result<Cid> { |
Andrew Walbran | 014efb5 | 2022-02-03 17:43:11 +0000 | [diff] [blame] | 997 | let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? { |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 998 | if let Ok(num) = val.parse::<u32>() { |
| 999 | num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))? |
| 1000 | } else { |
| 1001 | error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID); |
| 1002 | FIRST_GUEST_CID |
| 1003 | } |
| 1004 | } else { |
| 1005 | // First VM since the boot |
| 1006 | FIRST_GUEST_CID |
| 1007 | }; |
| 1008 | // Persist the last value for next use |
| 1009 | let str_val = format!("{}", next); |
| 1010 | system_properties::write(SYSPROP_LAST_CID, &str_val)?; |
| 1011 | Ok(next) |
| 1012 | } |
| 1013 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1014 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 1015 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1016 | match &*instance.vm_state.lock().unwrap() { |
| 1017 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 1018 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1019 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 1020 | PayloadState::Started => VirtualMachineState::STARTED, |
| 1021 | PayloadState::Ready => VirtualMachineState::READY, |
| 1022 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 1023 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1024 | }, |
| 1025 | VmState::Dead => VirtualMachineState::DEAD, |
| 1026 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1027 | } |
| 1028 | } |
| 1029 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1030 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 1031 | pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1032 | file.as_ref().try_clone().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1033 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1034 | ExceptionCode::BAD_PARCELABLE, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1035 | Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1036 | ) |
| 1037 | }) |
| 1038 | } |
| 1039 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1040 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
| 1041 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> { |
| 1042 | file.as_ref().map(clone_file).transpose() |
| 1043 | } |
| 1044 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1045 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
| 1046 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1047 | // SAFETY: ownership is transferred from stream to f |
| 1048 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1049 | ParcelFileDescriptor::new(f) |
| 1050 | } |
| 1051 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1052 | /// Parses the platform version requirement string. |
| 1053 | fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> { |
| 1054 | VersionReq::parse(s).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1055 | Status::new_exception_str( |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1056 | ExceptionCode::BAD_PARCELABLE, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1057 | Some(format!("Invalid platform version requirement {}: {:?}", s, e)), |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1058 | ) |
| 1059 | }) |
| 1060 | } |
| 1061 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1062 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 1063 | /// it doesn't require that T implements Clone. |
| 1064 | enum BorrowedOrOwned<'a, T> { |
| 1065 | Borrowed(&'a T), |
| 1066 | Owned(T), |
| 1067 | } |
| 1068 | |
| 1069 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 1070 | fn as_ref(&self) -> &T { |
| 1071 | match self { |
| 1072 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 1073 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1074 | } |
| 1075 | } |
| 1076 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1077 | |
| 1078 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 1079 | #[derive(Debug, Default)] |
| 1080 | struct VirtualMachineService { |
| 1081 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1082 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1083 | } |
| 1084 | |
| 1085 | impl Interface for VirtualMachineService {} |
| 1086 | |
| 1087 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1088 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 1089 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1090 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1091 | info!("VM having CID {} started payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1092 | vm.update_payload_state(PayloadState::Started).map_err(|e| { |
| 1093 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1094 | })?; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1095 | let stream = vm.stream.lock().unwrap().take(); |
| 1096 | vm.callbacks.notify_payload_started(cid, stream); |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 1097 | |
Seungjae Yoo | 2e7beea | 2022-08-24 16:09:12 +0900 | [diff] [blame] | 1098 | let vm_start_timestamp = vm.vm_start_timestamp.lock().unwrap(); |
| 1099 | write_vm_booted_stats(vm.requester_uid as i32, &vm.name, *vm_start_timestamp); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1100 | Ok(()) |
| 1101 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1102 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1103 | Err(Status::new_service_specific_error_str( |
| 1104 | -1, |
| 1105 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1106 | )) |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1107 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1108 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1109 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1110 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 1111 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1112 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1113 | info!("VM having CID {} payload is ready", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1114 | vm.update_payload_state(PayloadState::Ready).map_err(|e| { |
| 1115 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1116 | })?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1117 | vm.callbacks.notify_payload_ready(cid); |
| 1118 | Ok(()) |
| 1119 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1120 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1121 | Err(Status::new_service_specific_error_str( |
| 1122 | -1, |
| 1123 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1124 | )) |
| 1125 | } |
| 1126 | } |
| 1127 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1128 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 1129 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1130 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1131 | info!("VM having CID {} finished payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1132 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1133 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1134 | })?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1135 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 1136 | Ok(()) |
| 1137 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1138 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1139 | Err(Status::new_service_specific_error_str( |
| 1140 | -1, |
| 1141 | Some(format!("cannot find a VM with CID {}", cid)), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1142 | )) |
| 1143 | } |
| 1144 | } |
| 1145 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1146 | fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1147 | let cid = self.cid; |
| 1148 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1149 | info!("VM having CID {} encountered an error", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1150 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1151 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1152 | })?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1153 | vm.callbacks.notify_error(cid, error_code, message); |
| 1154 | Ok(()) |
| 1155 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 1156 | error!("notifyError is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1157 | Err(Status::new_service_specific_error_str( |
| 1158 | -1, |
| 1159 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1160 | )) |
| 1161 | } |
| 1162 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1163 | } |
| 1164 | |
| 1165 | impl VirtualMachineService { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1166 | fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1167 | if let Some(vm) = state.lock().unwrap().get_vm(cid) { |
| 1168 | let mut vm_service = vm.vm_service.lock().unwrap(); |
| 1169 | let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid)); |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1170 | Some(service.as_binder()) |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1171 | } else { |
| 1172 | error!("connection from cid={} is not from a guest VM", cid); |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1173 | None |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1178 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1179 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1180 | BinderFeatures::default(), |
| 1181 | ) |
| 1182 | } |
| 1183 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1184 | |
| 1185 | #[cfg(test)] |
| 1186 | mod tests { |
| 1187 | use super::*; |
| 1188 | |
| 1189 | #[test] |
| 1190 | fn test_is_allowed_label_for_partition() -> Result<()> { |
| 1191 | let expected_results = vec![ |
| 1192 | ("u:object_r:system_file:s0", true), |
| 1193 | ("u:object_r:apk_data_file:s0", true), |
| 1194 | ("u:object_r:app_data_file:s0", false), |
| 1195 | ("u:object_r:app_data_file:s0:c512,c768", false), |
| 1196 | ("u:object_r:privapp_data_file:s0:c512,c768", false), |
| 1197 | ("invalid", false), |
| 1198 | ("user:role:apk_data_file:severity:categories", true), |
| 1199 | ("user:role:apk_data_file:severity:categories:extraneous", false), |
| 1200 | ]; |
| 1201 | |
| 1202 | for (label, expected_valid) in expected_results { |
| 1203 | let context = SeContext::new(label)?; |
| 1204 | let result = check_label_is_allowed(&context); |
| 1205 | if expected_valid { |
| 1206 | assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result); |
| 1207 | } else if result.is_ok() { |
| 1208 | bail!("Expected label {} to be disallowed", label); |
| 1209 | } |
| 1210 | } |
| 1211 | Ok(()) |
| 1212 | } |
| 1213 | } |