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