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