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