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