Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // Copyright 2021, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 15 | //! Implementation of the AIDL interface of the VirtualizationService. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 16 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 17 | use crate::composite::make_composite_image; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 18 | use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 19 | use crate::payload::add_microdroid_images; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 20 | use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID}; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 21 | use crate::selinux::{SeContext, getfilecon}; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 22 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 23 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 24 | DeathReason::DeathReason, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 25 | DiskImage::DiskImage, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 26 | IVirtualMachine::{BnVirtualMachine, IVirtualMachine}, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 27 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 28 | IVirtualizationService::IVirtualizationService, |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 29 | Partition::Partition, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 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 | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 38 | self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, SpIBinder, Status, |
| 39 | StatusCode, Strong, ThreadState, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 40 | }; |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 41 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{ |
| 42 | IVirtualMachineService::{ |
| 43 | BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT, |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 44 | VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 45 | }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 46 | }; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 47 | use anyhow::{anyhow, bail, Context, Result}; |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 48 | use binder_common::{lazy_service::LazyServiceGuard, rpc_server::run_rpc_server_with_factory}; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 49 | use disk::QcowFile; |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 50 | use idsig::{HashAlgorithm, V4Signature}; |
Andrew Walbran | f6d600f | 2022-02-03 14:42:39 +0000 | [diff] [blame] | 51 | use log::{debug, error, info, warn, trace}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 52 | use microdroid_payload_config::VmPayloadConfig; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 53 | use rustutils::system_properties; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 54 | use semver::VersionReq; |
Treehugger Robot | 3ffa832 | 2021-11-22 12:06:47 +0000 | [diff] [blame] | 55 | use statslog_virtualization_rust::vm_creation_requested::{stats_write, Hypervisor}; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 56 | use std::convert::TryInto; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 57 | use std::ffi::CStr; |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 58 | use std::fs::{create_dir, File, OpenOptions}; |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 59 | use std::io::{Error, ErrorKind, Write, Read}; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 60 | use std::num::NonZeroU32; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 61 | use std::os::unix::io::{FromRawFd, IntoRawFd}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 62 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 63 | use std::sync::{Arc, Mutex, Weak}; |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 64 | use tombstoned_client::{TombstonedConnection, DebuggerdDumpType}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 65 | use vmconfig::VmConfig; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 66 | use vsock::{SockAddr, VsockListener, VsockStream}; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 67 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 68 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 69 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 70 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 71 | /// Directory in which to write disk image files used while running VMs. |
Andrew Walbran | 488bd07 | 2021-07-14 13:29:51 +0000 | [diff] [blame] | 72 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 73 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 74 | /// The CID representing the host VM |
| 75 | const VMADDR_CID_HOST: u32 = 2; |
| 76 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 77 | /// The size of zero.img. |
| 78 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 79 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 80 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 81 | /// Magic string for the instance image |
| 82 | const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance"; |
| 83 | |
| 84 | /// Version of the instance image format |
| 85 | const ANDROID_VM_INSTANCE_VERSION: u16 = 1; |
| 86 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 87 | const CHUNK_RECV_MAX_LEN: usize = 1024; |
| 88 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 89 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame] | 90 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 91 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 92 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 93 | } |
| 94 | |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 95 | impl Interface for VirtualizationService { |
| 96 | fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> { |
| 97 | check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?; |
| 98 | let state = &mut *self.state.lock().unwrap(); |
| 99 | let vms = state.vms(); |
| 100 | writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 101 | for vm in vms { |
| 102 | writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 103 | writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap()) |
| 104 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 105 | writeln!(file, "\tPayload state {:?}", vm.payload_state()) |
| 106 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 107 | writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 108 | writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy()) |
| 109 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 110 | writeln!(file, "\trequester_uid: {}", vm.requester_uid) |
| 111 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 112 | writeln!(file, "\trequester_sid: {}", vm.requester_sid) |
| 113 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 114 | writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid) |
| 115 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 116 | } |
| 117 | Ok(()) |
| 118 | } |
| 119 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 120 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 121 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 122 | /// Creates (but does not start) a new VM with the given configuration, assigning it the next |
| 123 | /// available CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 124 | /// |
| 125 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 126 | fn createVm( |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 127 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 128 | config: &VirtualMachineConfig, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 129 | console_fd: Option<&ParcelFileDescriptor>, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 130 | log_fd: Option<&ParcelFileDescriptor>, |
| 131 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 132 | let mut is_protected = false; |
| 133 | let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected); |
| 134 | match ret { |
| 135 | Ok(_) => { |
| 136 | let ok_status = Status::ok(); |
| 137 | write_vm_creation_stats( |
| 138 | is_protected, |
| 139 | /*creation_succeeded*/ true, |
| 140 | ok_status.exception_code() as i32, |
| 141 | ); |
| 142 | } |
| 143 | Err(ref e) => { |
| 144 | write_vm_creation_stats( |
| 145 | is_protected, |
| 146 | /*creation_succeeded*/ false, |
| 147 | e.exception_code() as i32, |
| 148 | ); |
| 149 | } |
| 150 | } |
| 151 | ret |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 152 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 153 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 154 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 155 | fn initializeWritablePartition( |
| 156 | &self, |
| 157 | image_fd: &ParcelFileDescriptor, |
| 158 | size: i64, |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 159 | partition_type: PartitionType, |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 160 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 161 | check_manage_access()?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 162 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 163 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 164 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 165 | Some(format!("Invalid size {}: {}", size, e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 166 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 167 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 168 | let image = clone_file(image_fd)?; |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 169 | // initialize the file. Any data in the file will be erased. |
| 170 | image.set_len(0).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 171 | Status::new_service_specific_error_str( |
| 172 | -1, |
| 173 | Some(format!("Failed to reset a file: {}", e)), |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 174 | ) |
| 175 | })?; |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 176 | let mut part = QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 177 | Status::new_service_specific_error_str( |
| 178 | -1, |
| 179 | Some(format!("Failed to create QCOW2 image: {}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 180 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 181 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 182 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 183 | match partition_type { |
| 184 | PartitionType::RAW => Ok(()), |
| 185 | PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part), |
| 186 | _ => Err(Error::new( |
| 187 | ErrorKind::Unsupported, |
| 188 | format!("Unsupported partition type {:?}", partition_type), |
| 189 | )), |
| 190 | } |
| 191 | .map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 192 | Status::new_service_specific_error_str( |
| 193 | -1, |
| 194 | Some(format!("Failed to initialize partition as {:?}: {}", partition_type, e)), |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 195 | ) |
| 196 | })?; |
| 197 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 198 | Ok(()) |
| 199 | } |
| 200 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 201 | /// Creates or update the idsig file by digesting the input APK file. |
| 202 | fn createOrUpdateIdsigFile( |
| 203 | &self, |
| 204 | input_fd: &ParcelFileDescriptor, |
| 205 | idsig_fd: &ParcelFileDescriptor, |
| 206 | ) -> binder::Result<()> { |
| 207 | // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in |
| 208 | // idsig_fd is different from APK digest in input_fd |
| 209 | |
Jiyong Park | c3ca24f | 2022-06-28 10:45:15 +0900 | [diff] [blame] | 210 | check_manage_access()?; |
| 211 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 212 | let mut input = clone_file(input_fd)?; |
| 213 | let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap(); |
| 214 | |
| 215 | let mut output = clone_file(idsig_fd)?; |
| 216 | output.set_len(0).unwrap(); |
| 217 | sig.write_into(&mut output).unwrap(); |
| 218 | Ok(()) |
| 219 | } |
| 220 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 221 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 222 | /// and as such is only permitted from the shell user. |
| 223 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 224 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 225 | |
| 226 | let state = &mut *self.state.lock().unwrap(); |
| 227 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 228 | let cids = vms |
| 229 | .into_iter() |
| 230 | .map(|vm| VirtualMachineDebugInfo { |
| 231 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 232 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 233 | requesterUid: vm.requester_uid as i32, |
| 234 | requesterSid: vm.requester_sid.clone(), |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 235 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 236 | state: get_state(&vm), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 237 | }) |
| 238 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 239 | Ok(cids) |
| 240 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 241 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 242 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 243 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 244 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 245 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 246 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 247 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 248 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 249 | Ok(()) |
| 250 | } |
| 251 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 252 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 253 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 254 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 255 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 256 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 257 | |
| 258 | let state = &mut *self.state.lock().unwrap(); |
| 259 | Ok(state.debug_drop_vm(cid)) |
| 260 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 261 | } |
| 262 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 263 | fn handle_stream_connection_tombstoned() -> Result<()> { |
| 264 | let listener = |
| 265 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?; |
| 266 | info!("Listening to tombstones from guests ..."); |
| 267 | for incoming_stream in listener.incoming() { |
| 268 | let mut incoming_stream = match incoming_stream { |
| 269 | Err(e) => { |
| 270 | warn!("invalid incoming connection: {}", e); |
| 271 | continue; |
| 272 | } |
| 273 | Ok(s) => s, |
| 274 | }; |
| 275 | std::thread::spawn(move || { |
| 276 | if let Err(e) = handle_tombstone(&mut incoming_stream) { |
| 277 | error!("Failed to write tombstone- {:?}", e); |
| 278 | } |
| 279 | }); |
| 280 | } |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | fn handle_tombstone(stream: &mut VsockStream) -> Result<()> { |
| 285 | if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() { |
| 286 | info!("Vsock Stream connected to cid={} for tombstones", addr.cid()); |
| 287 | } |
| 288 | let tb_connection = |
| 289 | TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone) |
| 290 | .context("Failed to connect to tombstoned")?; |
| 291 | let mut text_output = tb_connection |
| 292 | .text_output |
| 293 | .as_ref() |
| 294 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 295 | let mut num_bytes_read = 0; |
| 296 | loop { |
| 297 | let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN]; |
| 298 | let n = stream |
| 299 | .read(&mut chunk_recv) |
| 300 | .context("Failed to read tombstone data from Vsock stream")?; |
| 301 | if n == 0 { |
| 302 | break; |
| 303 | } |
| 304 | num_bytes_read += n; |
| 305 | text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?; |
| 306 | } |
| 307 | info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read); |
| 308 | tb_connection.notify_completion()?; |
| 309 | Ok(()) |
| 310 | } |
| 311 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 312 | impl VirtualizationService { |
| 313 | pub fn init() -> VirtualizationService { |
| 314 | let service = VirtualizationService::default(); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 315 | |
| 316 | // server for payload output |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 317 | let state = service.state.clone(); // reference to state (not the state itself) is copied |
| 318 | std::thread::spawn(move || { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 319 | handle_stream_connection_from_vm(state).unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 320 | }); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 321 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 322 | std::thread::spawn(|| { |
| 323 | if let Err(e) = handle_stream_connection_tombstoned() { |
| 324 | warn!("Error receiving tombstone from guest or writing them. Error: {}", e); |
| 325 | } |
| 326 | }); |
| 327 | |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 328 | // binder server for vm |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 329 | // reference to state (not the state itself) is copied |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 330 | let state = service.state.clone(); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 331 | std::thread::spawn(move || { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 332 | debug!("VirtualMachineService is starting as an RPC service."); |
| 333 | if run_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| { |
| 334 | VirtualMachineService::factory(cid, &state) |
| 335 | }) { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 336 | debug!("RPC server has shut down gracefully"); |
| 337 | } else { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 338 | panic!("Premature termination of RPC server"); |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 339 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 340 | }); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 341 | service |
| 342 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 343 | |
| 344 | fn create_vm_internal( |
| 345 | &self, |
| 346 | config: &VirtualMachineConfig, |
| 347 | console_fd: Option<&ParcelFileDescriptor>, |
| 348 | log_fd: Option<&ParcelFileDescriptor>, |
| 349 | is_protected: &mut bool, |
| 350 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
| 351 | check_manage_access()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 352 | |
| 353 | if let VirtualMachineConfig::RawConfig(config) = config { |
| 354 | if config.protectedVm { |
| 355 | check_use_custom_virtual_machine()?; |
| 356 | } |
| 357 | } |
| 358 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 359 | let state = &mut *self.state.lock().unwrap(); |
| 360 | let console_fd = console_fd.map(clone_file).transpose()?; |
| 361 | let log_fd = log_fd.map(clone_file).transpose()?; |
| 362 | let requester_uid = ThreadState::get_calling_uid(); |
| 363 | let requester_sid = get_calling_sid()?; |
| 364 | let requester_debug_pid = ThreadState::get_calling_pid(); |
| 365 | let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?; |
| 366 | |
| 367 | // Counter to generate unique IDs for temporary image files. |
| 368 | let mut next_temporary_image_id = 0; |
| 369 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 370 | // child process, and not closed before it is started. |
| 371 | let mut indirect_files = vec![]; |
| 372 | |
| 373 | // Make directory for temporary files. |
| 374 | let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 375 | create_dir(&temporary_directory).map_err(|e| { |
| 376 | // At this point, we do not know the protected status of Vm |
| 377 | // setting it to false, though this may not be correct. |
| 378 | error!( |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 379 | "Failed to create temporary directory {:?} for VM files: {:?}", |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 380 | temporary_directory, e |
| 381 | ); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 382 | Status::new_service_specific_error_str( |
| 383 | -1, |
| 384 | Some(format!( |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 385 | "Failed to create temporary directory {:?} for VM files: {}", |
| 386 | temporary_directory, e |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 387 | )), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 388 | ) |
| 389 | })?; |
| 390 | |
| 391 | let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_)); |
| 392 | |
| 393 | let config = match config { |
| 394 | VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned( |
| 395 | load_app_config(config, &temporary_directory).map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 396 | error!("Failed to load app config from {}: {:?}", &config.configPath, e); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 397 | *is_protected = config.protectedVm; |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 398 | Status::new_service_specific_error_str( |
| 399 | -1, |
| 400 | Some(format!( |
| 401 | "Failed to load app config from {}: {}", |
| 402 | &config.configPath, e |
| 403 | )), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 404 | ) |
| 405 | })?, |
| 406 | ), |
| 407 | VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config), |
| 408 | }; |
| 409 | let config = config.as_ref(); |
| 410 | *is_protected = config.protectedVm; |
| 411 | |
| 412 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 413 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from |
| 414 | // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed |
| 415 | // to be labeled as app_data_file. For images in the app config, nothing but the instance |
| 416 | // partition is allowed to be labeled as such. |
| 417 | config |
| 418 | .disks |
| 419 | .iter() |
| 420 | .flat_map(|disk| disk.partitions.iter()) |
| 421 | .filter(|partition| { |
| 422 | if is_app_config { |
| 423 | partition.label != "vm-instance" |
| 424 | } else { |
| 425 | true // all partitions are checked |
| 426 | } |
| 427 | }) |
| 428 | .try_for_each(check_label_for_partition) |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 429 | .map_err(|e| Status::new_service_specific_error_str(-1, Some(e.to_string())))?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 430 | |
| 431 | let zero_filler_path = temporary_directory.join("zero.img"); |
| 432 | write_zero_filler(&zero_filler_path).map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 433 | error!("Failed to make composite image: {:?}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 434 | Status::new_service_specific_error_str( |
| 435 | -1, |
| 436 | Some(format!("Failed to make composite image: {}", e)), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 437 | ) |
| 438 | })?; |
| 439 | |
| 440 | // Assemble disk images if needed. |
| 441 | let disks = config |
| 442 | .disks |
| 443 | .iter() |
| 444 | .map(|disk| { |
| 445 | assemble_disk_image( |
| 446 | disk, |
| 447 | &zero_filler_path, |
| 448 | &temporary_directory, |
| 449 | &mut next_temporary_image_id, |
| 450 | &mut indirect_files, |
| 451 | ) |
| 452 | }) |
| 453 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 454 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 455 | // Creating this ramdump file unconditionally is not harmful as ramdump will be created |
| 456 | // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 457 | // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read` |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 458 | // will be sent back to the client (i.e. the VM owner) for readout. |
| 459 | let ramdump_path = temporary_directory.join("ramdump"); |
| 460 | let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| { |
| 461 | error!("Failed to prepare ramdump file: {}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 462 | Status::new_service_specific_error_str( |
| 463 | -1, |
| 464 | Some(format!("Failed to prepare ramdump file: {}", e)), |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 465 | ) |
| 466 | })?; |
| 467 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 468 | // Actually start the VM. |
| 469 | let crosvm_config = CrosvmConfig { |
| 470 | cid, |
| 471 | bootloader: maybe_clone_file(&config.bootloader)?, |
| 472 | kernel: maybe_clone_file(&config.kernel)?, |
| 473 | initrd: maybe_clone_file(&config.initrd)?, |
| 474 | disks, |
| 475 | params: config.params.to_owned(), |
| 476 | protected: *is_protected, |
| 477 | memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new), |
| 478 | cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new), |
| 479 | cpu_affinity: config.cpuAffinity.clone(), |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 480 | task_profiles: config.taskProfiles.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 481 | console_fd, |
| 482 | log_fd, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 483 | ramdump: Some(ramdump), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 484 | indirect_files, |
| 485 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 486 | detect_hangup: is_app_config, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 487 | }; |
| 488 | let instance = Arc::new( |
| 489 | VmInstance::new( |
| 490 | crosvm_config, |
| 491 | temporary_directory, |
| 492 | requester_uid, |
| 493 | requester_sid, |
| 494 | requester_debug_pid, |
| 495 | ) |
| 496 | .map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 497 | error!("Failed to create VM with config {:?}: {:?}", config, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 498 | Status::new_service_specific_error_str( |
| 499 | -1, |
| 500 | Some(format!("Failed to create VM: {}", e)), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 501 | ) |
| 502 | })?, |
| 503 | ); |
| 504 | state.add_vm(Arc::downgrade(&instance)); |
| 505 | Ok(VirtualMachine::create(instance)) |
| 506 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 507 | } |
| 508 | |
Treehugger Robot | 3ffa832 | 2021-11-22 12:06:47 +0000 | [diff] [blame] | 509 | /// Write the stats of VMCreation to statsd |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 510 | fn write_vm_creation_stats(is_protected: bool, creation_succeeded: bool, exception_code: i32) { |
| 511 | match stats_write(Hypervisor::Pkvm, is_protected, creation_succeeded, exception_code) { |
Treehugger Robot | 3ffa832 | 2021-11-22 12:06:47 +0000 | [diff] [blame] | 512 | Err(e) => { |
Andrew Walbran | f6d600f | 2022-02-03 14:42:39 +0000 | [diff] [blame] | 513 | warn!("statslog_rust failed with error: {}", e); |
Treehugger Robot | 3ffa832 | 2021-11-22 12:06:47 +0000 | [diff] [blame] | 514 | } |
Andrew Walbran | f6d600f | 2022-02-03 14:42:39 +0000 | [diff] [blame] | 515 | Ok(_) => trace!("statslog_rust succeeded for virtualization service"), |
Treehugger Robot | 3ffa832 | 2021-11-22 12:06:47 +0000 | [diff] [blame] | 516 | } |
| 517 | } |
| 518 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 519 | /// Waits for incoming connections from VM. If a new connection is made, stores the stream in the |
| 520 | /// corresponding `VmInstance`. |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 521 | fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> { |
Inseob Kim | d058756 | 2021-09-01 21:27:32 +0900 | [diff] [blame] | 522 | let listener = |
| 523 | 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] | 524 | for stream in listener.incoming() { |
| 525 | let stream = match stream { |
| 526 | Err(e) => { |
| 527 | warn!("invalid incoming connection: {}", e); |
| 528 | continue; |
| 529 | } |
| 530 | Ok(s) => s, |
| 531 | }; |
| 532 | if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() { |
| 533 | let cid = addr.cid(); |
| 534 | let port = addr.port(); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 535 | info!("payload stream connected from cid={}, port={}", cid, port); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 536 | if let Some(vm) = state.lock().unwrap().get_vm(cid) { |
Chris Wailes | 8bbb893 | 2021-09-10 14:14:19 -0700 | [diff] [blame] | 537 | *vm.stream.lock().unwrap() = Some(stream); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 538 | } else { |
| 539 | error!("connection from cid={} is not from a guest VM", cid); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 540 | } |
| 541 | } |
| 542 | } |
| 543 | Ok(()) |
| 544 | } |
| 545 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 546 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 547 | let file = OpenOptions::new() |
| 548 | .create_new(true) |
| 549 | .read(true) |
| 550 | .write(true) |
| 551 | .open(zero_filler_path) |
| 552 | .with_context(|| "Failed to create zero.img")?; |
| 553 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 554 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 555 | } |
| 556 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 557 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 558 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 559 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 560 | part.flush() |
| 561 | } |
| 562 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 563 | fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> { |
| 564 | File::create(&ramdump_path) |
| 565 | .context(format!("Failed to create ramdump file {:?}", &ramdump_path)) |
| 566 | } |
| 567 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 568 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 569 | /// |
| 570 | /// This may involve assembling a composite disk from a set of partition images. |
| 571 | fn assemble_disk_image( |
| 572 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 573 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 574 | temporary_directory: &Path, |
| 575 | next_temporary_image_id: &mut u64, |
| 576 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 577 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 578 | let image = if !disk.partitions.is_empty() { |
| 579 | if disk.image.is_some() { |
| 580 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 581 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 582 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 583 | Some("DiskImage contains both image and partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 584 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 585 | } |
| 586 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 587 | let composite_image_filenames = |
| 588 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 589 | let (image, partition_files) = make_composite_image( |
| 590 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 591 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 592 | &composite_image_filenames.composite, |
| 593 | &composite_image_filenames.header, |
| 594 | &composite_image_filenames.footer, |
| 595 | ) |
| 596 | .map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 597 | error!("Failed to make composite image with config {:?}: {:?}", disk, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 598 | Status::new_service_specific_error_str( |
| 599 | -1, |
| 600 | Some(format!("Failed to make composite image: {}", e)), |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 601 | ) |
| 602 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 603 | |
| 604 | // Pass the file descriptors for the various partition files to crosvm when it |
| 605 | // is run. |
| 606 | indirect_files.extend(partition_files); |
| 607 | |
| 608 | image |
| 609 | } else if let Some(image) = &disk.image { |
| 610 | clone_file(image)? |
| 611 | } else { |
| 612 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 613 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 614 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 615 | Some("DiskImage didn't contain image or partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 616 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 617 | }; |
| 618 | |
| 619 | Ok(DiskFile { image, writable: disk.writable }) |
| 620 | } |
| 621 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 622 | fn load_app_config( |
| 623 | config: &VirtualMachineAppConfig, |
| 624 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 625 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 626 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 627 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 628 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 629 | let config_path = &config.configPath; |
| 630 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 631 | let mut apk_zip = ZipArchive::new(&apk_file)?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 632 | let config_file = apk_zip.by_name(config_path)?; |
| 633 | let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?; |
| 634 | |
| 635 | let os_name = &vm_payload_config.os.name; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 636 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 637 | // For now, the only supported "os" value is "microdroid" |
| 638 | if os_name != "microdroid" { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 639 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 640 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 641 | |
| 642 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 643 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 644 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 645 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 646 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 647 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 648 | if config.memoryMib > 0 { |
| 649 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 650 | } |
| 651 | |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 652 | vm_config.protectedVm = config.protectedVm; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 653 | vm_config.numCpus = config.numCpus; |
| 654 | vm_config.cpuAffinity = config.cpuAffinity.clone(); |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 655 | vm_config.taskProfiles = config.taskProfiles.clone(); |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 656 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 657 | // Microdroid requires an additional payload disk image and the bootconfig partition. |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 658 | if os_name == "microdroid" { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 659 | add_microdroid_images( |
| 660 | config, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 661 | temporary_directory, |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 662 | apk_file, |
| 663 | idsig_file, |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 664 | instance_file, |
Jooyung Han | 5dc4217 | 2021-10-05 16:43:47 +0900 | [diff] [blame] | 665 | &vm_payload_config, |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 666 | &mut vm_config, |
| 667 | )?; |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 668 | } |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 669 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 670 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 671 | } |
| 672 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 673 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 674 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 675 | temporary_directory: &Path, |
| 676 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 677 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 678 | let id = *next_temporary_image_id; |
| 679 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 680 | CompositeImageFilenames { |
| 681 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 682 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 683 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | /// Filenames for a composite disk image, including header and footer partitions. |
| 688 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 689 | struct CompositeImageFilenames { |
| 690 | /// The composite disk image itself. |
| 691 | composite: PathBuf, |
| 692 | /// The header partition image. |
| 693 | header: PathBuf, |
| 694 | /// The footer partition image. |
| 695 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 696 | } |
| 697 | |
| 698 | /// Gets the calling SID of the current Binder thread. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 699 | fn get_calling_sid() -> Result<String, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 700 | ThreadState::with_calling_sid(|sid| { |
| 701 | if let Some(sid) = sid { |
| 702 | match sid.to_str() { |
| 703 | Ok(sid) => Ok(sid.to_owned()), |
| 704 | Err(e) => { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 705 | error!("SID was not valid UTF-8: {}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 706 | Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 707 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 708 | Some(format!("SID was not valid UTF-8: {}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 709 | )) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 710 | } |
| 711 | } |
| 712 | } else { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 713 | error!("Missing SID on createVm"); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 714 | Err(Status::new_exception_str(ExceptionCode::SECURITY, Some("Missing SID on createVm"))) |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 715 | } |
| 716 | }) |
| 717 | } |
| 718 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 719 | /// Checks whether the caller has a specific permission |
| 720 | fn check_permission(perm: &str) -> binder::Result<()> { |
| 721 | let calling_pid = ThreadState::get_calling_pid(); |
| 722 | let calling_uid = ThreadState::get_calling_uid(); |
| 723 | // Root can do anything |
| 724 | if calling_uid == 0 { |
| 725 | return Ok(()); |
| 726 | } |
| 727 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 728 | binder::get_interface("permission")?; |
| 729 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 730 | Ok(()) |
| 731 | } else { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 732 | Err(Status::new_exception_str( |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 733 | ExceptionCode::SECURITY, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 734 | Some(format!("does not have the {} permission", perm)), |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 735 | )) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 736 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 737 | } |
| 738 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 739 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 740 | fn check_debug_access() -> binder::Result<()> { |
| 741 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 742 | } |
| 743 | |
| 744 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 745 | fn check_manage_access() -> binder::Result<()> { |
| 746 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 747 | } |
| 748 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 749 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 750 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 751 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 752 | } |
| 753 | |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 754 | /// Check if a partition has selinux labels that are not allowed |
| 755 | fn check_label_for_partition(partition: &Partition) -> Result<()> { |
| 756 | let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?; |
| 757 | if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() { |
| 758 | Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx)) |
| 759 | } else { |
| 760 | Ok(()) |
| 761 | } |
| 762 | } |
| 763 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 764 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 765 | #[derive(Debug)] |
| 766 | struct VirtualMachine { |
| 767 | instance: Arc<VmInstance>, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 768 | /// Keeps our service process running as long as this VM instance exists. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 769 | #[allow(dead_code)] |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 770 | lazy_service_guard: LazyServiceGuard, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 771 | } |
| 772 | |
| 773 | impl VirtualMachine { |
| 774 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 775 | let binder = VirtualMachine { instance, lazy_service_guard: Default::default() }; |
Andrew Walbran | 4de2878 | 2021-04-13 14:51:43 +0000 | [diff] [blame] | 776 | BnVirtualMachine::new_binder(binder, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 777 | } |
| 778 | } |
| 779 | |
| 780 | impl Interface for VirtualMachine {} |
| 781 | |
| 782 | impl IVirtualMachine for VirtualMachine { |
| 783 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 784 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 785 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 786 | Ok(self.instance.cid as i32) |
| 787 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 788 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 789 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 790 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 791 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 792 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 793 | } |
| 794 | |
| 795 | fn registerCallback( |
| 796 | &self, |
| 797 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 798 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 799 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 800 | // others. |
| 801 | // |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 802 | // TODO: Should this give an error if the VM is already dead? |
| 803 | self.instance.callbacks.add(callback.clone()); |
| 804 | Ok(()) |
| 805 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 806 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 807 | fn start(&self) -> binder::Result<()> { |
| 808 | self.instance.start().map_err(|e| { |
| 809 | error!("Error starting VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 810 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 811 | }) |
| 812 | } |
| 813 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 814 | fn stop(&self) -> binder::Result<()> { |
| 815 | self.instance.kill().map_err(|e| { |
| 816 | error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 817 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 818 | }) |
| 819 | } |
| 820 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 821 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 822 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 823 | return Err(Status::new_service_specific_error_str(-1, Some("VM is not running"))); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 824 | } |
| 825 | let stream = |
| 826 | VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 827 | Status::new_service_specific_error_str( |
| 828 | -1, |
| 829 | Some(format!("Failed to connect: {}", e)), |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 830 | ) |
| 831 | })?; |
| 832 | Ok(vsock_stream_to_pfd(stream)) |
| 833 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 834 | } |
| 835 | |
| 836 | impl Drop for VirtualMachine { |
| 837 | fn drop(&mut self) { |
| 838 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 839 | if let Err(e) = self.instance.kill() { |
| 840 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 841 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 842 | } |
| 843 | } |
| 844 | |
| 845 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 846 | /// dies. |
| 847 | #[derive(Debug, Default)] |
| 848 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 849 | |
| 850 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 851 | /// Call all registered callbacks to notify that the payload has started. |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 852 | pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 853 | let callbacks = &*self.0.lock().unwrap(); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 854 | let pfd = stream.map(vsock_stream_to_pfd); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 855 | for callback in callbacks { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 856 | if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 857 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 858 | } |
| 859 | } |
| 860 | } |
| 861 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 862 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 863 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 864 | let callbacks = &*self.0.lock().unwrap(); |
| 865 | for callback in callbacks { |
| 866 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 867 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 868 | } |
| 869 | } |
| 870 | } |
| 871 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 872 | /// Call all registered callbacks to notify that the payload has finished. |
| 873 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 874 | let callbacks = &*self.0.lock().unwrap(); |
| 875 | for callback in callbacks { |
| 876 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 877 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 878 | } |
| 879 | } |
| 880 | } |
| 881 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 882 | /// Call all registered callbacks to say that the VM encountered an error. |
| 883 | pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) { |
| 884 | let callbacks = &*self.0.lock().unwrap(); |
| 885 | for callback in callbacks { |
| 886 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 887 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 888 | } |
| 889 | } |
| 890 | } |
| 891 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 892 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 893 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 894 | let callbacks = &*self.0.lock().unwrap(); |
| 895 | for callback in callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 896 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 897 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 898 | } |
| 899 | } |
| 900 | } |
| 901 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 902 | /// Call all registered callbacks to say that there was a ramdump to download. |
| 903 | pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) { |
| 904 | let callbacks = &*self.0.lock().unwrap(); |
| 905 | let pfd = ParcelFileDescriptor::new(ramdump); |
| 906 | for callback in callbacks { |
| 907 | if let Err(e) = callback.onRamdump(cid as i32, &pfd) { |
| 908 | error!("Error notifying ramdump of VM CID {}: {}", cid, e); |
| 909 | } |
| 910 | } |
| 911 | } |
| 912 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 913 | /// Add a new callback to the set. |
| 914 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 915 | self.0.lock().unwrap().push(callback); |
| 916 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 917 | } |
| 918 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 919 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 920 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 921 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 922 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 923 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 924 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 925 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 926 | /// from the list opportunistically the next time `add_vm` is called. |
| 927 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 928 | |
| 929 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 930 | /// This is only used for debugging purposes. |
| 931 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 932 | } |
| 933 | |
| 934 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 935 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 936 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 937 | // Attempt to upgrade the weak pointers to strong pointers. |
| 938 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 939 | } |
| 940 | |
| 941 | /// Add a new VM to the list. |
| 942 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 943 | // Garbage collect any entries from the stored list which no longer exist. |
| 944 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 945 | |
| 946 | // Actually add the new VM. |
| 947 | self.vms.push(vm); |
| 948 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 949 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 950 | /// Get a VM that corresponds to the given cid |
| 951 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 952 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 953 | } |
| 954 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 955 | /// Store a strong VM reference. |
| 956 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 957 | self.debug_held_vms.push(vm); |
| 958 | } |
| 959 | |
| 960 | /// Retrieve and remove a strong VM reference. |
| 961 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 962 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 963 | let vm = self.debug_held_vms.swap_remove(pos); |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 964 | Some(vm) |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 965 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 966 | } |
| 967 | |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 968 | /// Get the next available CID, or an error if we have run out. The last CID used is stored in |
| 969 | /// a system property so that restart of virtualizationservice doesn't reuse CID while the host |
| 970 | /// Android is up. |
| 971 | fn next_cid() -> Result<Cid> { |
Andrew Walbran | 014efb5 | 2022-02-03 17:43:11 +0000 | [diff] [blame] | 972 | let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? { |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 973 | if let Ok(num) = val.parse::<u32>() { |
| 974 | num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))? |
| 975 | } else { |
| 976 | error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID); |
| 977 | FIRST_GUEST_CID |
| 978 | } |
| 979 | } else { |
| 980 | // First VM since the boot |
| 981 | FIRST_GUEST_CID |
| 982 | }; |
| 983 | // Persist the last value for next use |
| 984 | let str_val = format!("{}", next); |
| 985 | system_properties::write(SYSPROP_LAST_CID, &str_val)?; |
| 986 | Ok(next) |
| 987 | } |
| 988 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 989 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 990 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 991 | match &*instance.vm_state.lock().unwrap() { |
| 992 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 993 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 994 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 995 | PayloadState::Started => VirtualMachineState::STARTED, |
| 996 | PayloadState::Ready => VirtualMachineState::READY, |
| 997 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 998 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 999 | }, |
| 1000 | VmState::Dead => VirtualMachineState::DEAD, |
| 1001 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1002 | } |
| 1003 | } |
| 1004 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1005 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1006 | fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
| 1007 | file.as_ref().try_clone().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1008 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1009 | ExceptionCode::BAD_PARCELABLE, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1010 | Some(format!("Failed to clone File from ParcelFileDescriptor: {}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1011 | ) |
| 1012 | }) |
| 1013 | } |
| 1014 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1015 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
| 1016 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> { |
| 1017 | file.as_ref().map(clone_file).transpose() |
| 1018 | } |
| 1019 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1020 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
| 1021 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1022 | // SAFETY: ownership is transferred from stream to f |
| 1023 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1024 | ParcelFileDescriptor::new(f) |
| 1025 | } |
| 1026 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1027 | /// Parses the platform version requirement string. |
| 1028 | fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> { |
| 1029 | VersionReq::parse(s).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1030 | Status::new_exception_str( |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1031 | ExceptionCode::BAD_PARCELABLE, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1032 | Some(format!("Invalid platform version requirement {}: {}", s, e)), |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1033 | ) |
| 1034 | }) |
| 1035 | } |
| 1036 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1037 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 1038 | /// it doesn't require that T implements Clone. |
| 1039 | enum BorrowedOrOwned<'a, T> { |
| 1040 | Borrowed(&'a T), |
| 1041 | Owned(T), |
| 1042 | } |
| 1043 | |
| 1044 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 1045 | fn as_ref(&self) -> &T { |
| 1046 | match self { |
| 1047 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 1048 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1049 | } |
| 1050 | } |
| 1051 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1052 | |
| 1053 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 1054 | #[derive(Debug, Default)] |
| 1055 | struct VirtualMachineService { |
| 1056 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1057 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1058 | } |
| 1059 | |
| 1060 | impl Interface for VirtualMachineService {} |
| 1061 | |
| 1062 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1063 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 1064 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1065 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1066 | info!("VM having CID {} started payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1067 | vm.update_payload_state(PayloadState::Started).map_err(|e| { |
| 1068 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1069 | })?; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1070 | let stream = vm.stream.lock().unwrap().take(); |
| 1071 | vm.callbacks.notify_payload_started(cid, stream); |
| 1072 | Ok(()) |
| 1073 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1074 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1075 | Err(Status::new_service_specific_error_str( |
| 1076 | -1, |
| 1077 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1078 | )) |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1079 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1080 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1081 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1082 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 1083 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1084 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1085 | info!("VM having CID {} payload is ready", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1086 | vm.update_payload_state(PayloadState::Ready).map_err(|e| { |
| 1087 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1088 | })?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1089 | vm.callbacks.notify_payload_ready(cid); |
| 1090 | Ok(()) |
| 1091 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1092 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1093 | Err(Status::new_service_specific_error_str( |
| 1094 | -1, |
| 1095 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1096 | )) |
| 1097 | } |
| 1098 | } |
| 1099 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1100 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 1101 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1102 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1103 | info!("VM having CID {} finished payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1104 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1105 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1106 | })?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1107 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 1108 | Ok(()) |
| 1109 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1110 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1111 | Err(Status::new_service_specific_error_str( |
| 1112 | -1, |
| 1113 | Some(format!("cannot find a VM with CID {}", cid)), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1114 | )) |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> { |
| 1119 | let cid = self.cid; |
| 1120 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
| 1121 | info!("VM having CID {} encountered an error", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1122 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1123 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1124 | })?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1125 | vm.callbacks.notify_error(cid, error_code, message); |
| 1126 | Ok(()) |
| 1127 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 1128 | error!("notifyError is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame^] | 1129 | Err(Status::new_service_specific_error_str( |
| 1130 | -1, |
| 1131 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1132 | )) |
| 1133 | } |
| 1134 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1135 | } |
| 1136 | |
| 1137 | impl VirtualMachineService { |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1138 | fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1139 | if let Some(vm) = state.lock().unwrap().get_vm(cid) { |
| 1140 | let mut vm_service = vm.vm_service.lock().unwrap(); |
| 1141 | let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid)); |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1142 | Some(service.as_binder()) |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1143 | } else { |
| 1144 | error!("connection from cid={} is not from a guest VM", cid); |
Andrew Walbran | 0fd0ff0 | 2022-07-29 15:59:17 +0000 | [diff] [blame] | 1145 | None |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1150 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1151 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1152 | BinderFeatures::default(), |
| 1153 | ) |
| 1154 | } |
| 1155 | } |