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