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