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