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