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