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