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