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 | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 17 | use crate::{get_calling_pid, get_calling_uid, get_this_pid}; |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 18 | use crate::atom::{write_vm_booted_stats, write_vm_creation_stats}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 19 | use crate::composite::make_composite_image; |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 20 | use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState}; |
Jaewan Kim | abd328b | 2024-12-10 15:59:33 +0900 | [diff] [blame] | 21 | use crate::debug_config::{DebugConfig, DebugPolicy}; |
Shikha Panwar | 55e10ec | 2024-02-13 12:53:49 +0000 | [diff] [blame] | 22 | use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH}; |
Inseob Kim | f79c572 | 2024-12-16 17:29:57 +0900 | [diff] [blame] | 23 | use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image}; |
Nikita Ioffe | 13748d2 | 2024-10-23 15:10:39 +0000 | [diff] [blame] | 24 | use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext}; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 25 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 26 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{ |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 27 | Certificate::Certificate, |
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::{ |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 32 | AssignedDevices::AssignedDevices, |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 33 | AssignableDevice::AssignableDevice, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 34 | DiskImage::DiskImage, |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 35 | SharedPath::SharedPath, |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 36 | InputDevice::InputDevice, |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 37 | IVirtualMachine::{self, BnVirtualMachine}, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 38 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 39 | IVirtualizationService::IVirtualizationService, |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 40 | Partition::Partition, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 41 | PartitionType::PartitionType, |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 42 | VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig}, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 43 | VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 44 | VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 45 | VirtualMachinePayloadConfig::VirtualMachinePayloadConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 46 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 47 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 48 | }; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 49 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 50 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal; |
Seungjae Yoo | dd91f0f | 2022-11-09 15:25:21 +0900 | [diff] [blame] | 51 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{ |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 52 | BnVirtualMachineService, IVirtualMachineService, |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 53 | }; |
Shikha Panwar | e45e942 | 2024-02-28 21:18:10 +0000 | [diff] [blame] | 54 | use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper}; |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 55 | use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId; |
Matt Gilbride | b57abcc | 2024-10-12 15:26:45 +0000 | [diff] [blame] | 56 | use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey; |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 57 | use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{ |
| 58 | Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange, |
| 59 | IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult, |
| 60 | Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo, |
| 61 | SessionInitiationInfo::SessionInitiationInfo, |
| 62 | }; |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 63 | use anyhow::{anyhow, bail, ensure, Context, Result}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 64 | use apkverify::{HashAlgorithm, V4Signature}; |
Jiyong Park | d7bd2f2 | 2023-08-10 20:41:19 +0900 | [diff] [blame] | 65 | use avflog::LogResult; |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 66 | use binder::{ |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 67 | self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor, |
| 68 | SpIBinder, Status, StatusCode, Strong, IntoBinderResult, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 69 | }; |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 70 | use glob::glob; |
Devin Moore | c8800a1 | 2024-10-17 17:56:18 +0000 | [diff] [blame] | 71 | use libc::{AF_VSOCK, sa_family_t, sockaddr_vm}; |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 72 | use log::{debug, error, info, warn}; |
Nikita Ioffe | 901083f | 2025-01-20 01:54:28 +0000 | [diff] [blame] | 73 | use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig}; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 74 | use nix::unistd::pipe; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 75 | use rpcbinder::RpcServer; |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 76 | use rustutils::system_properties; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 77 | use semver::VersionReq; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 78 | use serde::Deserialize; |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 79 | use std::collections::{HashSet, HashMap}; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 80 | use std::convert::TryInto; |
Shikha Panwar | 55e10ec | 2024-02-13 12:53:49 +0000 | [diff] [blame] | 81 | use std::fs; |
Jaewan Kim | 3995207 | 2024-01-19 17:04:53 +0900 | [diff] [blame] | 82 | use std::ffi::CStr; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 83 | use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions}; |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 84 | use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write}; |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 85 | use std::iter; |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 86 | use std::num::{NonZeroU16, NonZeroU32}; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 87 | use std::ops::Range; |
Jiyong Park | af63d1c | 2024-09-04 16:15:42 +0900 | [diff] [blame] | 88 | use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 89 | use std::os::unix::raw::pid_t; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 90 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 9c03a3a | 2024-09-03 12:12:59 +0100 | [diff] [blame] | 91 | use std::sync::{Arc, Mutex, Weak, LazyLock}; |
Seungjae Yoo | 14e6018 | 2024-02-21 13:28:31 +0900 | [diff] [blame] | 92 | use vbmeta::VbMetaImage; |
Pierre-Clément Tosi | d3bbe1d | 2024-04-15 18:03:51 +0100 | [diff] [blame] | 93 | use vmconfig::{VmConfig, get_debug_level}; |
Devin Moore | c8800a1 | 2024-10-17 17:56:18 +0000 | [diff] [blame] | 94 | use vsock::VsockStream; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 95 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 96 | |
David Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 97 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 98 | pub type Cid = u32; |
| 99 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 100 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
| 101 | |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 102 | /// Vsock privileged ports are below this number. |
| 103 | const VSOCK_PRIV_PORT_MAX: u32 = 1024; |
| 104 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 105 | /// The size of zero.img. |
| 106 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 107 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 108 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 109 | /// Magic string for the instance image |
| 110 | const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance"; |
| 111 | |
| 112 | /// Version of the instance image format |
| 113 | const ANDROID_VM_INSTANCE_VERSION: u16 = 1; |
| 114 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 115 | const MICRODROID_OS_NAME: &str = "microdroid"; |
| 116 | |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 117 | const SECRETKEEPER_IDENTIFIER: &str = |
Shikha Panwar | be5dee7 | 2024-02-21 19:06:20 +0000 | [diff] [blame] | 118 | "android.hardware.security.secretkeeper.ISecretkeeper/default"; |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 119 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 120 | const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE"; |
| 121 | |
| 122 | /// crosvm requires all partitions to be a multiple of 4KiB. |
| 123 | const PARTITION_GRANULARITY_BYTES: u64 = 4096; |
| 124 | |
Shikha Panwar | 55e10ec | 2024-02-13 12:53:49 +0000 | [diff] [blame] | 125 | const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference"; |
| 126 | |
Andrew Walbran | 9c03a3a | 2024-09-03 12:12:59 +0100 | [diff] [blame] | 127 | pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> = |
| 128 | LazyLock::new(|| { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 129 | if cfg!(early) { |
| 130 | panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal") |
| 131 | } else { |
| 132 | wait_for_interface(BINDER_SERVICE_IDENTIFIER) |
| 133 | .expect("Could not connect to VirtualizationServiceInternal") |
| 134 | } |
Andrew Walbran | 9c03a3a | 2024-09-03 12:12:59 +0100 | [diff] [blame] | 135 | }); |
| 136 | static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> = |
| 137 | LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names")); |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 138 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 139 | static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| { |
| 140 | let calling_exe_link = format!("/proc/{}/exe", get_calling_pid()); |
| 141 | match fs::read_link(&calling_exe_link) { |
| 142 | Ok(calling_exe_path) => Some(calling_exe_path), |
| 143 | Err(e) => { |
| 144 | // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we |
| 145 | // discourage vendor apps, regarding such cases as system is safer. |
| 146 | // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of |
| 147 | // apps. |
| 148 | warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system"); |
| 149 | None |
| 150 | } |
| 151 | } |
| 152 | }); |
| 153 | |
Nikita Ioffe | 22e5d0a | 2025-02-17 16:36:52 +0000 | [diff] [blame] | 154 | // TODO(ioffe): add service for guest-ffa. |
| 155 | const KNOWN_TEE_SERVICES: [&str; 0] = []; |
| 156 | |
| 157 | fn check_known_tee_service(tee_service: &str) -> binder::Result<()> { |
| 158 | if !KNOWN_TEE_SERVICES.contains(&tee_service) { |
| 159 | return Err(anyhow!("unknown tee_service {tee_service}")) |
| 160 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 161 | } |
| 162 | Ok(()) |
| 163 | } |
| 164 | |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 165 | fn create_or_update_idsig_file( |
| 166 | input_fd: &ParcelFileDescriptor, |
| 167 | idsig_fd: &ParcelFileDescriptor, |
| 168 | ) -> Result<()> { |
| 169 | let mut input = clone_file(input_fd)?; |
| 170 | let metadata = input.metadata().context("failed to get input metadata")?; |
| 171 | if !metadata.is_file() { |
| 172 | bail!("input is not a regular file"); |
| 173 | } |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 174 | let mut sig = |
| 175 | V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256) |
| 176 | .context("failed to create idsig")?; |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 177 | |
| 178 | let mut output = clone_file(idsig_fd)?; |
Jiyong Park | 8d19295 | 2023-06-26 14:29:51 +0900 | [diff] [blame] | 179 | |
| 180 | // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it, |
| 181 | // if the idsig file already has the same APK digest. |
| 182 | if output.metadata()?.len() > 0 { |
| 183 | if let Ok(out_sig) = V4Signature::from_idsig(&mut output) { |
| 184 | if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest { |
| 185 | debug!("idsig {:?} is up-to-date with apk {:?}.", output, input); |
| 186 | return Ok(()); |
| 187 | } |
| 188 | } |
| 189 | // if we fail to read v4signature from output, that's fine. User can pass a random file. |
| 190 | // We will anyway overwrite the file to the v4signature generated from input_fd. |
| 191 | } |
| 192 | |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 193 | output |
| 194 | .seek(SeekFrom::Start(0)) |
| 195 | .context("failed to move cursor to start on the idsig output")?; |
Nikita Ioffe | c09b049 | 2022-12-14 20:18:33 +0000 | [diff] [blame] | 196 | output.set_len(0).context("failed to set_len on the idsig output")?; |
| 197 | sig.write_into(&mut output).context("failed to write idsig")?; |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 198 | Ok(()) |
| 199 | } |
| 200 | |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 201 | fn get_current_sdk() -> Result<u32> { |
| 202 | let current_sdk = system_properties::read("ro.build.version.sdk")?; |
| 203 | let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?; |
| 204 | current_sdk.parse().context("Malformed SDK version") |
| 205 | } |
| 206 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 207 | pub fn remove_temporary_files(path: &PathBuf) -> Result<()> { |
| 208 | for dir_entry in read_dir(path)? { |
| 209 | remove_file(dir_entry?.path())?; |
| 210 | } |
| 211 | Ok(()) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 212 | } |
| 213 | |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 214 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 215 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 216 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 217 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 218 | } |
| 219 | |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 220 | impl Interface for VirtualizationService { |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 221 | fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> { |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 222 | check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?; |
| 223 | let state = &mut *self.state.lock().unwrap(); |
| 224 | let vms = state.vms(); |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 225 | writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 226 | for vm in vms { |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 227 | writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 228 | writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 229 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 230 | writeln!(writer, "\tPayload state {:?}", vm.payload_state()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 231 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 232 | writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 233 | writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 234 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 235 | writeln!(writer, "\trequester_uid: {}", vm.requester_uid) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 236 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame] | 237 | writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 238 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 239 | } |
| 240 | Ok(()) |
| 241 | } |
| 242 | } |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 243 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 244 | /// Creates (but does not start) a new VM with the given configuration, assigning it the next |
| 245 | /// available CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 246 | /// |
| 247 | /// 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] | 248 | fn createVm( |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 249 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 250 | config: &VirtualMachineConfig, |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 251 | console_out_fd: Option<&ParcelFileDescriptor>, |
| 252 | console_in_fd: Option<&ParcelFileDescriptor>, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 253 | log_fd: Option<&ParcelFileDescriptor>, |
Elie Kheirallah | 5c807a2 | 2024-09-23 20:40:42 +0000 | [diff] [blame] | 254 | dump_dt_fd: Option<&ParcelFileDescriptor>, |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 255 | ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 256 | let mut is_protected = false; |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 257 | let ret = self.create_vm_internal( |
| 258 | config, |
| 259 | console_out_fd, |
| 260 | console_in_fd, |
| 261 | log_fd, |
| 262 | &mut is_protected, |
Elie Kheirallah | 5c807a2 | 2024-09-23 20:40:42 +0000 | [diff] [blame] | 263 | dump_dt_fd, |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 264 | ); |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 265 | write_vm_creation_stats(config, is_protected, &ret); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 266 | ret |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 267 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 268 | |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 269 | /// Allocate a new instance_id to the VM |
| 270 | fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> { |
Shikha Panwar | bd5eba9 | 2024-03-27 20:23:31 +0000 | [diff] [blame] | 271 | check_manage_access()?; |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 272 | GLOBAL_SERVICE.allocateInstanceId() |
| 273 | } |
| 274 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 275 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 276 | fn initializeWritablePartition( |
| 277 | &self, |
| 278 | image_fd: &ParcelFileDescriptor, |
Alan Stokes | ff0005f | 2023-01-30 09:53:00 +0000 | [diff] [blame] | 279 | size_bytes: i64, |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 280 | partition_type: PartitionType, |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 281 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 282 | check_manage_access()?; |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 283 | let size_bytes = size_bytes |
| 284 | .try_into() |
| 285 | .with_context(|| format!("Invalid size: {}", size_bytes)) |
| 286 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 287 | let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES); |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 288 | let mut image = clone_file(image_fd)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 289 | // initialize the file. Any data in the file will be erased. |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 290 | image |
| 291 | .seek(SeekFrom::Start(0)) |
| 292 | .context("failed to move cursor to start") |
| 293 | .or_service_specific_exception(-1)?; |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 294 | image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?; |
Frederick Mayle | 0d31057 | 2024-05-02 12:34:58 -0700 | [diff] [blame] | 295 | // Set the file length. In most filesystems, this will not allocate any physical disk |
| 296 | // space, it will only change the logical size. |
| 297 | image |
| 298 | .set_len(size_bytes) |
| 299 | .context("Failed to extend file") |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 300 | .or_service_specific_exception(-1)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 301 | |
| 302 | match partition_type { |
| 303 | PartitionType::RAW => Ok(()), |
Frederick Mayle | 0d31057 | 2024-05-02 12:34:58 -0700 | [diff] [blame] | 304 | PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image), |
| 305 | PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image), |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 306 | _ => Err(Error::new( |
| 307 | ErrorKind::Unsupported, |
| 308 | format!("Unsupported partition type {:?}", partition_type), |
| 309 | )), |
| 310 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 311 | .with_context(|| format!("Failed to initialize partition as {:?}", partition_type)) |
| 312 | .or_service_specific_exception(-1)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 313 | |
| 314 | Ok(()) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 315 | } |
| 316 | |
Shraddha Basantwani | a9a9c4f | 2025-02-25 09:51:48 -0800 | [diff] [blame] | 317 | fn setEncryptedStorageSize( |
| 318 | &self, |
| 319 | image_fd: &ParcelFileDescriptor, |
| 320 | size: i64, |
| 321 | ) -> binder::Result<()> { |
| 322 | check_manage_access()?; |
| 323 | |
| 324 | let size = size |
| 325 | .try_into() |
| 326 | .with_context(|| format!("Invalid size: {}", size)) |
| 327 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?; |
| 328 | let size = round_up(size, PARTITION_GRANULARITY_BYTES); |
| 329 | |
| 330 | let image = clone_file(image_fd)?; |
| 331 | let image_size = image.metadata().unwrap().len(); |
| 332 | |
| 333 | if image_size > size { |
| 334 | return Err(Status::new_exception_str( |
| 335 | ExceptionCode::ILLEGAL_ARGUMENT, |
| 336 | Some("Can't shrink encrypted storage"), |
| 337 | )); |
| 338 | } |
| 339 | // Reset the file length. In most filesystems, this will not allocate any physical disk |
| 340 | // space, it will only change the logical size. |
| 341 | image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?; |
| 342 | Ok(()) |
| 343 | } |
| 344 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 345 | /// Creates or update the idsig file by digesting the input APK file. |
| 346 | fn createOrUpdateIdsigFile( |
| 347 | &self, |
| 348 | input_fd: &ParcelFileDescriptor, |
| 349 | idsig_fd: &ParcelFileDescriptor, |
| 350 | ) -> binder::Result<()> { |
Jiyong Park | c3ca24f | 2022-06-28 10:45:15 +0900 | [diff] [blame] | 351 | check_manage_access()?; |
| 352 | |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 353 | create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?; |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 354 | Ok(()) |
| 355 | } |
| 356 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 357 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 358 | /// and as such is only permitted from the shell user. |
| 359 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 360 | // Delegate to the global service, including checking the debug permission. |
David Brazdil | d4f51a5 | 2023-01-11 14:09:27 +0000 | [diff] [blame] | 361 | GLOBAL_SERVICE.debugListVms() |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 362 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 363 | |
| 364 | /// Get a list of assignable device types. |
| 365 | fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> { |
| 366 | // Delegate to the global service, including checking the permission. |
| 367 | GLOBAL_SERVICE.getAssignableDevices() |
| 368 | } |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 369 | |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 370 | /// Get a list of supported OSes. |
| 371 | fn getSupportedOSList(&self) -> binder::Result<Vec<String>> { |
| 372 | Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned())) |
| 373 | } |
| 374 | |
Jaewan Kim | abd328b | 2024-12-10 15:59:33 +0900 | [diff] [blame] | 375 | /// Get printable debug policy for testing and debugging |
| 376 | fn getDebugPolicy(&self) -> binder::Result<String> { |
| 377 | let debug_policy = DebugPolicy::from_host(); |
| 378 | Ok(format!("{debug_policy:?}")) |
| 379 | } |
| 380 | |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 381 | /// Returns whether given feature is enabled |
| 382 | fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> { |
| 383 | check_manage_access()?; |
Shikha Panwar | 6d30641 | 2024-02-17 21:37:49 +0000 | [diff] [blame] | 384 | Ok(avf_features::is_feature_enabled(feature)) |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 385 | } |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 386 | |
| 387 | fn enableTestAttestation(&self) -> binder::Result<()> { |
| 388 | GLOBAL_SERVICE.enableTestAttestation() |
| 389 | } |
Alice Wang | 0362f7f | 2024-03-21 08:16:26 +0000 | [diff] [blame] | 390 | |
| 391 | fn isRemoteAttestationSupported(&self) -> binder::Result<bool> { |
| 392 | check_manage_access()?; |
| 393 | GLOBAL_SERVICE.isRemoteAttestationSupported() |
| 394 | } |
Shikha Panwar | 7aef66d | 2024-03-13 00:28:41 +0000 | [diff] [blame] | 395 | |
| 396 | fn isUpdatableVmSupported(&self) -> binder::Result<bool> { |
| 397 | // The response is specific to Microdroid. Updatable VMs are only possible if device |
| 398 | // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does |
| 399 | // this, however other guest OSes may do things differently. |
| 400 | check_manage_access()?; |
| 401 | Ok(is_secretkeeper_supported()) |
| 402 | } |
Shikha Panwar | bd5eba9 | 2024-03-27 20:23:31 +0000 | [diff] [blame] | 403 | |
Shikha Panwar | 07d701c | 2024-03-28 14:43:52 +0000 | [diff] [blame] | 404 | fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> { |
| 405 | check_manage_access()?; |
| 406 | GLOBAL_SERVICE.removeVmInstance(instance_id) |
| 407 | } |
| 408 | |
Shikha Panwar | bd5eba9 | 2024-03-27 20:23:31 +0000 | [diff] [blame] | 409 | fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> { |
| 410 | check_manage_access()?; |
| 411 | GLOBAL_SERVICE.claimVmInstance(instance_id) |
| 412 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 413 | } |
| 414 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 415 | /// Implementation of the AIDL `IGlobalVmContext` interface for early VMs. |
| 416 | #[derive(Debug, Default)] |
| 417 | struct EarlyVmContext { |
| 418 | /// The unique CID assigned to the VM for vsock communication. |
| 419 | cid: Cid, |
| 420 | /// Temporary directory for this VM instance. |
| 421 | temp_dir: PathBuf, |
| 422 | } |
| 423 | |
| 424 | impl EarlyVmContext { |
| 425 | fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> { |
| 426 | // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF |
| 427 | // should trust clients, e.g. they won't run two VMs at the same time |
| 428 | let _ = remove_dir_all(&temp_dir); |
| 429 | create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?; |
| 430 | |
| 431 | Ok(Self { cid, temp_dir }) |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | impl Interface for EarlyVmContext {} |
| 436 | |
| 437 | impl Drop for EarlyVmContext { |
| 438 | fn drop(&mut self) { |
| 439 | if let Err(e) = remove_dir_all(&self.temp_dir) { |
| 440 | error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display()); |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | impl IGlobalVmContext for EarlyVmContext { |
| 446 | fn getCid(&self) -> binder::Result<i32> { |
| 447 | Ok(self.cid as i32) |
| 448 | } |
| 449 | |
| 450 | fn getTemporaryDirectory(&self) -> binder::Result<String> { |
| 451 | Ok(self.temp_dir.to_string_lossy().to_string()) |
| 452 | } |
| 453 | |
| 454 | fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> { |
| 455 | Err(Status::new_exception_str( |
| 456 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 457 | Some("Early VM doesn't support setting host console name"), |
| 458 | )) |
| 459 | } |
| 460 | } |
| 461 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 462 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 463 | enum CallingPartition { |
| 464 | Odm, |
| 465 | Product, |
| 466 | System, |
| 467 | SystemExt, |
| 468 | Vendor, |
| 469 | Unknown, |
| 470 | } |
| 471 | |
| 472 | impl CallingPartition { |
| 473 | fn as_str(&self) -> &'static str { |
| 474 | match self { |
| 475 | CallingPartition::Odm => "odm", |
| 476 | CallingPartition::Product => "product", |
| 477 | CallingPartition::System => "system", |
| 478 | CallingPartition::SystemExt => "system_ext", |
| 479 | CallingPartition::Vendor => "vendor", |
| 480 | CallingPartition::Unknown => "[unknown]", |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | impl std::fmt::Display for CallingPartition { |
| 486 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 487 | write!(f, "{}", self.as_str()) |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> { |
Frederick Mayle | cc9862f | 2025-02-10 20:42:59 -0800 | [diff] [blame] | 492 | let Some(path) = path else { |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 493 | return Ok(CallingPartition::System); |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 494 | }; |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 495 | if path.starts_with("/system/system_ext/") { |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 496 | return Ok(CallingPartition::SystemExt); |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 497 | } |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 498 | if path.starts_with("/system/product/") { |
| 499 | return Ok(CallingPartition::Product); |
| 500 | } |
Frederick Mayle | 2192baf | 2025-02-26 11:27:22 -0800 | [diff] [blame] | 501 | if path.starts_with("/data/nativetest/vendor/") |
| 502 | || path.starts_with("/data/nativetest64/vendor/") |
| 503 | { |
| 504 | return Ok(CallingPartition::Vendor); |
| 505 | } |
| 506 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 507 | let partition = { |
| 508 | let mut components = path.components(); |
| 509 | let Some(std::path::Component::Normal(partition)) = components.nth(1) else { |
| 510 | return Err(anyhow!("Can't find partition in '{}'", path.display())) |
Frederick Mayle | cc9862f | 2025-02-10 20:42:59 -0800 | [diff] [blame] | 511 | .or_service_specific_exception(-1); |
| 512 | }; |
Frederick Mayle | cc9862f | 2025-02-10 20:42:59 -0800 | [diff] [blame] | 513 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 514 | // If path is under /apex, find a partition of the preinstalled .apex path |
| 515 | if partition == "apex" { |
| 516 | let Some(std::path::Component::Normal(apex_name)) = components.next() else { |
| 517 | return Err(anyhow!("Can't find apex name for '{}'", path.display())) |
| 518 | .or_service_specific_exception(-1); |
| 519 | }; |
| 520 | let apex_info_list = ApexInfoList::load() |
| 521 | .context("Failed to get apex info list") |
| 522 | .or_service_specific_exception(-1)?; |
| 523 | apex_info_list |
| 524 | .list |
| 525 | .iter() |
| 526 | .find(|apex_info| apex_info.name.as_str() == apex_name) |
| 527 | .map(|apex_info| apex_info.partition.to_lowercase()) |
| 528 | .ok_or(anyhow!("Can't find apex info for {apex_name:?}")) |
| 529 | .or_service_specific_exception(-1)? |
| 530 | } else { |
| 531 | partition.to_string_lossy().into_owned() |
| 532 | } |
| 533 | }; |
| 534 | Ok(match partition.as_str() { |
| 535 | "odm" => CallingPartition::Odm, |
| 536 | "product" => CallingPartition::Product, |
| 537 | "system" => CallingPartition::System, |
| 538 | "system_ext" => CallingPartition::SystemExt, |
| 539 | "vendor" => CallingPartition::Vendor, |
| 540 | _ => { |
| 541 | warn!("unknown partition for '{}'", path.display()); |
| 542 | CallingPartition::Unknown |
| 543 | } |
| 544 | }) |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 545 | } |
| 546 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 547 | impl VirtualizationService { |
| 548 | pub fn init() -> VirtualizationService { |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 549 | VirtualizationService::default() |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 550 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 551 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 552 | fn create_early_vm_context( |
| 553 | &self, |
| 554 | config: &VirtualMachineConfig, |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 555 | calling_exe_path: Option<&Path>, |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 556 | calling_partition: CallingPartition, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 557 | ) -> binder::Result<(VmContext, Cid, PathBuf)> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 558 | let name = match config { |
| 559 | VirtualMachineConfig::RawConfig(config) => &config.name, |
| 560 | VirtualMachineConfig::AppConfig(config) => &config.name, |
| 561 | }; |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 562 | let early_vm = find_early_vm_for_partition(calling_partition, name) |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 563 | .or_service_specific_exception(-1)?; |
| 564 | let calling_exe_path = match calling_exe_path { |
| 565 | Some(path) => path, |
| 566 | None => { |
| 567 | return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid())) |
| 568 | .or_service_specific_exception(-1) |
| 569 | } |
| 570 | }; |
Alice Wang | 78dd87a | 2025-02-13 08:56:07 +0000 | [diff] [blame] | 571 | early_vm.check_exe_paths_match(calling_exe_path)?; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 572 | |
| 573 | let cid = early_vm.cid as Cid; |
| 574 | let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}")); |
| 575 | |
| 576 | let context = EarlyVmContext::new(cid, temp_dir.clone()) |
| 577 | .context(format!("Can't create early vm contexts for {cid}")) |
| 578 | .or_service_specific_exception(-1)?; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 579 | |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 580 | if requires_vm_service(config) { |
| 581 | // Start VM service listening for connections from the new CID on port=CID. |
| 582 | let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder(); |
| 583 | let port = cid; |
| 584 | let (vm_server, _) = RpcServer::new_vsock(service, cid, port) |
| 585 | .context(format!("Could not start RpcServer on port {port}")) |
| 586 | .or_service_specific_exception(-1)?; |
| 587 | vm_server.start(); |
| 588 | Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir)) |
| 589 | } else { |
| 590 | Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir)) |
| 591 | } |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 592 | } |
| 593 | |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 594 | fn create_vm_context( |
| 595 | &self, |
| 596 | requester_debug_pid: pid_t, |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 597 | config: &VirtualMachineConfig, |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 598 | ) -> binder::Result<(VmContext, Cid, PathBuf)> { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 599 | const NUM_ATTEMPTS: usize = 5; |
| 600 | |
| 601 | for _ in 0..NUM_ATTEMPTS { |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 602 | let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?; |
David Brazdil | d4f51a5 | 2023-01-11 14:09:27 +0000 | [diff] [blame] | 603 | let cid = vm_context.getCid()? as Cid; |
| 604 | let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into(); |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 605 | |
| 606 | // We don't need to start the VM service for custom VMs. |
| 607 | if !requires_vm_service(config) { |
| 608 | return Ok((VmContext::new(vm_context, None), cid, temp_dir)); |
| 609 | } |
| 610 | |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 611 | let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder(); |
| 612 | |
| 613 | // 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] | 614 | let port = cid; |
David Brazdil | 3238da4 | 2022-11-18 10:04:51 +0000 | [diff] [blame] | 615 | match RpcServer::new_vsock(service, cid, port) { |
Devin Moore | 068e674 | 2024-10-28 18:16:25 +0000 | [diff] [blame] | 616 | Ok((vm_server, _)) => { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 617 | vm_server.start(); |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 618 | return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir)); |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 619 | } |
| 620 | Err(err) => { |
| 621 | warn!("Could not start RpcServer on port {}: {}", port, err); |
| 622 | } |
| 623 | } |
| 624 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 625 | Err(anyhow!("Too many attempts to create VM context failed")) |
| 626 | .or_service_specific_exception(-1) |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 627 | } |
| 628 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 629 | fn create_vm_internal( |
| 630 | &self, |
| 631 | config: &VirtualMachineConfig, |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 632 | console_out_fd: Option<&ParcelFileDescriptor>, |
| 633 | console_in_fd: Option<&ParcelFileDescriptor>, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 634 | log_fd: Option<&ParcelFileDescriptor>, |
| 635 | is_protected: &mut bool, |
Elie Kheirallah | 5c807a2 | 2024-09-23 20:40:42 +0000 | [diff] [blame] | 636 | dump_dt_fd: Option<&ParcelFileDescriptor>, |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 637 | ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> { |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 638 | let requester_uid = get_calling_uid(); |
| 639 | let requester_debug_pid = get_calling_pid(); |
| 640 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 641 | let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?; |
| 642 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 643 | check_config_features(config)?; |
| 644 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 645 | if cfg!(early) { |
| 646 | check_config_allowed_for_early_vms(config)?; |
| 647 | } |
| 648 | |
Nikita Ioffe | b141612 | 2024-10-22 12:18:49 +0000 | [diff] [blame] | 649 | let caller_secontext = getprevcon().or_service_specific_exception(-1)?; |
| 650 | info!("callers secontext: {}", caller_secontext); |
| 651 | |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 652 | // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission. |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 653 | let (vm_context, cid, temporary_directory) = if cfg!(early) { |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 654 | self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)? |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 655 | } else { |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 656 | self.create_vm_context(requester_debug_pid, config)? |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 657 | }; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 658 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 659 | if is_custom_config(config) { |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 660 | check_use_custom_virtual_machine()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 661 | } |
| 662 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 663 | let gdb_port = extract_gdb_port(config); |
| 664 | |
| 665 | // Additional permission checks if caller request gdb. |
| 666 | if gdb_port.is_some() { |
| 667 | check_gdb_allowed(config)?; |
| 668 | } |
| 669 | |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 670 | let instance_id = extract_instance_id(config); |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 671 | let mut device_tree_overlays = vec![]; |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 672 | if let Some(dt_overlay) = |
| 673 | maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)? |
| 674 | { |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 675 | device_tree_overlays.push(dt_overlay); |
| 676 | } |
| 677 | if let Some(dtbo) = get_dtbo(config) { |
| 678 | let dtbo = File::from( |
| 679 | dtbo.as_ref() |
| 680 | .try_clone() |
| 681 | .context("Failed to create VM DTBO from ParcelFileDescriptor") |
| 682 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?, |
| 683 | ); |
| 684 | device_tree_overlays.push(dtbo); |
| 685 | } |
Seungjae Yoo | ec3bc52 | 2023-11-09 10:14:30 +0900 | [diff] [blame] | 686 | |
Jaewan Kim | f314324 | 2024-03-15 06:56:31 +0000 | [diff] [blame] | 687 | let debug_config = DebugConfig::new(config); |
Nikita Ioffe | 2cb75cf | 2024-06-04 16:43:56 +0000 | [diff] [blame] | 688 | let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() { |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 689 | Some(prepare_ramdump_file(&temporary_directory)?) |
| 690 | } else { |
| 691 | None |
| 692 | }; |
| 693 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 694 | let state = &mut *self.state.lock().unwrap(); |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 695 | let console_out_fd = |
Pierre-Clément Tosi | fc523c5 | 2024-08-20 10:34:06 +0100 | [diff] [blame] | 696 | clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?; |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 697 | let console_in_fd = console_in_fd.map(clone_file).transpose()?; |
Pierre-Clément Tosi | fc523c5 | 2024-08-20 10:34:06 +0100 | [diff] [blame] | 698 | let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?; |
Pierre-Clément Tosi | 9515d0f | 2024-04-15 15:58:07 +0100 | [diff] [blame] | 699 | let dump_dt_fd = if let Some(fd) = dump_dt_fd { |
| 700 | Some(clone_file(fd)?) |
| 701 | } else if debug_config.dump_device_tree { |
| 702 | Some(prepare_dump_dt_file(&temporary_directory)?) |
| 703 | } else { |
| 704 | None |
| 705 | }; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 706 | |
| 707 | // Counter to generate unique IDs for temporary image files. |
| 708 | let mut next_temporary_image_id = 0; |
| 709 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 710 | // child process, and not closed before it is started. |
| 711 | let mut indirect_files = vec![]; |
| 712 | |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 713 | let (is_app_config, config) = match config { |
| 714 | VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)), |
| 715 | VirtualMachineConfig::AppConfig(config) => { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 716 | let config = load_app_config(config, &debug_config, &temporary_directory) |
| 717 | .or_service_specific_exception_with(-1, |e| { |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 718 | *is_protected = config.protectedVm; |
| 719 | let message = format!("Failed to load app config: {:?}", e); |
| 720 | error!("{}", message); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 721 | message |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 722 | })?; |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 723 | (true, BorrowedOrOwned::Owned(config)) |
| 724 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 725 | }; |
| 726 | let config = config.as_ref(); |
| 727 | *is_protected = config.protectedVm; |
| 728 | |
Nikita Ioffe | 9951e4b | 2024-11-14 17:30:50 +0000 | [diff] [blame] | 729 | if !config.teeServices.is_empty() { |
Nikita Ioffe | 65e6fdb | 2025-02-17 17:00:27 +0000 | [diff] [blame^] | 730 | if !config.protectedVm { |
| 731 | return Err(anyhow!("only protected VMs can request tee services")) |
| 732 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 733 | } |
Nikita Ioffe | 9951e4b | 2024-11-14 17:30:50 +0000 | [diff] [blame] | 734 | check_tee_service_permission(&caller_secontext, &config.teeServices) |
| 735 | .with_log() |
| 736 | .or_binder_exception(ExceptionCode::SECURITY)?; |
| 737 | } |
Nikita Ioffe | 13748d2 | 2024-10-23 15:10:39 +0000 | [diff] [blame] | 738 | |
Nikita Ioffe | 22e5d0a | 2025-02-17 16:36:52 +0000 | [diff] [blame] | 739 | let mut system_tee_services = Vec::new(); |
| 740 | let mut vendor_tee_services = Vec::new(); |
| 741 | for tee_service in config.teeServices.clone() { |
| 742 | if !tee_service.starts_with("vendor.") { |
| 743 | check_known_tee_service(&tee_service)?; |
| 744 | system_tee_services.push(tee_service); |
| 745 | } else { |
| 746 | vendor_tee_services.push(tee_service); |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | // TODO(b/391774181): handle vendor tee services (which require talking to HAL) as well. |
| 751 | if !vendor_tee_services.is_empty() { |
| 752 | return Err(anyhow!("support for vendor tee services is coming soon!")) |
| 753 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 754 | } |
| 755 | |
Nikita Ioffe | 65e6fdb | 2025-02-17 17:00:27 +0000 | [diff] [blame^] | 756 | // TODO(b/391774181): remove this check in a follow-up patch. |
Nikita Ioffe | 22e5d0a | 2025-02-17 16:36:52 +0000 | [diff] [blame] | 757 | if !system_tee_services.is_empty() { |
| 758 | return Err(anyhow!("support for system tee services is coming soon!")) |
| 759 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 760 | } |
| 761 | |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 762 | let kernel = maybe_clone_file(&config.kernel)?; |
| 763 | let initrd = maybe_clone_file(&config.initrd)?; |
| 764 | |
| 765 | if config.protectedVm { |
| 766 | // Fail fast with a meaningful error message in case device doesn't support pVMs. |
| 767 | check_protected_vm_is_supported()?; |
| 768 | |
| 769 | // In a protected VM, we require custom kernels to come from a trusted source |
| 770 | // (b/237054515). |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 771 | check_label_for_kernel_files(&kernel, &initrd, calling_partition) |
| 772 | .or_service_specific_exception(-1)?; |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 773 | |
| 774 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 775 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) |
| 776 | // from being loaded in a pVM. This applies to everything but the instance image in the |
| 777 | // raw config, and everything but the non-executable, generated partitions in the app |
| 778 | // config. |
| 779 | config |
| 780 | .disks |
| 781 | .iter() |
Frederick Mayle | 9539fb5 | 2025-02-13 13:08:15 -0800 | [diff] [blame] | 782 | .flat_map(|disk| disk.image.as_ref()) |
| 783 | .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition)) |
| 784 | .or_service_specific_exception(-1)?; |
| 785 | config |
| 786 | .disks |
| 787 | .iter() |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 788 | .flat_map(|disk| disk.partitions.iter()) |
| 789 | .filter(|partition| { |
| 790 | if is_app_config { |
| 791 | !is_safe_app_partition(&partition.label) |
| 792 | } else { |
| 793 | !is_safe_raw_partition(&partition.label) |
| 794 | } |
| 795 | }) |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 796 | .try_for_each(|partition| check_label_for_partition(partition, calling_partition)) |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 797 | .or_service_specific_exception(-1)?; |
| 798 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 799 | |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 800 | // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may |
| 801 | // have unstable interfaces. |
| 802 | // TODO(b/316431494): remove once Treble interfaces are stabilized. |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 803 | check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 804 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 805 | let zero_filler_path = temporary_directory.join("zero.img"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 806 | write_zero_filler(&zero_filler_path) |
| 807 | .context("Failed to make composite image") |
| 808 | .with_log() |
| 809 | .or_service_specific_exception(-1)?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 810 | |
| 811 | // Assemble disk images if needed. |
| 812 | let disks = config |
| 813 | .disks |
| 814 | .iter() |
| 815 | .map(|disk| { |
| 816 | assemble_disk_image( |
| 817 | disk, |
| 818 | &zero_filler_path, |
| 819 | &temporary_directory, |
| 820 | &mut next_temporary_image_id, |
| 821 | &mut indirect_files, |
| 822 | ) |
| 823 | }) |
| 824 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 825 | |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 826 | let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?; |
| 827 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 828 | let (vfio_devices, dtbo) = match &config.devices { |
| 829 | AssignedDevices::Devices(devices) if !devices.is_empty() => { |
| 830 | let mut set = HashSet::new(); |
| 831 | for device in devices.iter() { |
| 832 | let path = canonicalize(device) |
| 833 | .with_context(|| format!("can't canonicalize {device}")) |
| 834 | .or_service_specific_exception(-1)?; |
| 835 | if !set.insert(path) { |
| 836 | return Err(anyhow!("duplicated device {device}")) |
| 837 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
| 838 | } |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 839 | } |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 840 | let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?; |
| 841 | let dtbo_file = File::from( |
| 842 | GLOBAL_SERVICE |
| 843 | .getDtboFile()? |
| 844 | .as_ref() |
| 845 | .try_clone() |
| 846 | .context("Failed to create VM DTBO from ParcelFileDescriptor") |
| 847 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?, |
| 848 | ); |
| 849 | (devices, Some(dtbo_file)) |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 850 | } |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 851 | _ => (vec![], None), |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 852 | }; |
Jeongik Cha | 798401c | 2024-04-11 21:54:49 +0900 | [diff] [blame] | 853 | let display_config = if cfg!(paravirtualized_devices) { |
| 854 | config |
| 855 | .displayConfig |
| 856 | .as_ref() |
| 857 | .map(DisplayConfig::new) |
| 858 | .transpose() |
| 859 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 860 | } else { |
| 861 | None |
| 862 | }; |
Jason Macnak | ea7b0fa | 2024-05-08 17:02:44 -0700 | [diff] [blame] | 863 | let gpu_config = if cfg!(paravirtualized_devices) { |
| 864 | config |
| 865 | .gpuConfig |
| 866 | .as_ref() |
| 867 | .map(GpuConfig::new) |
| 868 | .transpose() |
| 869 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 870 | } else { |
| 871 | None |
| 872 | }; |
Jeongik Cha | 1df1c03 | 2024-04-03 16:03:12 +0900 | [diff] [blame] | 873 | |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 874 | let input_device_options = if cfg!(paravirtualized_devices) { |
| 875 | config |
| 876 | .inputDevices |
| 877 | .iter() |
| 878 | .map(to_input_device_option_from) |
| 879 | .collect::<Result<Vec<InputDeviceOption>, _>>() |
| 880 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 881 | } else { |
| 882 | vec![] |
| 883 | }; |
| 884 | |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 885 | // Create TAP network interface if the VM supports network. |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 886 | let tap = if cfg!(network) && config.networkSupported { |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 887 | if *is_protected { |
| 888 | return Err(anyhow!("Network feature is not supported for pVM yet")) |
| 889 | .with_log() |
| 890 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?; |
| 891 | } |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 892 | Some(File::from( |
| 893 | GLOBAL_SERVICE |
| 894 | .createTapInterface(&get_this_pid().to_string())? |
| 895 | .as_ref() |
| 896 | .try_clone() |
| 897 | .context("Failed to get TAP interface from ParcelFileDescriptor") |
| 898 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?, |
| 899 | )) |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 900 | } else { |
| 901 | None |
| 902 | }; |
Mu-Le Lee | b2d5a31 | 2024-06-05 10:52:47 +0800 | [diff] [blame] | 903 | |
| 904 | let audio_config = if cfg!(paravirtualized_devices) { |
| 905 | config.audioConfig.as_ref().map(AudioConfig::new) |
| 906 | } else { |
| 907 | None |
| 908 | }; |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 909 | |
Elie Kheirallah | 29d7291 | 2024-08-07 20:17:26 +0000 | [diff] [blame] | 910 | let usb_config = config |
| 911 | .usbConfig |
| 912 | .as_ref() |
| 913 | .map(UsbConfig::new) |
| 914 | .unwrap_or(Ok(UsbConfig { controller: false })) |
| 915 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?; |
| 916 | |
Pierre-Clément Tosi | 3d70d46 | 2025-01-07 16:03:24 +0000 | [diff] [blame] | 917 | let detect_hangup = is_app_config && gdb_port.is_none(); |
| 918 | |
Frederick Mayle | 31cc5b2 | 2024-12-19 14:42:43 -0800 | [diff] [blame] | 919 | let custom_memory_backing_files = config |
| 920 | .customMemoryBackingFiles |
| 921 | .iter() |
| 922 | .map(|memory_backing_file| { |
| 923 | Ok(( |
| 924 | clone_file( |
| 925 | memory_backing_file |
| 926 | .file |
| 927 | .as_ref() |
| 928 | .context("missing CustomMemoryBackingFile FD") |
| 929 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?, |
| 930 | )? |
| 931 | .into(), |
| 932 | memory_backing_file.rangeStart as u64, |
| 933 | memory_backing_file.size as u64, |
| 934 | )) |
| 935 | }) |
| 936 | .collect::<binder::Result<_>>()?; |
| 937 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 938 | // Actually start the VM. |
| 939 | let crosvm_config = CrosvmConfig { |
| 940 | cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 941 | name: config.name.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 942 | bootloader: maybe_clone_file(&config.bootloader)?, |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 943 | kernel, |
| 944 | initrd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 945 | disks, |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 946 | shared_paths, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 947 | params: config.params.to_owned(), |
| 948 | protected: *is_protected, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 949 | debug_config, |
Frederick Mayle | 68d06e7 | 2024-07-12 17:18:11 -0700 | [diff] [blame] | 950 | memory_mib: config |
| 951 | .memoryMib |
| 952 | .try_into() |
| 953 | .ok() |
| 954 | .and_then(NonZeroU32::new) |
| 955 | .unwrap_or(NonZeroU32::new(256).unwrap()), |
Frederick Mayle | 384f5b5 | 2024-12-06 16:23:23 -0800 | [diff] [blame] | 956 | swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new), |
Elie Kheirallah | b4b2f24 | 2025-01-23 03:38:07 +0000 | [diff] [blame] | 957 | cpus: config.cpuOptions.clone(), |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 958 | console_out_fd, |
| 959 | console_in_fd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 960 | log_fd, |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 961 | ramdump, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 962 | indirect_files, |
| 963 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Pierre-Clément Tosi | 3d70d46 | 2025-01-07 16:03:24 +0000 | [diff] [blame] | 964 | detect_hangup, |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 965 | gdb_port, |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 966 | vfio_devices, |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 967 | dtbo, |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 968 | device_tree_overlays, |
Jeongik Cha | 1df1c03 | 2024-04-03 16:03:12 +0900 | [diff] [blame] | 969 | display_config, |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 970 | input_device_options, |
Vincent Donnefort | 538a2c6 | 2024-03-20 16:01:10 +0000 | [diff] [blame] | 971 | hugepages: config.hugePages, |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 972 | tap, |
Yi-Yo Chiang | 8dd3255 | 2024-05-22 19:38:16 +0800 | [diff] [blame] | 973 | console_input_device: config.consoleInputDevice.clone(), |
David Dai | 23cff71 | 2024-06-13 19:23:45 +0000 | [diff] [blame] | 974 | boost_uclamp: config.boostUclamp, |
Jason Macnak | ea7b0fa | 2024-05-08 17:02:44 -0700 | [diff] [blame] | 975 | gpu_config, |
Mu-Le Lee | b2d5a31 | 2024-06-05 10:52:47 +0800 | [diff] [blame] | 976 | audio_config, |
Frederick Mayle | cc4e2d7 | 2024-12-06 16:54:40 -0800 | [diff] [blame] | 977 | balloon: config.balloon, |
Elie Kheirallah | 29d7291 | 2024-08-07 20:17:26 +0000 | [diff] [blame] | 978 | usb_config, |
Elie Kheirallah | 5c807a2 | 2024-09-23 20:40:42 +0000 | [diff] [blame] | 979 | dump_dt_fd, |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 980 | enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod, |
| 981 | instance_id, |
Frederick Mayle | 31cc5b2 | 2024-12-19 14:42:43 -0800 | [diff] [blame] | 982 | custom_memory_backing_files, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 983 | }; |
| 984 | let instance = Arc::new( |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 985 | VmInstance::new( |
| 986 | crosvm_config, |
| 987 | temporary_directory, |
| 988 | requester_uid, |
| 989 | requester_debug_pid, |
| 990 | vm_context, |
| 991 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 992 | .with_context(|| format!("Failed to create VM with config {:?}", config)) |
| 993 | .with_log() |
| 994 | .or_service_specific_exception(-1)?, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 995 | ); |
| 996 | state.add_vm(Arc::downgrade(&instance)); |
| 997 | Ok(VirtualMachine::create(instance)) |
| 998 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 999 | } |
| 1000 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1001 | /// Returns whether a VM config represents a "custom" virtual machine, which requires the |
| 1002 | /// USE_CUSTOM_VIRTUAL_MACHINE. |
| 1003 | fn is_custom_config(config: &VirtualMachineConfig) -> bool { |
| 1004 | match config { |
| 1005 | // Any raw (non-Microdroid) VM is considered custom. |
| 1006 | VirtualMachineConfig::RawConfig(_) => true, |
| 1007 | VirtualMachineConfig::AppConfig(config) => { |
| 1008 | // Some features are reserved for platform apps only, even when using |
| 1009 | // VirtualMachineAppConfig. Almost all of these features are grouped in the |
| 1010 | // CustomConfig struct: |
| 1011 | // - controlling CPUs; |
| 1012 | // - gdbPort is set, meaning that crosvm will start a gdb server; |
| 1013 | // - using anything other than the default kernel; |
| 1014 | // - specifying devices to be assigned. |
| 1015 | if config.customConfig.is_some() { |
| 1016 | true |
| 1017 | } else { |
| 1018 | // Additional custom features not included in CustomConfig: |
| 1019 | // - specifying a config file; |
Alan Stokes | 736f682 | 2024-02-16 16:08:00 +0000 | [diff] [blame] | 1020 | // - specifying extra APKs; |
| 1021 | // - specifying an OS other than Microdroid. |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1022 | (match &config.payload { |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1023 | Payload::ConfigPath(_) => true, |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1024 | Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(), |
| 1025 | }) || config.osName != MICRODROID_OS_NAME |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1026 | } |
| 1027 | } |
| 1028 | } |
| 1029 | } |
| 1030 | |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 1031 | /// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid |
| 1032 | /// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid |
| 1033 | /// VM. To handle the exceptional case, we use name as a second criteria; if the name is |
| 1034 | /// "microdroid" we run VirtualMachineService |
| 1035 | fn requires_vm_service(config: &VirtualMachineConfig) -> bool { |
| 1036 | match config { |
| 1037 | VirtualMachineConfig::AppConfig(_) => true, |
| 1038 | VirtualMachineConfig::RawConfig(config) => config.name == "microdroid", |
| 1039 | } |
| 1040 | } |
| 1041 | |
Seungjae Yoo | 14e6018 | 2024-02-21 13:28:31 +0900 | [diff] [blame] | 1042 | fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> { |
| 1043 | let VirtualMachineConfig::AppConfig(config) = config else { |
| 1044 | return Ok(None); |
| 1045 | }; |
| 1046 | let Some(custom_config) = &config.customConfig else { |
| 1047 | return Ok(None); |
| 1048 | }; |
| 1049 | let Some(file) = custom_config.vendorImage.as_ref() else { |
| 1050 | return Ok(None); |
| 1051 | }; |
| 1052 | |
| 1053 | let file = clone_file(file)?; |
| 1054 | let size = |
| 1055 | file.metadata().context("Failed to get metadata from microdroid vendor image")?.len(); |
| 1056 | let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size) |
| 1057 | .context("Failed to get vbmeta from microdroid-vendor.img")?; |
| 1058 | |
| 1059 | for descriptor in vbmeta.descriptors()?.iter() { |
| 1060 | if let vbmeta::Descriptor::Hashtree(_) = descriptor { |
| 1061 | let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest()); |
| 1062 | return Ok(Some(root_digest.as_bytes().to_vec())); |
| 1063 | } |
| 1064 | } |
| 1065 | Err(anyhow!("No hashtree digest is extracted from microdroid vendor image")) |
| 1066 | } |
| 1067 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1068 | fn maybe_create_reference_dt_overlay( |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1069 | config: &VirtualMachineConfig, |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 1070 | instance_id: &[u8; 64], |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1071 | temporary_directory: &Path, |
| 1072 | ) -> binder::Result<Option<File>> { |
| 1073 | // Currently, VirtMgr adds the host copy of reference DT & untrusted properties |
| 1074 | // (e.g. instance-id) |
| 1075 | let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH); |
| 1076 | let host_ref_dt = if host_ref_dt.exists() |
| 1077 | && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some() |
| 1078 | { |
| 1079 | Some(host_ref_dt) |
| 1080 | } else { |
| 1081 | warn!("VM reference DT doesn't exist in host DT"); |
| 1082 | None |
| 1083 | }; |
| 1084 | |
| 1085 | let vendor_hashtree_digest = extract_vendor_hashtree_digest(config) |
| 1086 | .context("Failed to extract vendor hashtree digest") |
| 1087 | .or_service_specific_exception(-1)?; |
| 1088 | |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1089 | let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest { |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1090 | info!( |
| 1091 | "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \ |
| 1092 | match the trusted digest in the pvmfw config, causing the VM to fail to start." |
| 1093 | ); |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1094 | vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())] |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1095 | } else { |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1096 | vec![] |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1097 | }; |
| 1098 | |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1099 | let key_material; |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1100 | let mut untrusted_props = Vec::with_capacity(2); |
| 1101 | if cfg!(llpvm_changes) { |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1102 | untrusted_props.push((c"instance-id", &instance_id[..])); |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1103 | let want_updatable = extract_want_updatable(config); |
| 1104 | if want_updatable && is_secretkeeper_supported() { |
| 1105 | // Let guest know that it can defer rollback protection to Secretkeeper by setting |
| 1106 | // an empty property in untrusted node in DT. This enables Updatable VMs. |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1107 | untrusted_props.push((c"defer-rollback-protection", &[])); |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1108 | let sk: Strong<dyn ISecretkeeper> = |
| 1109 | binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?; |
| 1110 | if sk.getInterfaceVersion()? >= 2 { |
| 1111 | let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?; |
| 1112 | key_material = keyMaterial; |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1113 | trusted_props.push((c"secretkeeper_public_key", key_material.as_slice())); |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1114 | } |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | let device_tree_overlay = if host_ref_dt.is_some() |
| 1119 | || !untrusted_props.is_empty() |
| 1120 | || !trusted_props.is_empty() |
| 1121 | { |
| 1122 | let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH); |
| 1123 | let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE]; |
| 1124 | let fdt = |
| 1125 | create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props) |
| 1126 | .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}")) |
| 1127 | .or_service_specific_exception(-1)?; |
| 1128 | fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?; |
| 1129 | Some(File::open(dt_output).or_service_specific_exception(-1)?) |
| 1130 | } else { |
| 1131 | None |
| 1132 | }; |
| 1133 | Ok(device_tree_overlay) |
| 1134 | } |
| 1135 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1136 | fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> { |
| 1137 | let VirtualMachineConfig::RawConfig(config) = config else { |
| 1138 | return None; |
| 1139 | }; |
| 1140 | match &config.devices { |
| 1141 | AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(), |
| 1142 | _ => None, |
| 1143 | } |
| 1144 | } |
| 1145 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 1146 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1147 | let file = OpenOptions::new() |
| 1148 | .create_new(true) |
| 1149 | .read(true) |
| 1150 | .write(true) |
| 1151 | .open(zero_filler_path) |
| 1152 | .with_context(|| "Failed to create zero.img")?; |
| 1153 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 1154 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1155 | } |
| 1156 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1157 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 1158 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 1159 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 1160 | part.flush() |
| 1161 | } |
| 1162 | |
| 1163 | fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> { |
| 1164 | part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?; |
| 1165 | part.flush() |
| 1166 | } |
| 1167 | |
| 1168 | fn round_up(input: u64, granularity: u64) -> u64 { |
| 1169 | if granularity == 0 { |
| 1170 | return input; |
| 1171 | } |
| 1172 | // If the input is absurdly large we round down instead of up; it's going to fail anyway. |
| 1173 | let result = input.checked_add(granularity - 1).unwrap_or(input); |
| 1174 | (result / granularity) * granularity |
| 1175 | } |
| 1176 | |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 1177 | fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> { |
| 1178 | Ok(match input_device { |
| 1179 | InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch { |
| 1180 | file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1181 | height: u32::try_from(single_touch.height)?, |
| 1182 | width: u32::try_from(single_touch.width)?, |
| 1183 | name: if !single_touch.name.is_empty() { |
| 1184 | Some(single_touch.name.clone()) |
| 1185 | } else { |
| 1186 | None |
| 1187 | }, |
| 1188 | }, |
| 1189 | InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file( |
| 1190 | evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1191 | )?), |
Jeongik Cha | 985b640 | 2024-04-15 18:13:00 +0900 | [diff] [blame] | 1192 | InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file( |
| 1193 | keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1194 | )?), |
Jeongik Cha | 343894e | 2024-05-17 20:39:31 +0900 | [diff] [blame] | 1195 | InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file( |
| 1196 | mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1197 | )?), |
Jiyong Park | 6c1b9f0 | 2024-07-05 16:21:10 +0900 | [diff] [blame] | 1198 | InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file( |
| 1199 | switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1200 | )?), |
Jeongik Cha | 112a268 | 2024-07-09 12:28:45 +0900 | [diff] [blame] | 1201 | InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad { |
| 1202 | file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1203 | height: u32::try_from(trackpad.height)?, |
| 1204 | width: u32::try_from(trackpad.width)?, |
| 1205 | name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None }, |
| 1206 | }, |
Jeongik Cha | 1049491 | 2024-07-16 11:19:50 +0900 | [diff] [blame] | 1207 | InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch { |
| 1208 | file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1209 | height: u32::try_from(multi_touch.height)?, |
| 1210 | width: u32::try_from(multi_touch.width)?, |
| 1211 | name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None }, |
| 1212 | }, |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 1213 | }) |
| 1214 | } |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 1215 | |
| 1216 | fn assemble_shared_paths( |
| 1217 | shared_paths: &[SharedPath], |
| 1218 | temporary_directory: &Path, |
| 1219 | ) -> Result<Vec<SharedPathConfig>, Status> { |
| 1220 | if shared_paths.is_empty() { |
| 1221 | return Ok(Vec::new()); // Return an empty vector if shared_paths is empty |
| 1222 | } |
| 1223 | |
| 1224 | shared_paths |
| 1225 | .iter() |
| 1226 | .map(|path| { |
| 1227 | Ok(SharedPathConfig { |
| 1228 | path: path.sharedPath.clone(), |
| 1229 | host_uid: path.hostUid, |
| 1230 | host_gid: path.hostGid, |
| 1231 | guest_uid: path.guestUid, |
| 1232 | guest_gid: path.guestGid, |
| 1233 | mask: path.mask, |
| 1234 | tag: path.tag.clone(), |
Akilesh Kailash | c9aa068 | 2024-11-25 10:27:24 -0800 | [diff] [blame] | 1235 | socket_path: temporary_directory |
| 1236 | .join(&path.socketPath) |
| 1237 | .to_string_lossy() |
| 1238 | .to_string(), |
| 1239 | socket_fd: maybe_clone_file(&path.socketFd)?, |
| 1240 | app_domain: path.appDomain, |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 1241 | }) |
| 1242 | }) |
| 1243 | .collect() |
| 1244 | } |
| 1245 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1246 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 1247 | /// |
| 1248 | /// This may involve assembling a composite disk from a set of partition images. |
| 1249 | fn assemble_disk_image( |
| 1250 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1251 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1252 | temporary_directory: &Path, |
| 1253 | next_temporary_image_id: &mut u64, |
| 1254 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1255 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1256 | let image = if !disk.partitions.is_empty() { |
| 1257 | if disk.image.is_some() { |
| 1258 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1259 | return Err(anyhow!("DiskImage contains both image and partitions")) |
| 1260 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1261 | } |
| 1262 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1263 | let composite_image_filenames = |
| 1264 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 1265 | let (image, partition_files) = make_composite_image( |
| 1266 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1267 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1268 | &composite_image_filenames.composite, |
| 1269 | &composite_image_filenames.header, |
| 1270 | &composite_image_filenames.footer, |
| 1271 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1272 | .with_context(|| format!("Failed to make composite disk image with config {:?}", disk)) |
| 1273 | .with_log() |
| 1274 | .or_service_specific_exception(-1)?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1275 | |
| 1276 | // Pass the file descriptors for the various partition files to crosvm when it |
| 1277 | // is run. |
| 1278 | indirect_files.extend(partition_files); |
| 1279 | |
| 1280 | image |
| 1281 | } else if let Some(image) = &disk.image { |
| 1282 | clone_file(image)? |
| 1283 | } else { |
| 1284 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1285 | return Err(anyhow!("DiskImage didn't contain image or partitions.")) |
| 1286 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1287 | }; |
| 1288 | |
| 1289 | Ok(DiskFile { image, writable: disk.writable }) |
| 1290 | } |
| 1291 | |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 1292 | fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) { |
| 1293 | if let Some(ref mut params) = vm_config.params { |
| 1294 | params.push(' '); |
| 1295 | params.push_str(param) |
| 1296 | } else { |
| 1297 | vm_config.params = Some(param.to_owned()) |
| 1298 | } |
| 1299 | } |
| 1300 | |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 1301 | fn extract_os_name_from_config_path(config: &Path) -> Option<String> { |
| 1302 | if config.extension()?.to_str()? != "json" { |
| 1303 | return None; |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1304 | } |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 1305 | |
| 1306 | Some(config.with_extension("").file_name()?.to_str()?.to_owned()) |
| 1307 | } |
| 1308 | |
| 1309 | fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> { |
| 1310 | let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?; |
| 1311 | let os_names = |
| 1312 | configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>(); |
| 1313 | |
| 1314 | Ok(os_names) |
| 1315 | } |
| 1316 | |
| 1317 | fn get_supported_os_names() -> Result<HashSet<String>> { |
| 1318 | if !cfg!(vendor_modules) { |
| 1319 | return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect()); |
| 1320 | } |
| 1321 | |
| 1322 | extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json") |
| 1323 | } |
| 1324 | |
| 1325 | fn is_valid_os(os_name: &str) -> bool { |
| 1326 | SUPPORTED_OS_NAMES.contains(os_name) |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1327 | } |
| 1328 | |
Nikita Ioffe | 2cb75cf | 2024-06-04 16:43:56 +0000 | [diff] [blame] | 1329 | fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool { |
| 1330 | if !cfg!(vendor_modules) { |
| 1331 | return false; |
| 1332 | } |
| 1333 | match config { |
| 1334 | VirtualMachineConfig::RawConfig(_) => false, |
| 1335 | VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"), |
| 1336 | } |
| 1337 | } |
| 1338 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1339 | fn load_app_config( |
| 1340 | config: &VirtualMachineAppConfig, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1341 | debug_config: &DebugConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1342 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 1343 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1344 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 1345 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 1346 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1347 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 1348 | let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() { |
| 1349 | Some(clone_file(file)?) |
| 1350 | } else { |
| 1351 | None |
| 1352 | }; |
| 1353 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1354 | let vm_payload_config; |
| 1355 | let extra_apk_files: Vec<_>; |
| 1356 | match &config.payload { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1357 | Payload::ConfigPath(config_path) => { |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1358 | vm_payload_config = |
| 1359 | load_vm_payload_config_from_file(&apk_file, config_path.as_str()) |
| 1360 | .with_context(|| format!("Couldn't read config from {}", config_path))?; |
| 1361 | extra_apk_files = vm_payload_config |
| 1362 | .extra_apks |
| 1363 | .iter() |
| 1364 | .enumerate() |
| 1365 | .map(|(i, apk)| { |
| 1366 | File::open(PathBuf::from(&apk.path)) |
| 1367 | .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path)) |
| 1368 | }) |
| 1369 | .collect::<Result<_>>()?; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1370 | } |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1371 | Payload::PayloadConfig(payload_config) => { |
| 1372 | vm_payload_config = create_vm_payload_config(payload_config)?; |
| 1373 | extra_apk_files = |
| 1374 | payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?; |
| 1375 | } |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1376 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1377 | |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1378 | let payload_config_os = vm_payload_config.os.name.as_str(); |
| 1379 | if !payload_config_os.is_empty() && payload_config_os != "microdroid" { |
| 1380 | bail!("'os' in payload config is deprecated"); |
| 1381 | } |
| 1382 | |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1383 | // For now, the only supported OS is Microdroid and Microdroid GKI |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1384 | let os_name = config.osName.as_str(); |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1385 | if !is_valid_os(os_name) { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1386 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1387 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1388 | |
| 1389 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 1390 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1391 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 1392 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1393 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1394 | |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 1395 | if let Some(custom_config) = &config.customConfig { |
| 1396 | if let Some(file) = custom_config.customKernelImage.as_ref() { |
| 1397 | vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?)) |
| 1398 | } |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 1399 | vm_config.gdbPort = custom_config.gdbPort; |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 1400 | |
| 1401 | if let Some(file) = custom_config.vendorImage.as_ref() { |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 1402 | add_microdroid_vendor_image(clone_file(file)?, &mut vm_config); |
Pechetty Sravani (xWF) | faabfbd | 2024-09-24 15:27:48 +0000 | [diff] [blame] | 1403 | append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config) |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 1404 | } |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 1405 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1406 | vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone()); |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 1407 | vm_config.networkSupported = custom_config.networkSupported; |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 1408 | |
| 1409 | for param in custom_config.extraKernelCmdlineParams.iter() { |
| 1410 | append_kernel_param(param, &mut vm_config); |
| 1411 | } |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 1412 | |
| 1413 | vm_config.teeServices.clone_from(&custom_config.teeServices); |
Nikita Ioffe | 26c35ed | 2023-06-05 17:49:08 +0100 | [diff] [blame] | 1414 | } |
| 1415 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 1416 | if config.memoryMib > 0 { |
| 1417 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 1418 | } |
| 1419 | |
Chris Wailes | 6177c66 | 2024-05-09 14:37:44 -0700 | [diff] [blame] | 1420 | vm_config.name.clone_from(&config.name); |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 1421 | vm_config.protectedVm = config.protectedVm; |
Elie Kheirallah | b4b2f24 | 2025-01-23 03:38:07 +0000 | [diff] [blame] | 1422 | vm_config.cpuOptions = config.cpuOptions.clone(); |
Vincent Donnefort | 538a2c6 | 2024-03-20 16:01:10 +0000 | [diff] [blame] | 1423 | vm_config.hugePages = config.hugePages || vm_payload_config.hugepages; |
David Dai | 23cff71 | 2024-06-13 19:23:45 +0000 | [diff] [blame] | 1424 | vm_config.boostUclamp = config.boostUclamp; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 1425 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 1426 | // Microdroid takes additional init ramdisk & (optionally) storage image |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1427 | add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?; |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 1428 | |
| 1429 | // Include Microdroid payload disk (contains apks, idsigs) in vm config |
| 1430 | add_microdroid_payload_images( |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1431 | config, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1432 | debug_config, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1433 | temporary_directory, |
| 1434 | apk_file, |
| 1435 | idsig_file, |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1436 | extra_apk_files, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1437 | &vm_payload_config, |
| 1438 | &mut vm_config, |
| 1439 | )?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1440 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1441 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1442 | } |
| 1443 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1444 | fn check_partition_for_file( |
| 1445 | fd: &ParcelFileDescriptor, |
| 1446 | calling_partition: CallingPartition, |
| 1447 | ) -> Result<()> { |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1448 | let path = format!("/proc/self/fd/{}", fd.as_raw_fd()); |
| 1449 | let link = fs::read_link(&path).context(format!("can't read_link {path}"))?; |
| 1450 | |
| 1451 | // microdroid vendor image is OK |
| 1452 | if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img") |
| 1453 | { |
| 1454 | return Ok(()); |
| 1455 | } |
| 1456 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1457 | let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm"); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1458 | let is_caller_vendor = |
| 1459 | calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm; |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1460 | |
| 1461 | if is_fd_vendor != is_caller_vendor { |
| 1462 | bail!("{} can't be used for VM client in {calling_partition}", link.display()); |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1463 | } |
| 1464 | |
| 1465 | Ok(()) |
| 1466 | } |
| 1467 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1468 | fn check_partitions_for_files( |
| 1469 | config: &VirtualMachineRawConfig, |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1470 | calling_partition: CallingPartition, |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1471 | ) -> Result<()> { |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1472 | config |
| 1473 | .disks |
| 1474 | .iter() |
| 1475 | .flat_map(|disk| disk.partitions.iter()) |
| 1476 | .filter_map(|partition| partition.image.as_ref()) |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1477 | .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1478 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1479 | config |
| 1480 | .disks |
| 1481 | .iter() |
| 1482 | .filter_map(|disk| disk.image.as_ref()) |
| 1483 | .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?; |
| 1484 | |
| 1485 | config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
| 1486 | config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
| 1487 | config |
| 1488 | .bootloader |
| 1489 | .as_ref() |
| 1490 | .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1491 | |
| 1492 | Ok(()) |
| 1493 | } |
| 1494 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1495 | fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> { |
| 1496 | let mut apk_zip = ZipArchive::new(apk_file)?; |
| 1497 | let config_file = apk_zip.by_name(config_path)?; |
| 1498 | Ok(serde_json::from_reader(config_file)?) |
| 1499 | } |
| 1500 | |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 1501 | fn create_vm_payload_config( |
| 1502 | payload_config: &VirtualMachinePayloadConfig, |
| 1503 | ) -> Result<VmPayloadConfig> { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1504 | // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit |
| 1505 | // parameters we've been given. Microdroid will do something equivalent inside the VM using the |
| 1506 | // payload config that we send it via the metadata file. |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 1507 | |
| 1508 | let payload_binary_name = &payload_config.payloadBinaryName; |
| 1509 | if payload_binary_name.contains('/') { |
| 1510 | bail!("Payload binary name must not specify a path: {payload_binary_name}"); |
| 1511 | } |
| 1512 | |
| 1513 | let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() }; |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1514 | |
| 1515 | // The VM only cares about how many there are, these names are actually ignored. |
| 1516 | let extra_apk_count = payload_config.extraApks.len(); |
| 1517 | let extra_apks = |
| 1518 | (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect(); |
| 1519 | |
Nikita Ioffe | 901083f | 2025-01-20 01:54:28 +0000 | [diff] [blame] | 1520 | if check_use_relaxed_microdroid_rollback_protection().is_ok() { |
| 1521 | // The only payload delivered via Mainline module in this release requires |
| 1522 | // com.android.i18n apex. However, we are past all the reasonable deadlines to add new |
| 1523 | // APIs, so we use the fact that the payload is granted |
| 1524 | // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include |
| 1525 | // com.android.i18n APEX. |
| 1526 | // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to |
| 1527 | // Microdroid pVMs. |
| 1528 | let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }]; |
| 1529 | Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() }) |
| 1530 | } else { |
| 1531 | Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() }) |
| 1532 | } |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1533 | } |
| 1534 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1535 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1536 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1537 | temporary_directory: &Path, |
| 1538 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1539 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1540 | let id = *next_temporary_image_id; |
| 1541 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1542 | CompositeImageFilenames { |
| 1543 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 1544 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 1545 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 1546 | } |
| 1547 | } |
| 1548 | |
| 1549 | /// Filenames for a composite disk image, including header and footer partitions. |
| 1550 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 1551 | struct CompositeImageFilenames { |
| 1552 | /// The composite disk image itself. |
| 1553 | composite: PathBuf, |
| 1554 | /// The header partition image. |
| 1555 | header: PathBuf, |
| 1556 | /// The footer partition image. |
| 1557 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1558 | } |
| 1559 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1560 | /// Checks whether the caller has a specific permission |
| 1561 | fn check_permission(perm: &str) -> binder::Result<()> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 1562 | if cfg!(early) { |
| 1563 | // Skip permission check for early VMs, in favor of SELinux |
| 1564 | return Ok(()); |
| 1565 | } |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 1566 | let calling_pid = get_calling_pid(); |
| 1567 | let calling_uid = get_calling_uid(); |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1568 | // Root can do anything |
| 1569 | if calling_uid == 0 { |
| 1570 | return Ok(()); |
| 1571 | } |
| 1572 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
Frederick Mayle | b2a0287 | 2024-05-08 13:35:12 -0700 | [diff] [blame] | 1573 | binder::wait_for_interface("permission")?; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1574 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1575 | Ok(()) |
| 1576 | } else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1577 | Err(anyhow!("does not have the {} permission", perm)) |
| 1578 | .or_binder_exception(ExceptionCode::SECURITY) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1579 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1580 | } |
| 1581 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1582 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 1583 | fn check_manage_access() -> binder::Result<()> { |
| 1584 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 1585 | } |
| 1586 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 1587 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 1588 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 1589 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 1590 | } |
| 1591 | |
Nikita Ioffe | 901083f | 2025-01-20 01:54:28 +0000 | [diff] [blame] | 1592 | /// Check whether the caller of the current binder method is allowed to use relaxed microdroid |
| 1593 | /// rollback protection schema. |
| 1594 | fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> { |
| 1595 | check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION") |
| 1596 | } |
| 1597 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1598 | /// Return whether a partition is exempt from selinux label checks, because we know that it does |
| 1599 | /// 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] | 1600 | fn is_safe_app_partition(label: &str) -> bool { |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 1601 | // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1602 | label == "vm-instance" |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 1603 | || label == "encryptedstore" |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1604 | || label == "microdroid-apk-idsig" |
| 1605 | || label == "payload-metadata" |
| 1606 | || label.starts_with("extra-idsig-") |
| 1607 | } |
| 1608 | |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 1609 | /// Returns whether a partition with the given label is safe for a raw config VM. |
| 1610 | fn is_safe_raw_partition(label: &str) -> bool { |
| 1611 | label == "vm-instance" |
| 1612 | } |
| 1613 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1614 | /// Check that a file SELinux label is acceptable. |
| 1615 | /// |
| 1616 | /// We only want to allow code in a VM to be sourced from places that apps, and the |
Seungjae Yoo | 2b74c44 | 2023-11-15 18:05:07 +0900 | [diff] [blame] | 1617 | /// system or vendor, do not have write access to. |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1618 | /// |
| 1619 | /// Note that sepolicy must also grant read access for these types to both virtualization |
| 1620 | /// service and crosvm. |
| 1621 | /// |
| 1622 | /// App private data files are deliberately excluded, to avoid arbitrary payloads being run on |
| 1623 | /// user devices (W^X). |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1624 | fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1625 | match context.selinux_type()? { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1626 | | "apk_data_file" // APKs of an installed app |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1627 | | "shell_data_file" // test files created via adb shell |
Alan Stokes | fe4bb0c | 2023-03-20 14:15:36 +0000 | [diff] [blame] | 1628 | | "staging_data_file" // updated/staged APEX images |
| 1629 | | "system_file" // immutable dm-verity protected partition |
| 1630 | | "virtualizationservice_data_file" // files created by VS / VirtMgr |
Seungjae Yoo | 2b74c44 | 2023-11-15 18:05:07 +0900 | [diff] [blame] | 1631 | | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*) |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1632 | => Ok(()), |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1633 | // It is difficult to require specific label types for vendor initiated VM's files, so we |
| 1634 | // allow anything with a vendor prefix. |
| 1635 | t if calling_partition == CallingPartition::Vendor && t.starts_with("vendor_") => Ok(()), |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1636 | _ => bail!("Label {} is not allowed", context), |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 1637 | } |
| 1638 | } |
| 1639 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1640 | fn check_label_for_partition( |
| 1641 | partition: &Partition, |
| 1642 | calling_partition: CallingPartition, |
| 1643 | ) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1644 | let file = partition.image.as_ref().unwrap().as_ref(); |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1645 | check_label_is_allowed(&getfilecon(file)?, calling_partition) |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1646 | .with_context(|| format!("Partition {} invalid", &partition.label)) |
| 1647 | } |
| 1648 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1649 | fn check_label_for_kernel_files( |
| 1650 | kernel: &Option<File>, |
| 1651 | initrd: &Option<File>, |
| 1652 | calling_partition: CallingPartition, |
| 1653 | ) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1654 | if let Some(f) = kernel { |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1655 | check_label_for_file(f, "kernel", calling_partition)?; |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1656 | } |
| 1657 | if let Some(f) = initrd { |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1658 | check_label_for_file(f, "initrd", calling_partition)?; |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1659 | } |
| 1660 | Ok(()) |
| 1661 | } |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1662 | fn check_label_for_file( |
Frederick Mayle | 9539fb5 | 2025-02-13 13:08:15 -0800 | [diff] [blame] | 1663 | file: &impl AsRawFd, |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1664 | name: &str, |
| 1665 | calling_partition: CallingPartition, |
| 1666 | ) -> Result<()> { |
| 1667 | check_label_is_allowed(&getfilecon(file)?, calling_partition) |
| 1668 | .with_context(|| format!("{} file invalid", name)) |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1669 | } |
| 1670 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1671 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 1672 | #[derive(Debug)] |
| 1673 | struct VirtualMachine { |
| 1674 | instance: Arc<VmInstance>, |
| 1675 | } |
| 1676 | |
| 1677 | impl VirtualMachine { |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1678 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 1679 | BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1680 | } |
| 1681 | } |
| 1682 | |
| 1683 | impl Interface for VirtualMachine {} |
| 1684 | |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1685 | impl IVirtualMachine::IVirtualMachine for VirtualMachine { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1686 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1687 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1688 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1689 | Ok(self.instance.cid as i32) |
| 1690 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1691 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1692 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1693 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1694 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1695 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1696 | } |
| 1697 | |
| 1698 | fn registerCallback( |
| 1699 | &self, |
| 1700 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 1701 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1702 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1703 | // others. |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1704 | |
| 1705 | // Only register callback if it may be notified. |
| 1706 | // This also ensures no cyclic reference between callback and VmInstance after VM is died. |
| 1707 | let vm_state = self.instance.vm_state.lock().unwrap(); |
| 1708 | if matches!(*vm_state, VmState::Dead) { |
| 1709 | warn!("Ignoring registerCallback() after VM is died"); |
| 1710 | } else { |
| 1711 | self.instance.callbacks.add(callback.clone()); |
| 1712 | } |
| 1713 | drop(vm_state); |
| 1714 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1715 | Ok(()) |
| 1716 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1717 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1718 | fn start(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1719 | self.instance |
| 1720 | .start() |
| 1721 | .with_context(|| format!("Error starting VM with CID {}", self.instance.cid)) |
| 1722 | .with_log() |
| 1723 | .or_service_specific_exception(-1) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1724 | } |
| 1725 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1726 | fn stop(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1727 | self.instance |
| 1728 | .kill() |
| 1729 | .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid)) |
| 1730 | .with_log() |
| 1731 | .or_service_specific_exception(-1) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1732 | } |
| 1733 | |
Keir Fraser | 48221ba | 2024-07-12 14:05:02 +0000 | [diff] [blame] | 1734 | fn getMemoryBalloon(&self) -> binder::Result<i64> { |
| 1735 | let balloon = self |
| 1736 | .instance |
| 1737 | .get_memory_balloon() |
| 1738 | .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid)) |
| 1739 | .with_log() |
| 1740 | .or_service_specific_exception(-1)?; |
| 1741 | Ok(balloon.try_into().unwrap()) |
| 1742 | } |
| 1743 | |
| 1744 | fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1745 | self.instance |
Keir Fraser | 48221ba | 2024-07-12 14:05:02 +0000 | [diff] [blame] | 1746 | .set_memory_balloon(num_bytes.try_into().unwrap()) |
| 1747 | .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid)) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1748 | .with_log() |
| 1749 | .or_service_specific_exception(-1) |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 1750 | } |
| 1751 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1752 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1753 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1754 | return Err(Status::new_service_specific_error_str( |
| 1755 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1756 | Some("Virtual Machine is not running"), |
| 1757 | )); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1758 | } |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 1759 | let port = port as u32; |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1760 | if port < VSOCK_PRIV_PORT_MAX { |
| 1761 | return Err(Status::new_service_specific_error_str( |
| 1762 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1763 | Some("Can't connect to privileged port {port}"), |
| 1764 | )); |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 1765 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1766 | let stream = VsockStream::connect_with_cid_port(self.instance.cid, port) |
| 1767 | .context("Failed to connect") |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1768 | .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?; |
Jiyong Park | af63d1c | 2024-09-04 16:15:42 +0900 | [diff] [blame] | 1769 | Ok(vsock_stream_to_pfd(stream)) |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1770 | } |
Yi-Yo Chiang | 2fbf0da | 2024-06-14 22:56:56 +0800 | [diff] [blame] | 1771 | |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1772 | fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> { |
| 1773 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
| 1774 | return Err(Status::new_service_specific_error_str( |
| 1775 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1776 | Some("Virtual Machine is not running"), |
| 1777 | )); |
| 1778 | } |
| 1779 | let port = port as u32; |
| 1780 | if port < VSOCK_PRIV_PORT_MAX { |
| 1781 | return Err(Status::new_service_specific_error_str( |
| 1782 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1783 | Some("Can't connect to privileged port {port}"), |
| 1784 | )); |
| 1785 | } |
| 1786 | let cid = self.instance.cid; |
Devin Moore | c8800a1 | 2024-10-17 17:56:18 +0000 | [diff] [blame] | 1787 | let addr = sockaddr_vm { |
| 1788 | svm_family: AF_VSOCK as sa_family_t, |
| 1789 | svm_reserved1: 0, |
| 1790 | svm_port: port, |
| 1791 | svm_cid: cid, |
| 1792 | svm_zero: [0u8; 4], |
| 1793 | }; |
| 1794 | let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr)); |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1795 | let accessor = Accessor::new(name, get_connection_info); |
| 1796 | accessor |
| 1797 | .as_binder() |
| 1798 | .context("The newly created Accessor should always have a binder") |
| 1799 | .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED) |
| 1800 | } |
| 1801 | |
Yi-Yo Chiang | 2fbf0da | 2024-06-14 22:56:56 +0800 | [diff] [blame] | 1802 | fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> { |
| 1803 | self.instance.vm_context.global_context.setHostConsoleName(ptsname) |
| 1804 | } |
Jiyong Park | 23b6739 | 2024-07-04 13:51:42 +0900 | [diff] [blame] | 1805 | |
| 1806 | fn suspend(&self) -> binder::Result<()> { |
| 1807 | self.instance |
| 1808 | .suspend() |
| 1809 | .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid)) |
| 1810 | .with_log() |
| 1811 | .or_service_specific_exception(-1) |
| 1812 | } |
| 1813 | |
| 1814 | fn resume(&self) -> binder::Result<()> { |
| 1815 | self.instance |
| 1816 | .resume() |
| 1817 | .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid)) |
| 1818 | .with_log() |
| 1819 | .or_service_specific_exception(-1) |
| 1820 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1821 | } |
| 1822 | |
| 1823 | impl Drop for VirtualMachine { |
| 1824 | fn drop(&mut self) { |
| 1825 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1826 | if let Err(e) = self.instance.kill() { |
| 1827 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 1828 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1829 | } |
| 1830 | } |
| 1831 | |
| 1832 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 1833 | /// dies. |
| 1834 | #[derive(Debug, Default)] |
| 1835 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 1836 | |
| 1837 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1838 | /// Call all registered callbacks to notify that the payload has started. |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1839 | pub fn notify_payload_started(&self, cid: Cid) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1840 | let callbacks = &*self.0.lock().unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1841 | for callback in callbacks { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1842 | if let Err(e) = callback.onPayloadStarted(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1843 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1844 | } |
| 1845 | } |
| 1846 | } |
| 1847 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1848 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 1849 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 1850 | let callbacks = &*self.0.lock().unwrap(); |
| 1851 | for callback in callbacks { |
| 1852 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1853 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1854 | } |
| 1855 | } |
| 1856 | } |
| 1857 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1858 | /// Call all registered callbacks to notify that the payload has finished. |
| 1859 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 1860 | let callbacks = &*self.0.lock().unwrap(); |
| 1861 | for callback in callbacks { |
| 1862 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1863 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1864 | } |
| 1865 | } |
| 1866 | } |
| 1867 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1868 | /// Call all registered callbacks to say that the VM encountered an error. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1869 | pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1870 | let callbacks = &*self.0.lock().unwrap(); |
| 1871 | for callback in callbacks { |
| 1872 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1873 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1874 | } |
| 1875 | } |
| 1876 | } |
| 1877 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1878 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1879 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1880 | let mut callbacks = self.0.lock().unwrap(); |
| 1881 | for callback in &*callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1882 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1883 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1884 | } |
| 1885 | } |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1886 | |
| 1887 | // Nothing to notify afterward because VM cannot be restarted. |
| 1888 | // Explicitly clear callbacks to prevent potential cyclic references |
| 1889 | // between callback and VmInstance. |
| 1890 | (*callbacks).clear(); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1891 | } |
| 1892 | |
| 1893 | /// Add a new callback to the set. |
| 1894 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 1895 | self.0.lock().unwrap().push(callback); |
| 1896 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1897 | } |
| 1898 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 1899 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 1900 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 1901 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1902 | struct State { |
Alan Stokes | 3e5eec1 | 2023-09-07 12:10:00 +0100 | [diff] [blame] | 1903 | /// The VMs which have been started. When VMs are started a weak reference is added to this |
| 1904 | /// list while a strong reference is returned to the caller over Binder. Once all copies of |
| 1905 | /// the Binder client are dropped the weak reference here will become invalid, and will be |
| 1906 | /// removed from the list opportunistically the next time `add_vm` is called. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1907 | vms: Vec<Weak<VmInstance>>, |
| 1908 | } |
| 1909 | |
| 1910 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1911 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1912 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 1913 | // Attempt to upgrade the weak pointers to strong pointers. |
| 1914 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 1915 | } |
| 1916 | |
| 1917 | /// Add a new VM to the list. |
| 1918 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 1919 | // Garbage collect any entries from the stored list which no longer exist. |
| 1920 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 1921 | |
| 1922 | // Actually add the new VM. |
| 1923 | self.vms.push(vm); |
| 1924 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1925 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1926 | /// Get a VM that corresponds to the given cid |
| 1927 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 1928 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 1929 | } |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 1930 | } |
| 1931 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1932 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 1933 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1934 | match &*instance.vm_state.lock().unwrap() { |
| 1935 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 1936 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1937 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 1938 | PayloadState::Started => VirtualMachineState::STARTED, |
| 1939 | PayloadState::Ready => VirtualMachineState::READY, |
| 1940 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 1941 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1942 | }, |
| 1943 | VmState::Dead => VirtualMachineState::DEAD, |
| 1944 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1945 | } |
| 1946 | } |
| 1947 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1948 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1949 | pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> { |
| 1950 | file.as_ref() |
| 1951 | .try_clone() |
| 1952 | .context("Failed to clone File from ParcelFileDescriptor") |
| 1953 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Andrei Homescu | 11333c6 | 2023-11-09 04:26:39 +0000 | [diff] [blame] | 1954 | .map(File::from) |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1955 | } |
| 1956 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1957 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1958 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> { |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1959 | file.as_ref().map(clone_file).transpose() |
| 1960 | } |
| 1961 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1962 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
Jiyong Park | af63d1c | 2024-09-04 16:15:42 +0900 | [diff] [blame] | 1963 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1964 | // SAFETY: ownership is transferred from stream to f |
| 1965 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1966 | ParcelFileDescriptor::new(f) |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1967 | } |
| 1968 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1969 | /// Parses the platform version requirement string. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1970 | fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> { |
| 1971 | VersionReq::parse(s) |
| 1972 | .with_context(|| format!("Invalid platform version requirement {}", s)) |
| 1973 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1974 | } |
| 1975 | |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1976 | /// Create the empty ramdump file |
| 1977 | fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> { |
| 1978 | // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where |
| 1979 | // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM |
| 1980 | // owner) for readout. |
| 1981 | let ramdump_path = temporary_directory.join("ramdump"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1982 | let ramdump = File::create(ramdump_path) |
| 1983 | .context("Failed to prepare ramdump file") |
| 1984 | .with_log() |
| 1985 | .or_service_specific_exception(-1)?; |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1986 | Ok(ramdump) |
| 1987 | } |
| 1988 | |
Pierre-Clément Tosi | 9515d0f | 2024-04-15 15:58:07 +0100 | [diff] [blame] | 1989 | /// Create the empty device tree dump file |
| 1990 | fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> { |
| 1991 | let path = temporary_directory.join("device_tree.dtb"); |
| 1992 | let file = File::create(path) |
| 1993 | .context("Failed to prepare device tree dump file") |
| 1994 | .with_log() |
| 1995 | .or_service_specific_exception(-1)?; |
| 1996 | Ok(file) |
| 1997 | } |
| 1998 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1999 | fn is_protected(config: &VirtualMachineConfig) -> bool { |
| 2000 | match config { |
| 2001 | VirtualMachineConfig::RawConfig(config) => config.protectedVm, |
| 2002 | VirtualMachineConfig::AppConfig(config) => config.protectedVm, |
| 2003 | } |
| 2004 | } |
| 2005 | |
| 2006 | fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2007 | if is_protected(config) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2008 | return Err(anyhow!("Can't use gdb with protected VMs")) |
| 2009 | .or_binder_exception(ExceptionCode::SECURITY); |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2010 | } |
| 2011 | |
Pierre-Clément Tosi | d3bbe1d | 2024-04-15 18:03:51 +0100 | [diff] [blame] | 2012 | if get_debug_level(config) == Some(DebugLevel::NONE) { |
| 2013 | return Err(anyhow!("Can't use gdb with non-debuggable VMs")) |
| 2014 | .or_binder_exception(ExceptionCode::SECURITY); |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2015 | } |
Pierre-Clément Tosi | d3bbe1d | 2024-04-15 18:03:51 +0100 | [diff] [blame] | 2016 | |
| 2017 | Ok(()) |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2018 | } |
| 2019 | |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 2020 | fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] { |
| 2021 | match config { |
| 2022 | VirtualMachineConfig::RawConfig(config) => config.instanceId, |
| 2023 | VirtualMachineConfig::AppConfig(config) => config.instanceId, |
| 2024 | } |
| 2025 | } |
| 2026 | |
Alan Stokes | c96b35e | 2024-05-03 13:21:20 +0100 | [diff] [blame] | 2027 | fn extract_want_updatable(config: &VirtualMachineConfig) -> bool { |
| 2028 | match config { |
| 2029 | VirtualMachineConfig::RawConfig(_) => true, |
| 2030 | VirtualMachineConfig::AppConfig(config) => { |
| 2031 | let Some(custom) = &config.customConfig else { return true }; |
| 2032 | custom.wantUpdatable |
| 2033 | } |
| 2034 | } |
| 2035 | } |
| 2036 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2037 | fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> { |
| 2038 | match config { |
| 2039 | VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16), |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 2040 | VirtualMachineConfig::AppConfig(config) => { |
| 2041 | NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16) |
| 2042 | } |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2043 | } |
| 2044 | } |
| 2045 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2046 | fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2047 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2048 | if let Some(custom_config) = &config.customConfig { |
| 2049 | if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() { |
| 2050 | return Err(anyhow!("vendor modules feature is disabled")) |
| 2051 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2052 | } |
| 2053 | } |
| 2054 | Ok(()) |
| 2055 | } |
| 2056 | |
Nikita Ioffe | 94a8a18 | 2023-11-16 16:37:48 +0000 | [diff] [blame] | 2057 | fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2058 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2059 | if let Some(custom_config) = &config.customConfig { |
| 2060 | if !custom_config.devices.is_empty() { |
| 2061 | return Err(anyhow!("device assignment feature is disabled")) |
| 2062 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2063 | } |
| 2064 | } |
| 2065 | Ok(()) |
| 2066 | } |
| 2067 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 2068 | fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2069 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2070 | let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) }; |
| 2071 | if !payload_config.extraApks.is_empty() { |
| 2072 | return Err(anyhow!("multi-tenant feature is disabled")) |
| 2073 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2074 | } |
| 2075 | Ok(()) |
| 2076 | } |
| 2077 | |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 2078 | fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2079 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2080 | if let Some(custom_config) = &config.customConfig { |
| 2081 | if !custom_config.extraKernelCmdlineParams.is_empty() { |
| 2082 | return Err(anyhow!("debuggable_vms_improvements feature is disabled")) |
| 2083 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2084 | } |
| 2085 | } |
| 2086 | Ok(()) |
| 2087 | } |
| 2088 | |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 2089 | fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2090 | match config { |
| 2091 | VirtualMachineConfig::RawConfig(config) => { |
| 2092 | if !config.teeServices.is_empty() { |
| 2093 | return Err(anyhow!("tee_services_allowlist feature is disabled")) |
| 2094 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2095 | } |
| 2096 | } |
| 2097 | VirtualMachineConfig::AppConfig(config) => { |
| 2098 | if let Some(custom_config) = &config.customConfig { |
| 2099 | if !custom_config.teeServices.is_empty() { |
| 2100 | return Err(anyhow!("tee_services_allowlist feature is disabled")) |
| 2101 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2102 | } |
| 2103 | } |
| 2104 | } |
| 2105 | }; |
| 2106 | Ok(()) |
| 2107 | } |
| 2108 | |
Nikita Ioffe | f934e81 | 2024-07-05 15:44:41 +0000 | [diff] [blame] | 2109 | fn check_protected_vm_is_supported() -> binder::Result<()> { |
| 2110 | let is_pvm_supported = |
| 2111 | hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?; |
| 2112 | if is_pvm_supported { |
| 2113 | Ok(()) |
| 2114 | } else { |
| 2115 | Err(anyhow!("pVM is not supported")) |
| 2116 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION) |
| 2117 | } |
| 2118 | } |
| 2119 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2120 | fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2121 | if !cfg!(vendor_modules) { |
| 2122 | check_no_vendor_modules(config)?; |
| 2123 | } |
Nikita Ioffe | 94a8a18 | 2023-11-16 16:37:48 +0000 | [diff] [blame] | 2124 | if !cfg!(device_assignment) { |
| 2125 | check_no_devices(config)?; |
| 2126 | } |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 2127 | if !cfg!(multi_tenant) { |
| 2128 | check_no_extra_apks(config)?; |
| 2129 | } |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 2130 | if !cfg!(debuggable_vms_improvements) { |
| 2131 | check_no_extra_kernel_cmdline_params(config)?; |
| 2132 | } |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 2133 | if !cfg!(tee_services_allowlist) { |
| 2134 | check_no_tee_services(config)?; |
| 2135 | } |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2136 | Ok(()) |
| 2137 | } |
| 2138 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2139 | fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2140 | check_no_vendor_modules(config)?; |
| 2141 | check_no_devices(config)?; |
| 2142 | |
| 2143 | Ok(()) |
| 2144 | } |
| 2145 | |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2146 | fn clone_or_prepare_logger_fd( |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2147 | fd: Option<&ParcelFileDescriptor>, |
| 2148 | tag: String, |
| 2149 | ) -> Result<Option<File>, Status> { |
| 2150 | if let Some(fd) = fd { |
| 2151 | return Ok(Some(clone_file(fd)?)); |
| 2152 | } |
| 2153 | |
Frederick Mayle | fbbcfcd | 2024-04-08 16:31:54 -0700 | [diff] [blame] | 2154 | let (read_fd, write_fd) = |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2155 | pipe().context("Failed to create pipe").or_service_specific_exception(-1)?; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2156 | |
Frederick Mayle | fbbcfcd | 2024-04-08 16:31:54 -0700 | [diff] [blame] | 2157 | let mut reader = BufReader::new(File::from(read_fd)); |
| 2158 | let write_fd = File::from(write_fd); |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2159 | |
Frederick Mayle | 26e41af | 2025-02-05 18:30:29 -0800 | [diff] [blame] | 2160 | let mut buf = vec![]; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2161 | std::thread::spawn(move || loop { |
Frederick Mayle | 26e41af | 2025-02-05 18:30:29 -0800 | [diff] [blame] | 2162 | buf.clear(); |
| 2163 | buf.shrink_to(1024); |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2164 | match reader.read_until(b'\n', &mut buf) { |
| 2165 | Ok(0) => { |
| 2166 | // EOF |
| 2167 | return; |
| 2168 | } |
Frederick Mayle | 690ec2c | 2025-02-05 18:31:33 -0800 | [diff] [blame] | 2169 | Ok(_size) => { |
| 2170 | if buf.last() == Some(&b'\n') { |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2171 | buf.pop(); |
Frederick Mayle | 690ec2c | 2025-02-05 18:31:33 -0800 | [diff] [blame] | 2172 | // Logs sent via TTY usually end lines with "\r\n". |
| 2173 | if buf.last() == Some(&b'\r') { |
| 2174 | buf.pop(); |
| 2175 | } |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2176 | } |
| 2177 | info!("{}: {}", &tag, &String::from_utf8_lossy(&buf)); |
| 2178 | } |
| 2179 | Err(e) => { |
| 2180 | error!("Could not read console pipe: {:?}", e); |
| 2181 | return; |
| 2182 | } |
| 2183 | }; |
| 2184 | }); |
| 2185 | |
| 2186 | Ok(Some(write_fd)) |
| 2187 | } |
| 2188 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2189 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 2190 | /// it doesn't require that T implements Clone. |
| 2191 | enum BorrowedOrOwned<'a, T> { |
| 2192 | Borrowed(&'a T), |
| 2193 | Owned(T), |
| 2194 | } |
| 2195 | |
Chris Wailes | 73a1eb7 | 2025-01-15 11:56:43 -0800 | [diff] [blame] | 2196 | impl<T> AsRef<T> for BorrowedOrOwned<'_, T> { |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2197 | fn as_ref(&self) -> &T { |
| 2198 | match self { |
| 2199 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 2200 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2201 | } |
| 2202 | } |
| 2203 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2204 | |
| 2205 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 2206 | #[derive(Debug, Default)] |
| 2207 | struct VirtualMachineService { |
| 2208 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2209 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2210 | } |
| 2211 | |
| 2212 | impl Interface for VirtualMachineService {} |
| 2213 | |
| 2214 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2215 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 2216 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 2217 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2218 | info!("VM with CID {} started payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2219 | vm.update_payload_state(PayloadState::Started) |
| 2220 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 2221 | vm.callbacks.notify_payload_started(cid); |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 2222 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 2223 | let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp; |
| 2224 | 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] | 2225 | Ok(()) |
| 2226 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2227 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2228 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2229 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2230 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2231 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2232 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 2233 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 2234 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2235 | info!("VM with CID {} reported payload is ready", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2236 | vm.update_payload_state(PayloadState::Ready) |
| 2237 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 2238 | vm.callbacks.notify_payload_ready(cid); |
| 2239 | Ok(()) |
| 2240 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2241 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2242 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 2243 | } |
| 2244 | } |
| 2245 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2246 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 2247 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2248 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2249 | info!("VM with CID {} finished payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2250 | vm.update_payload_state(PayloadState::Finished) |
| 2251 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2252 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 2253 | Ok(()) |
| 2254 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2255 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2256 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2257 | } |
| 2258 | } |
| 2259 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 2260 | fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2261 | let cid = self.cid; |
| 2262 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2263 | info!("VM with CID {} encountered an error", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2264 | vm.update_payload_state(PayloadState::Finished) |
| 2265 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2266 | vm.callbacks.notify_error(cid, error_code, message); |
| 2267 | Ok(()) |
| 2268 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 2269 | error!("notifyError is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2270 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2271 | } |
| 2272 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 2273 | |
Shikha Panwar | e45e942 | 2024-02-28 21:18:10 +0000 | [diff] [blame] | 2274 | fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> { |
| 2275 | if !is_secretkeeper_supported() { |
| 2276 | return Err(StatusCode::NAME_NOT_FOUND)?; |
| 2277 | } |
| 2278 | let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?; |
| 2279 | Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default())) |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 2280 | } |
| 2281 | |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 2282 | fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> { |
| 2283 | GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode) |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 2284 | } |
Shikha Panwar | eeae640 | 2025-02-06 19:05:31 +0000 | [diff] [blame] | 2285 | |
| 2286 | fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> { |
| 2287 | GLOBAL_SERVICE.claimSecretkeeperEntry(id) |
| 2288 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2289 | } |
| 2290 | |
Shikha Panwar | 8707f0f | 2024-02-28 20:40:42 +0000 | [diff] [blame] | 2291 | fn is_secretkeeper_supported() -> bool { |
Shikha Panwar | 81d13d3 | 2024-03-10 19:39:23 +0000 | [diff] [blame] | 2292 | binder::is_declared(SECRETKEEPER_IDENTIFIER) |
| 2293 | .expect("Could not check for declared Secretkeeper interface") |
Shikha Panwar | 8187ca2 | 2024-01-04 08:33:08 +0000 | [diff] [blame] | 2294 | } |
| 2295 | |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2296 | impl VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2297 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2298 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2299 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2300 | BinderFeatures::default(), |
| 2301 | ) |
| 2302 | } |
| 2303 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2304 | |
Stephen Hines | 4c1e2fc | 2024-02-09 16:34:47 -0800 | [diff] [blame] | 2305 | struct SecretkeeperProxy(Strong<dyn ISecretkeeper>); |
| 2306 | |
| 2307 | impl Interface for SecretkeeperProxy {} |
| 2308 | |
| 2309 | impl ISecretkeeper for SecretkeeperProxy { |
| 2310 | fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> { |
| 2311 | // Pass the request to the channel, and read the response. |
| 2312 | self.0.processSecretManagementRequest(req) |
| 2313 | } |
| 2314 | |
| 2315 | fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> { |
| 2316 | let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?); |
| 2317 | Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default())) |
| 2318 | } |
| 2319 | |
| 2320 | fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> { |
| 2321 | self.0.deleteIds(ids) |
| 2322 | } |
| 2323 | |
| 2324 | fn deleteAll(&self) -> binder::Result<()> { |
| 2325 | self.0.deleteAll() |
| 2326 | } |
Matt Gilbride | b57abcc | 2024-10-12 15:26:45 +0000 | [diff] [blame] | 2327 | |
| 2328 | fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> { |
| 2329 | // SecretkeeperProxy is really a RPC binder service for PVM (It is called by |
| 2330 | // MicrodroidManager). PVMs do not & must not (for security reason) rely on |
| 2331 | // getSecretKeeperIdentity, so we throw an exception if someone attempts to |
| 2332 | // use this API from the proxy. |
| 2333 | Err(ExceptionCode::SECURITY.into()) |
| 2334 | } |
Stephen Hines | 4c1e2fc | 2024-02-09 16:34:47 -0800 | [diff] [blame] | 2335 | } |
| 2336 | |
| 2337 | struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>); |
| 2338 | |
| 2339 | impl Interface for AuthGraphKeyExchangeProxy {} |
| 2340 | |
| 2341 | impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy { |
| 2342 | fn create(&self) -> binder::Result<SessionInitiationInfo> { |
| 2343 | self.0.create() |
| 2344 | } |
| 2345 | |
| 2346 | fn init( |
| 2347 | &self, |
| 2348 | peer_pub_key: &PubKey, |
| 2349 | peer_id: &Identity, |
| 2350 | peer_nonce: &[u8], |
| 2351 | peer_version: i32, |
| 2352 | ) -> binder::Result<KeInitResult> { |
| 2353 | self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version) |
| 2354 | } |
| 2355 | |
| 2356 | fn finish( |
| 2357 | &self, |
| 2358 | peer_pub_key: &PubKey, |
| 2359 | peer_id: &Identity, |
| 2360 | peer_signature: &SessionIdSignature, |
| 2361 | peer_nonce: &[u8], |
| 2362 | peer_version: i32, |
| 2363 | own_key: &Key, |
| 2364 | ) -> binder::Result<SessionInfo> { |
| 2365 | self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key) |
| 2366 | } |
| 2367 | |
| 2368 | fn authenticationComplete( |
| 2369 | &self, |
| 2370 | peer_signature: &SessionIdSignature, |
| 2371 | shared_keys: &[AuthgraphArc; 2], |
| 2372 | ) -> binder::Result<[AuthgraphArc; 2]> { |
| 2373 | self.0.authenticationComplete(peer_signature, shared_keys) |
| 2374 | } |
| 2375 | } |
| 2376 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2377 | // KEEP IN SYNC WITH early_vms.xsd |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2378 | #[derive(Clone, Debug, Deserialize, PartialEq)] |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2379 | struct EarlyVm { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2380 | name: String, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2381 | cid: i32, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2382 | path: String, |
| 2383 | } |
| 2384 | |
| 2385 | #[derive(Debug, Default, Deserialize)] |
| 2386 | struct EarlyVms { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2387 | early_vm: Vec<EarlyVm>, |
| 2388 | } |
| 2389 | |
Alice Wang | 78dd87a | 2025-02-13 08:56:07 +0000 | [diff] [blame] | 2390 | impl EarlyVm { |
| 2391 | /// Verifies that the provided executable path matches the expected path stored in the XML |
| 2392 | /// configuration. |
| 2393 | /// If the provided path starts with `/system`, it will be stripped before comparison. |
| 2394 | fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> { |
| 2395 | let actual_path = calling_exe_path.as_ref(); |
| 2396 | if Path::new(&self.path) |
| 2397 | == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path)) |
| 2398 | { |
| 2399 | return Ok(()); |
| 2400 | } |
| 2401 | Err(Status::new_service_specific_error_str( |
| 2402 | -1, |
| 2403 | Some(format!( |
| 2404 | "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.", |
| 2405 | self.name, |
| 2406 | self.path, |
| 2407 | actual_path.display() |
| 2408 | )), |
| 2409 | )) |
| 2410 | } |
| 2411 | } |
| 2412 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2413 | static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> = |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2414 | LazyLock::new(|| Mutex::new(HashMap::new())); |
| 2415 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2416 | fn range_for_partition(partition: CallingPartition) -> Range<Cid> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2417 | match partition { |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2418 | CallingPartition::System => 100..200, |
| 2419 | CallingPartition::SystemExt | CallingPartition::Product => 200..300, |
| 2420 | CallingPartition::Vendor | CallingPartition::Odm => 300..400, |
| 2421 | CallingPartition::Unknown => 0..0, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2422 | } |
| 2423 | } |
| 2424 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2425 | fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2426 | if !xml_path.exists() { |
| 2427 | bail!("{} doesn't exist", xml_path.display()); |
| 2428 | } |
| 2429 | |
| 2430 | let xml = |
| 2431 | fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?; |
| 2432 | let xml = String::from_utf8(xml) |
| 2433 | .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?; |
| 2434 | let early_vms: EarlyVms = serde_xml_rs::from_str(&xml) |
| 2435 | .with_context(|| format!("Can't parse {}", xml_path.display()))?; |
| 2436 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2437 | Ok(early_vms.early_vm) |
| 2438 | } |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2439 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2440 | fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> { |
| 2441 | for early_vm in early_vms { |
| 2442 | let cid = early_vm |
| 2443 | .cid |
| 2444 | .try_into() |
| 2445 | .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?; |
| 2446 | |
| 2447 | ensure!( |
| 2448 | cid_range.contains(&cid), |
| 2449 | "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}", |
| 2450 | early_vm.name |
| 2451 | ); |
| 2452 | } |
| 2453 | Ok(()) |
| 2454 | } |
| 2455 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2456 | fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2457 | let mut cache = EARLY_VMS_CACHE.lock().unwrap(); |
| 2458 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2459 | if let Some(result) = cache.get(&partition) { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2460 | return Ok(result.clone()); |
| 2461 | } |
| 2462 | |
| 2463 | let pattern = format!("/{partition}/etc/avf/early_vms*.xml"); |
| 2464 | let mut early_vms = Vec::new(); |
| 2465 | for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? { |
| 2466 | match entry { |
| 2467 | Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?), |
| 2468 | Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e), |
| 2469 | } |
| 2470 | } |
| 2471 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2472 | validate_cid_range(&early_vms, &range_for_partition(partition)) |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2473 | .with_context(|| format!("CID validation for {partition} failed"))?; |
| 2474 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2475 | cache.insert(partition, early_vms.clone()); |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2476 | |
| 2477 | Ok(early_vms) |
| 2478 | } |
| 2479 | |
| 2480 | fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> { |
| 2481 | let mut found_vm: Option<&EarlyVm> = None; |
| 2482 | |
| 2483 | for early_vm in early_vms { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2484 | if early_vm.name != name { |
| 2485 | continue; |
| 2486 | } |
| 2487 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2488 | if found_vm.is_some() { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2489 | bail!("Multiple VMs named '{name}' are found"); |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2490 | } |
| 2491 | |
| 2492 | found_vm = Some(early_vm); |
| 2493 | } |
| 2494 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2495 | found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'")) |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2496 | } |
| 2497 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2498 | fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2499 | let early_vms = get_early_vms_in_partition(partition) |
| 2500 | .with_context(|| format!("Failed to get early VMs from {partition}"))?; |
| 2501 | |
| 2502 | Ok(find_early_vm(&early_vms, name) |
| 2503 | .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))? |
| 2504 | .clone()) |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2505 | } |
| 2506 | |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2507 | #[cfg(test)] |
| 2508 | mod tests { |
| 2509 | use super::*; |
| 2510 | |
| 2511 | #[test] |
| 2512 | fn test_is_allowed_label_for_partition() -> Result<()> { |
| 2513 | let expected_results = vec![ |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2514 | (CallingPartition::System, "u:object_r:system_file:s0", true), |
| 2515 | (CallingPartition::System, "u:object_r:apk_data_file:s0", true), |
| 2516 | (CallingPartition::System, "u:object_r:app_data_file:s0", false), |
| 2517 | (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false), |
| 2518 | (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false), |
| 2519 | (CallingPartition::System, "invalid", false), |
| 2520 | (CallingPartition::System, "user:role:apk_data_file:severity:categories", true), |
| 2521 | ( |
| 2522 | CallingPartition::System, |
| 2523 | "user:role:apk_data_file:severity:categories:extraneous", |
| 2524 | false, |
| 2525 | ), |
| 2526 | (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false), |
| 2527 | (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true), |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2528 | ]; |
| 2529 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2530 | for (calling_partition, label, expected_valid) in expected_results { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2531 | let context = SeContext::new(label)?; |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2532 | let result = check_label_is_allowed(&context, calling_partition); |
| 2533 | if expected_valid != result.is_ok() { |
| 2534 | bail!( |
| 2535 | "Expected label {label} to be {} for {calling_partition} partition", |
| 2536 | if expected_valid { "allowed" } else { "disallowed" } |
| 2537 | ); |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2538 | } |
| 2539 | } |
| 2540 | Ok(()) |
| 2541 | } |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 2542 | |
| 2543 | #[test] |
| 2544 | fn test_create_or_update_idsig_file_empty_apk() -> Result<()> { |
| 2545 | let apk = tempfile::tempfile().unwrap(); |
| 2546 | let idsig = tempfile::tempfile().unwrap(); |
| 2547 | |
| 2548 | let ret = create_or_update_idsig_file( |
| 2549 | &ParcelFileDescriptor::new(apk), |
| 2550 | &ParcelFileDescriptor::new(idsig), |
| 2551 | ); |
| 2552 | assert!(ret.is_err(), "should fail"); |
| 2553 | Ok(()) |
| 2554 | } |
| 2555 | |
| 2556 | #[test] |
| 2557 | fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> { |
| 2558 | let tmp_dir = tempfile::TempDir::new().unwrap(); |
| 2559 | let apk = File::open(tmp_dir.path()).unwrap(); |
| 2560 | let idsig = tempfile::tempfile().unwrap(); |
| 2561 | |
| 2562 | let ret = create_or_update_idsig_file( |
| 2563 | &ParcelFileDescriptor::new(apk), |
| 2564 | &ParcelFileDescriptor::new(idsig), |
| 2565 | ); |
| 2566 | assert!(ret.is_err(), "should fail"); |
| 2567 | Ok(()) |
| 2568 | } |
| 2569 | |
| 2570 | /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory |
| 2571 | /// on ext4 filesystem is passed. |
| 2572 | /// On ext4 lseek on a directory fd will return (off_t)-1 (see: |
| 2573 | /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in |
| 2574 | /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory. |
| 2575 | #[test] |
| 2576 | fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> { |
| 2577 | // APEXes are backed by the ext4. |
| 2578 | let apk = File::open("/apex/com.android.virt/").unwrap(); |
| 2579 | let idsig = tempfile::tempfile().unwrap(); |
| 2580 | |
| 2581 | let ret = create_or_update_idsig_file( |
| 2582 | &ParcelFileDescriptor::new(apk), |
| 2583 | &ParcelFileDescriptor::new(idsig), |
| 2584 | ); |
| 2585 | assert!(ret.is_err(), "should fail"); |
| 2586 | Ok(()) |
| 2587 | } |
Jiyong Park | 8d19295 | 2023-06-26 14:29:51 +0900 | [diff] [blame] | 2588 | |
| 2589 | #[test] |
| 2590 | fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> { |
| 2591 | use std::io::Seek; |
| 2592 | |
| 2593 | // Pick any APK |
| 2594 | let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap(); |
| 2595 | let mut idsig = tempfile::tempfile().unwrap(); |
| 2596 | |
| 2597 | create_or_update_idsig_file( |
| 2598 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2599 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 2600 | )?; |
| 2601 | let modified_orig = idsig.metadata()?.modified()?; |
| 2602 | apk.rewind()?; |
| 2603 | idsig.rewind()?; |
| 2604 | |
| 2605 | // Call the function again |
| 2606 | create_or_update_idsig_file( |
| 2607 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2608 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 2609 | )?; |
| 2610 | let modified_new = idsig.metadata()?.modified()?; |
| 2611 | assert!(modified_orig == modified_new, "idsig file was updated unnecessarily"); |
| 2612 | Ok(()) |
| 2613 | } |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 2614 | |
| 2615 | #[test] |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 2616 | fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> { |
| 2617 | use std::io::Read; |
| 2618 | |
| 2619 | // Pick any APK |
| 2620 | let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap(); |
| 2621 | let idsig_empty = tempfile::tempfile().unwrap(); |
| 2622 | let mut idsig_invalid = tempfile::tempfile().unwrap(); |
| 2623 | idsig_invalid.write_all(b"Oops")?; |
| 2624 | |
| 2625 | // Create new idsig |
| 2626 | create_or_update_idsig_file( |
| 2627 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2628 | &ParcelFileDescriptor::new(idsig_empty.try_clone()?), |
| 2629 | )?; |
| 2630 | apk.rewind()?; |
| 2631 | |
| 2632 | // Update idsig_invalid |
| 2633 | create_or_update_idsig_file( |
| 2634 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2635 | &ParcelFileDescriptor::new(idsig_invalid.try_clone()?), |
| 2636 | )?; |
| 2637 | |
| 2638 | // Ensure the 2 idsig files have same size! |
| 2639 | assert!( |
| 2640 | idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(), |
| 2641 | "idsig files differ in size" |
| 2642 | ); |
| 2643 | // Ensure the 2 idsig files have same content! |
| 2644 | for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) { |
| 2645 | assert!(b1.unwrap() == b2.unwrap(), "idsig files differ") |
| 2646 | } |
| 2647 | Ok(()) |
| 2648 | } |
| 2649 | #[test] |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 2650 | fn test_append_kernel_param_first_param() { |
| 2651 | let mut vm_config = VirtualMachineRawConfig { ..Default::default() }; |
| 2652 | append_kernel_param("foo=1", &mut vm_config); |
| 2653 | assert_eq!(vm_config.params, Some("foo=1".to_owned())) |
| 2654 | } |
| 2655 | |
| 2656 | #[test] |
| 2657 | fn test_append_kernel_param() { |
| 2658 | let mut vm_config = |
| 2659 | VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() }; |
| 2660 | append_kernel_param("bar=42", &mut vm_config); |
| 2661 | assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned())) |
| 2662 | } |
Seungjae Yoo | ec3bc52 | 2023-11-09 10:14:30 +0900 | [diff] [blame] | 2663 | |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 2664 | fn test_extract_os_name_from_config_path( |
| 2665 | path: &Path, |
| 2666 | expected_result: Option<&str>, |
| 2667 | ) -> Result<()> { |
| 2668 | let result = extract_os_name_from_config_path(path); |
| 2669 | if result.as_deref() != expected_result { |
| 2670 | bail!("Expected {:?} but was {:?}", expected_result, &result) |
| 2671 | } |
| 2672 | Ok(()) |
| 2673 | } |
| 2674 | |
| 2675 | #[test] |
| 2676 | fn test_extract_os_name_from_microdroid_config() -> Result<()> { |
| 2677 | test_extract_os_name_from_config_path( |
| 2678 | Path::new("/apex/com.android.virt/etc/microdroid.json"), |
| 2679 | Some("microdroid"), |
| 2680 | ) |
| 2681 | } |
| 2682 | |
| 2683 | #[test] |
Nikita Ioffe | f49350e | 2024-11-01 16:11:48 +0000 | [diff] [blame] | 2684 | fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> { |
| 2685 | test_extract_os_name_from_config_path( |
| 2686 | Path::new("/apex/com.android.virt/etc/microdroid_16k.json"), |
| 2687 | Some("microdroid_16k"), |
| 2688 | ) |
| 2689 | } |
| 2690 | |
| 2691 | #[test] |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 2692 | fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> { |
| 2693 | test_extract_os_name_from_config_path( |
| 2694 | Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"), |
| 2695 | Some("microdroid_gki-android14-6.1"), |
| 2696 | ) |
| 2697 | } |
| 2698 | |
| 2699 | #[test] |
| 2700 | fn test_extract_os_name_from_invalid_path() -> Result<()> { |
| 2701 | test_extract_os_name_from_config_path( |
| 2702 | Path::new("/apex/com.android.virt/etc/microdroid.img"), |
| 2703 | None, |
| 2704 | ) |
| 2705 | } |
| 2706 | |
| 2707 | #[test] |
| 2708 | fn test_extract_os_name_from_configs() -> Result<()> { |
| 2709 | let tmp_dir = tempfile::TempDir::new()?; |
| 2710 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2711 | |
| 2712 | let mut os_names: HashSet<String> = HashSet::new(); |
| 2713 | os_names.insert("microdroid".to_owned()); |
| 2714 | os_names.insert("microdroid_gki-android14-6.1".to_owned()); |
| 2715 | os_names.insert("microdroid_gki-android15-6.1".to_owned()); |
| 2716 | |
| 2717 | // config files |
| 2718 | for os_name in &os_names { |
| 2719 | std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?; |
| 2720 | } |
| 2721 | |
| 2722 | // fake files not related to configs |
| 2723 | std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?; |
| 2724 | std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?; |
| 2725 | |
| 2726 | let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() { |
| 2727 | Some(s) => s.to_owned(), |
| 2728 | None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path), |
| 2729 | }; |
| 2730 | |
| 2731 | let result = extract_os_names_from_configs(&glob_pattern)?; |
| 2732 | if result != os_names { |
| 2733 | bail!("Expected {:?} but was {:?}", os_names, result); |
| 2734 | } |
| 2735 | Ok(()) |
| 2736 | } |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2737 | |
| 2738 | #[test] |
| 2739 | fn test_find_early_vms_from_xml() -> Result<()> { |
| 2740 | let tmp_dir = tempfile::TempDir::new()?; |
| 2741 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2742 | let xml_path = tmp_dir_path.join("early_vms.xml"); |
| 2743 | |
| 2744 | std::fs::write( |
| 2745 | &xml_path, |
| 2746 | br#"<?xml version="1.0" encoding="utf-8"?> |
| 2747 | <early_vms> |
| 2748 | <early_vm> |
| 2749 | <name>vm_demo_native_early</name> |
| 2750 | <cid>123</cid> |
| 2751 | <path>/system/bin/vm_demo_native_early</path> |
| 2752 | </early_vm> |
| 2753 | <early_vm> |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2754 | <name>vm_demo_native_early_2</name> |
| 2755 | <cid>456</cid> |
| 2756 | <path>/system/bin/vm_demo_native_early_2</path> |
| 2757 | </early_vm> |
| 2758 | </early_vms> |
| 2759 | "#, |
| 2760 | )?; |
| 2761 | |
| 2762 | let cid_range = 100..1000; |
| 2763 | |
| 2764 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2765 | validate_cid_range(&early_vms, &cid_range)?; |
| 2766 | |
| 2767 | let test_cases = [ |
| 2768 | ( |
| 2769 | "vm_demo_native_early", |
| 2770 | EarlyVm { |
| 2771 | name: "vm_demo_native_early".to_owned(), |
| 2772 | cid: 123, |
| 2773 | path: "/system/bin/vm_demo_native_early".to_owned(), |
| 2774 | }, |
| 2775 | ), |
| 2776 | ( |
| 2777 | "vm_demo_native_early_2", |
| 2778 | EarlyVm { |
| 2779 | name: "vm_demo_native_early_2".to_owned(), |
| 2780 | cid: 456, |
| 2781 | path: "/system/bin/vm_demo_native_early_2".to_owned(), |
| 2782 | }, |
| 2783 | ), |
| 2784 | ]; |
| 2785 | |
| 2786 | for (name, expected) in test_cases { |
| 2787 | let result = find_early_vm(&early_vms, name)?; |
| 2788 | assert_eq!(result, &expected); |
| 2789 | } |
| 2790 | |
| 2791 | Ok(()) |
| 2792 | } |
| 2793 | |
| 2794 | #[test] |
| 2795 | fn test_invalid_cid_validation() -> Result<()> { |
| 2796 | let tmp_dir = tempfile::TempDir::new()?; |
| 2797 | let xml_path = tmp_dir.path().join("early_vms.xml"); |
| 2798 | |
| 2799 | let cid_range = 100..1000; |
| 2800 | |
| 2801 | for cid in [-1, 999999] { |
| 2802 | std::fs::write( |
| 2803 | &xml_path, |
| 2804 | format!( |
| 2805 | r#"<?xml version="1.0" encoding="utf-8"?> |
| 2806 | <early_vms> |
| 2807 | <early_vm> |
| 2808 | <name>vm_demo_invalid_cid</name> |
| 2809 | <cid>{cid}</cid> |
| 2810 | <path>/system/bin/vm_demo_invalid_cid</path> |
| 2811 | </early_vm> |
| 2812 | </early_vms> |
| 2813 | "# |
| 2814 | ), |
| 2815 | )?; |
| 2816 | |
| 2817 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2818 | assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail"); |
| 2819 | } |
| 2820 | |
| 2821 | Ok(()) |
| 2822 | } |
| 2823 | |
| 2824 | #[test] |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2825 | fn test_symlink_to_system_ext_supported() -> Result<()> { |
| 2826 | let link_path = Path::new("/system/system_ext/file"); |
| 2827 | let partition = find_partition(Some(link_path)).unwrap(); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2828 | assert_eq!(CallingPartition::SystemExt, partition); |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2829 | Ok(()) |
| 2830 | } |
| 2831 | |
| 2832 | #[test] |
| 2833 | fn test_symlink_to_product_supported() -> Result<()> { |
| 2834 | let link_path = Path::new("/system/product/file"); |
| 2835 | let partition = find_partition(Some(link_path)).unwrap(); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2836 | assert_eq!(CallingPartition::Product, partition); |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2837 | Ok(()) |
| 2838 | } |
| 2839 | |
| 2840 | #[test] |
Frederick Mayle | 2192baf | 2025-02-26 11:27:22 -0800 | [diff] [blame] | 2841 | fn test_vendor_in_data() { |
| 2842 | assert_eq!( |
| 2843 | CallingPartition::Vendor, |
| 2844 | find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap() |
| 2845 | ); |
| 2846 | } |
| 2847 | |
| 2848 | #[test] |
Alice Wang | 78dd87a | 2025-02-13 08:56:07 +0000 | [diff] [blame] | 2849 | fn early_vm_exe_paths_match_succeeds_with_same_paths() { |
| 2850 | let early_vm = EarlyVm { |
| 2851 | name: "vm_demo_native_early".to_owned(), |
| 2852 | cid: 123, |
| 2853 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2854 | }; |
| 2855 | let calling_exe_path = "/system_ext/bin/vm_demo_native_early"; |
| 2856 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok()) |
| 2857 | } |
| 2858 | |
| 2859 | #[test] |
| 2860 | fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() { |
| 2861 | let early_vm = EarlyVm { |
| 2862 | name: "vm_demo_native_early".to_owned(), |
| 2863 | cid: 123, |
| 2864 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2865 | }; |
| 2866 | let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early"; |
| 2867 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok()) |
| 2868 | } |
| 2869 | |
| 2870 | #[test] |
| 2871 | fn early_vm_exe_paths_match_fails_with_unmatched_paths() { |
| 2872 | let early_vm = EarlyVm { |
| 2873 | name: "vm_demo_native_early".to_owned(), |
| 2874 | cid: 123, |
| 2875 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2876 | }; |
| 2877 | let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early"; |
| 2878 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err()) |
| 2879 | } |
| 2880 | |
| 2881 | #[test] |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2882 | fn test_duplicated_early_vms() -> Result<()> { |
| 2883 | let tmp_dir = tempfile::TempDir::new()?; |
| 2884 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2885 | let xml_path = tmp_dir_path.join("early_vms.xml"); |
| 2886 | |
| 2887 | std::fs::write( |
| 2888 | &xml_path, |
| 2889 | br#"<?xml version="1.0" encoding="utf-8"?> |
| 2890 | <early_vms> |
| 2891 | <early_vm> |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2892 | <name>vm_demo_duplicated_name</name> |
| 2893 | <cid>456</cid> |
| 2894 | <path>/system/bin/vm_demo_duplicated_name_1</path> |
| 2895 | </early_vm> |
| 2896 | <early_vm> |
| 2897 | <name>vm_demo_duplicated_name</name> |
| 2898 | <cid>789</cid> |
| 2899 | <path>/system/bin/vm_demo_duplicated_name_2</path> |
| 2900 | </early_vm> |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2901 | </early_vms> |
| 2902 | "#, |
| 2903 | )?; |
| 2904 | |
| 2905 | let cid_range = 100..1000; |
| 2906 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2907 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2908 | validate_cid_range(&early_vms, &cid_range)?; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2909 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2910 | assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail"); |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2911 | |
| 2912 | Ok(()) |
| 2913 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2914 | } |