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}; |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame^] | 19 | use crate::payload::make_payload_disk; |
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 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 22 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 23 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 24 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{ |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 25 | BnVirtualMachine, IVirtualMachine, |
| 26 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 27 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 28 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
| 29 | VirtualMachineAppConfig::VirtualMachineAppConfig, |
| 30 | VirtualMachineConfig::VirtualMachineConfig, |
| 31 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
| 32 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 33 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo; |
| 34 | use android_system_virtualizationservice::binder::{ |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 35 | self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 36 | }; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 37 | use anyhow::{bail, Result}; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 38 | use disk::QcowFile; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 39 | use log::{debug, error, warn}; |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 40 | use microdroid_payload_config::{ApexConfig, VmPayloadConfig}; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 41 | use std::convert::TryInto; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 42 | use std::ffi::CString; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 43 | use std::fs::{File, create_dir}; |
| 44 | use std::os::unix::io::AsRawFd; |
| 45 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 46 | use std::sync::{Arc, Mutex, Weak}; |
Jiyong Park | 2360114 | 2021-07-05 13:15:32 +0900 | [diff] [blame] | 47 | use vmconfig::{VmConfig, Partition}; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 48 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 49 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 50 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 51 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 52 | /// Directory in which to write disk image files used while running VMs. |
| 53 | const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
| 54 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 55 | // TODO(qwandor): Use PermissionController once it is available to Rust. |
| 56 | /// Only processes running with one of these UIDs are allowed to call debug methods. |
| 57 | const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000]; |
| 58 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 59 | /// The list of APEXes which microdroid requires. |
| 60 | /// TODO(b/192200378) move this to microdroid.json? |
| 61 | const MICRODROID_REQUIRED_APEXES: [&str; 4] = |
| 62 | ["com.android.adbd", "com.android.i18n", "com.android.os.statsd", "com.android.sdkext"]; |
| 63 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 64 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame^] | 65 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 66 | pub struct VirtualizationService { |
Andrew Walbran | 9c01baa | 2021-03-08 18:23:50 +0000 | [diff] [blame] | 67 | state: Mutex<State>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 68 | } |
| 69 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 70 | impl Interface for VirtualizationService {} |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 71 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 72 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 73 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 74 | /// |
| 75 | /// 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] | 76 | fn startVm( |
| 77 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 78 | config: &VirtualMachineConfig, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 79 | log_fd: Option<&ParcelFileDescriptor>, |
| 80 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 81 | let state = &mut *self.state.lock().unwrap(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 82 | let log_fd = log_fd.map(clone_file).transpose()?; |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 83 | let requester_uid = ThreadState::get_calling_uid(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 84 | let requester_sid = get_calling_sid()?; |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 85 | let requester_debug_pid = ThreadState::get_calling_pid(); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 86 | let cid = state.allocate_cid()?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 87 | |
| 88 | // Counter to generate unique IDs for temporary image files. |
| 89 | let mut next_temporary_image_id = 0; |
| 90 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 91 | // child process, and not closed before it is started. |
| 92 | let mut indirect_files = vec![]; |
| 93 | |
| 94 | // Make directory for temporary files. |
| 95 | let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 96 | create_dir(&temporary_directory).map_err(|e| { |
| 97 | error!( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 98 | "Failed to create temporary directory {:?} for VM files: {}", |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 99 | temporary_directory, e |
| 100 | ); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 101 | new_binder_exception( |
| 102 | ExceptionCode::SERVICE_SPECIFIC, |
| 103 | format!( |
| 104 | "Failed to create temporary directory {:?} for VM files: {}", |
| 105 | temporary_directory, e |
| 106 | ), |
| 107 | ) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 108 | })?; |
| 109 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 110 | let config = match config { |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 111 | VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned( |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame^] | 112 | load_app_config(config, &temporary_directory).map_err(|e| { |
| 113 | error!("Failed to load app config from {}: {}", &config.configPath, e); |
| 114 | new_binder_exception( |
| 115 | ExceptionCode::SERVICE_SPECIFIC, |
| 116 | format!("Failed to load app config from {}: {}", &config.configPath, e), |
| 117 | ) |
| 118 | })?, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 119 | ), |
| 120 | VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config), |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 121 | }; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 122 | let config = config.as_ref(); |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 123 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 124 | // Assemble disk images if needed. |
| 125 | let disks = config |
| 126 | .disks |
| 127 | .iter() |
| 128 | .map(|disk| { |
| 129 | assemble_disk_image( |
| 130 | disk, |
| 131 | &temporary_directory, |
| 132 | &mut next_temporary_image_id, |
| 133 | &mut indirect_files, |
| 134 | ) |
| 135 | }) |
| 136 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 137 | |
| 138 | // Actually start the VM. |
| 139 | let crosvm_config = CrosvmConfig { |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 140 | cid, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 141 | bootloader: as_asref(&config.bootloader), |
| 142 | kernel: as_asref(&config.kernel), |
| 143 | initrd: as_asref(&config.initrd), |
| 144 | disks, |
| 145 | params: config.params.to_owned(), |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 146 | protected: config.protected_vm, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 147 | }; |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 148 | let composite_disk_fds: Vec<_> = |
| 149 | indirect_files.iter().map(|file| file.as_raw_fd()).collect(); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 150 | let instance = VmInstance::start( |
| 151 | &crosvm_config, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 152 | log_fd, |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 153 | &composite_disk_fds, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 154 | temporary_directory, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 155 | requester_uid, |
| 156 | requester_sid, |
| 157 | requester_debug_pid, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 158 | ) |
| 159 | .map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 160 | error!("Failed to start VM with config {:?}: {}", config, e); |
| 161 | new_binder_exception( |
| 162 | ExceptionCode::SERVICE_SPECIFIC, |
| 163 | format!("Failed to start VM: {}", e), |
| 164 | ) |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 165 | })?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 166 | state.add_vm(Arc::downgrade(&instance)); |
| 167 | Ok(VirtualMachine::create(instance)) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 168 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 169 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 170 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 171 | fn initializeWritablePartition( |
| 172 | &self, |
| 173 | image_fd: &ParcelFileDescriptor, |
| 174 | size: i64, |
| 175 | ) -> binder::Result<()> { |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 176 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 177 | new_binder_exception( |
| 178 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 179 | format!("Invalid size {}: {}", size, e), |
| 180 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 181 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 182 | let image = clone_file(image_fd)?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 183 | |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 184 | QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 185 | new_binder_exception( |
| 186 | ExceptionCode::SERVICE_SPECIFIC, |
| 187 | format!("Failed to create QCOW2 image: {}", e), |
| 188 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 189 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 190 | |
| 191 | Ok(()) |
| 192 | } |
| 193 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 194 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 195 | /// and as such is only permitted from the shell user. |
| 196 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 197 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 198 | |
| 199 | let state = &mut *self.state.lock().unwrap(); |
| 200 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 201 | let cids = vms |
| 202 | .into_iter() |
| 203 | .map(|vm| VirtualMachineDebugInfo { |
| 204 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 205 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 206 | requesterUid: vm.requester_uid as i32, |
| 207 | requesterSid: vm.requester_sid.clone(), |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 208 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 209 | running: vm.running(), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 210 | }) |
| 211 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 212 | Ok(cids) |
| 213 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 214 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 215 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 216 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 217 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 218 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 219 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 220 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 221 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 222 | Ok(()) |
| 223 | } |
| 224 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 225 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 226 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 227 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 228 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 229 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 230 | |
| 231 | let state = &mut *self.state.lock().unwrap(); |
| 232 | Ok(state.debug_drop_vm(cid)) |
| 233 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 234 | } |
| 235 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 236 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 237 | /// |
| 238 | /// This may involve assembling a composite disk from a set of partition images. |
| 239 | fn assemble_disk_image( |
| 240 | disk: &DiskImage, |
| 241 | temporary_directory: &Path, |
| 242 | next_temporary_image_id: &mut u64, |
| 243 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 244 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 245 | let image = if !disk.partitions.is_empty() { |
| 246 | if disk.image.is_some() { |
| 247 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 248 | return Err(new_binder_exception( |
| 249 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 250 | "DiskImage contains both image and partitions.", |
| 251 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 252 | } |
| 253 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 254 | let composite_image_filenames = |
| 255 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 256 | let (image, partition_files) = make_composite_image( |
| 257 | &disk.partitions, |
| 258 | &composite_image_filenames.composite, |
| 259 | &composite_image_filenames.header, |
| 260 | &composite_image_filenames.footer, |
| 261 | ) |
| 262 | .map_err(|e| { |
| 263 | error!("Failed to make composite image with config {:?}: {}", disk, e); |
| 264 | new_binder_exception( |
| 265 | ExceptionCode::SERVICE_SPECIFIC, |
| 266 | format!("Failed to make composite image: {}", e), |
| 267 | ) |
| 268 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 269 | |
| 270 | // Pass the file descriptors for the various partition files to crosvm when it |
| 271 | // is run. |
| 272 | indirect_files.extend(partition_files); |
| 273 | |
| 274 | image |
| 275 | } else if let Some(image) = &disk.image { |
| 276 | clone_file(image)? |
| 277 | } else { |
| 278 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 279 | return Err(new_binder_exception( |
| 280 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 281 | "DiskImage didn't contain image or partitions.", |
| 282 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 283 | }; |
| 284 | |
| 285 | Ok(DiskFile { image, writable: disk.writable }) |
| 286 | } |
| 287 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 288 | fn load_app_config( |
| 289 | config: &VirtualMachineAppConfig, |
| 290 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 291 | ) -> Result<VirtualMachineRawConfig> { |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 292 | let apk_file = config.apk.as_ref().unwrap().as_ref(); |
| 293 | let idsig_file = config.idsig.as_ref().unwrap().as_ref(); |
| 294 | let config_path = &config.configPath; |
| 295 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 296 | let mut apk_zip = ZipArchive::new(apk_file)?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 297 | let config_file = apk_zip.by_name(config_path)?; |
| 298 | let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?; |
| 299 | |
| 300 | let os_name = &vm_payload_config.os.name; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 301 | // For now, the only supported "os" value is "microdroid" |
| 302 | if os_name != "microdroid" { |
| 303 | bail!("unknown os: {}", os_name); |
| 304 | } |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 305 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 306 | let vm_config_file = File::open(vm_config_path)?; |
| 307 | let mut vm_config = VmConfig::load(&vm_config_file)?; |
| 308 | |
Jiyong Park | 2360114 | 2021-07-05 13:15:32 +0900 | [diff] [blame] | 309 | // Microdroid requires additional payload disk image and the bootconfig partition |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 310 | if os_name == "microdroid" { |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 311 | let mut apexes = vm_payload_config.apexes.clone(); |
| 312 | apexes.extend( |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 313 | MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }), |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 314 | ); |
| 315 | apexes.dedup_by(|a, b| a.name == b.name); |
| 316 | |
Jooyung Han | 73bac24 | 2021-07-02 10:25:49 +0900 | [diff] [blame] | 317 | vm_config.disks.push(make_payload_disk( |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 318 | format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(), |
| 319 | format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(), |
| 320 | config_path, |
| 321 | &apexes, |
| 322 | temporary_directory, |
| 323 | )?); |
Jiyong Park | 2360114 | 2021-07-05 13:15:32 +0900 | [diff] [blame] | 324 | |
| 325 | if config.debug { |
| 326 | vm_config.disks[1].partitions.push(Partition { |
| 327 | label: "bootconfig".to_owned(), |
| 328 | paths: vec![PathBuf::from( |
| 329 | "/apex/com.android.virt/etc/microdroid_bootconfig.debug", |
| 330 | )], |
| 331 | writable: false, |
| 332 | }); |
| 333 | } |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 334 | } |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 335 | |
| 336 | vm_config.to_parcelable() |
| 337 | } |
| 338 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 339 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 340 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 341 | temporary_directory: &Path, |
| 342 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 343 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 344 | let id = *next_temporary_image_id; |
| 345 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 346 | CompositeImageFilenames { |
| 347 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 348 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 349 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | /// Filenames for a composite disk image, including header and footer partitions. |
| 354 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 355 | struct CompositeImageFilenames { |
| 356 | /// The composite disk image itself. |
| 357 | composite: PathBuf, |
| 358 | /// The header partition image. |
| 359 | header: PathBuf, |
| 360 | /// The footer partition image. |
| 361 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 362 | } |
| 363 | |
| 364 | /// Gets the calling SID of the current Binder thread. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 365 | fn get_calling_sid() -> Result<String, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 366 | ThreadState::with_calling_sid(|sid| { |
| 367 | if let Some(sid) = sid { |
| 368 | match sid.to_str() { |
| 369 | Ok(sid) => Ok(sid.to_owned()), |
| 370 | Err(e) => { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 371 | error!("SID was not valid UTF-8: {}", e); |
| 372 | Err(new_binder_exception( |
| 373 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 374 | format!("SID was not valid UTF-8: {}", e), |
| 375 | )) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 376 | } |
| 377 | } |
| 378 | } else { |
| 379 | error!("Missing SID on startVm"); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 380 | Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm")) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 381 | } |
| 382 | }) |
| 383 | } |
| 384 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 385 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 386 | fn check_debug_access() -> binder::Result<()> { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 387 | let uid = ThreadState::get_calling_uid(); |
| 388 | log::trace!("Debug method call from UID {}.", uid); |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 389 | if DEBUG_ALLOWED_UIDS.contains(&uid) { |
| 390 | Ok(()) |
| 391 | } else { |
| 392 | Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied")) |
| 393 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 394 | } |
| 395 | |
| 396 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 397 | #[derive(Debug)] |
| 398 | struct VirtualMachine { |
| 399 | instance: Arc<VmInstance>, |
| 400 | } |
| 401 | |
| 402 | impl VirtualMachine { |
| 403 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
| 404 | let binder = VirtualMachine { instance }; |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 405 | BnVirtualMachine::new_binder(binder, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 406 | } |
| 407 | } |
| 408 | |
| 409 | impl Interface for VirtualMachine {} |
| 410 | |
| 411 | impl IVirtualMachine for VirtualMachine { |
| 412 | fn getCid(&self) -> binder::Result<i32> { |
| 413 | Ok(self.instance.cid as i32) |
| 414 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 415 | |
| 416 | fn isRunning(&self) -> binder::Result<bool> { |
| 417 | Ok(self.instance.running()) |
| 418 | } |
| 419 | |
| 420 | fn registerCallback( |
| 421 | &self, |
| 422 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 423 | ) -> binder::Result<()> { |
| 424 | // TODO: Should this give an error if the VM is already dead? |
| 425 | self.instance.callbacks.add(callback.clone()); |
| 426 | Ok(()) |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | impl Drop for VirtualMachine { |
| 431 | fn drop(&mut self) { |
| 432 | debug!("Dropping {:?}", self); |
| 433 | self.instance.kill(); |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 438 | /// dies. |
| 439 | #[derive(Debug, Default)] |
| 440 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 441 | |
| 442 | impl VirtualMachineCallbacks { |
| 443 | /// Call all registered callbacks to say that the VM has died. |
| 444 | pub fn callback_on_died(&self, cid: Cid) { |
| 445 | let callbacks = &*self.0.lock().unwrap(); |
| 446 | for callback in callbacks { |
| 447 | if let Err(e) = callback.onDied(cid as i32) { |
| 448 | error!("Error calling callback: {}", e); |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /// Add a new callback to the set. |
| 454 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 455 | self.0.lock().unwrap().push(callback); |
| 456 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 457 | } |
| 458 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 459 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 460 | /// struct. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 461 | #[derive(Debug)] |
| 462 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 463 | /// The next available unused CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 464 | next_cid: Cid, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 465 | |
| 466 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 467 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 468 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 469 | /// from the list opportunistically the next time `add_vm` is called. |
| 470 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 471 | |
| 472 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 473 | /// This is only used for debugging purposes. |
| 474 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 475 | } |
| 476 | |
| 477 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 478 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 479 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 480 | // Attempt to upgrade the weak pointers to strong pointers. |
| 481 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 482 | } |
| 483 | |
| 484 | /// Add a new VM to the list. |
| 485 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 486 | // Garbage collect any entries from the stored list which no longer exist. |
| 487 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 488 | |
| 489 | // Actually add the new VM. |
| 490 | self.vms.push(vm); |
| 491 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 492 | |
| 493 | /// Store a strong VM reference. |
| 494 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 495 | self.debug_held_vms.push(vm); |
| 496 | } |
| 497 | |
| 498 | /// Retrieve and remove a strong VM reference. |
| 499 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 500 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
| 501 | Some(self.debug_held_vms.swap_remove(pos)) |
| 502 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 503 | |
| 504 | /// Get the next available CID, or an error if we have run out. |
| 505 | fn allocate_cid(&mut self) -> binder::Result<Cid> { |
| 506 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 507 | let cid = self.next_cid; |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 508 | 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] | 509 | Ok(cid) |
| 510 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 511 | } |
| 512 | |
| 513 | impl Default for State { |
| 514 | fn default() -> Self { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 515 | State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 516 | } |
| 517 | } |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 518 | |
| 519 | /// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`. |
| 520 | fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> { |
| 521 | option.as_ref().map(|t| t.as_ref()) |
| 522 | } |
| 523 | |
| 524 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 525 | fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
| 526 | file.as_ref().try_clone().map_err(|e| { |
| 527 | new_binder_exception( |
| 528 | ExceptionCode::BAD_PARCELABLE, |
| 529 | format!("Failed to clone File from ParcelFileDescriptor: {}", e), |
| 530 | ) |
| 531 | }) |
| 532 | } |
| 533 | |
| 534 | /// Constructs a new Binder error `Status` with the given `ExceptionCode` and message. |
| 535 | fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status { |
| 536 | Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref()) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 537 | } |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 538 | |
| 539 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 540 | /// it doesn't require that T implements Clone. |
| 541 | enum BorrowedOrOwned<'a, T> { |
| 542 | Borrowed(&'a T), |
| 543 | Owned(T), |
| 544 | } |
| 545 | |
| 546 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 547 | fn as_ref(&self) -> &T { |
| 548 | match self { |
| 549 | Self::Borrowed(b) => b, |
| 550 | Self::Owned(o) => &o, |
| 551 | } |
| 552 | } |
| 553 | } |