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