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