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 | 22e5d0a | 2025-02-17 16:36:52 +0000 | [diff] [blame^] | 730 | // TODO(ioffe): only pVMs should be able to request access to teeServices. |
Nikita Ioffe | 9951e4b | 2024-11-14 17:30:50 +0000 | [diff] [blame] | 731 | check_tee_service_permission(&caller_secontext, &config.teeServices) |
| 732 | .with_log() |
| 733 | .or_binder_exception(ExceptionCode::SECURITY)?; |
| 734 | } |
Nikita Ioffe | 13748d2 | 2024-10-23 15:10:39 +0000 | [diff] [blame] | 735 | |
Nikita Ioffe | 22e5d0a | 2025-02-17 16:36:52 +0000 | [diff] [blame^] | 736 | let mut system_tee_services = Vec::new(); |
| 737 | let mut vendor_tee_services = Vec::new(); |
| 738 | for tee_service in config.teeServices.clone() { |
| 739 | if !tee_service.starts_with("vendor.") { |
| 740 | check_known_tee_service(&tee_service)?; |
| 741 | system_tee_services.push(tee_service); |
| 742 | } else { |
| 743 | vendor_tee_services.push(tee_service); |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | // TODO(b/391774181): handle vendor tee services (which require talking to HAL) as well. |
| 748 | if !vendor_tee_services.is_empty() { |
| 749 | return Err(anyhow!("support for vendor tee services is coming soon!")) |
| 750 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 751 | } |
| 752 | |
| 753 | // TODO(ioffe): remove this check in a follow-up patch. |
| 754 | if !system_tee_services.is_empty() { |
| 755 | return Err(anyhow!("support for system tee services is coming soon!")) |
| 756 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 757 | } |
| 758 | |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 759 | let kernel = maybe_clone_file(&config.kernel)?; |
| 760 | let initrd = maybe_clone_file(&config.initrd)?; |
| 761 | |
| 762 | if config.protectedVm { |
| 763 | // Fail fast with a meaningful error message in case device doesn't support pVMs. |
| 764 | check_protected_vm_is_supported()?; |
| 765 | |
| 766 | // In a protected VM, we require custom kernels to come from a trusted source |
| 767 | // (b/237054515). |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 768 | check_label_for_kernel_files(&kernel, &initrd, calling_partition) |
| 769 | .or_service_specific_exception(-1)?; |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 770 | |
| 771 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 772 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) |
| 773 | // from being loaded in a pVM. This applies to everything but the instance image in the |
| 774 | // raw config, and everything but the non-executable, generated partitions in the app |
| 775 | // config. |
| 776 | config |
| 777 | .disks |
| 778 | .iter() |
Frederick Mayle | 9539fb5 | 2025-02-13 13:08:15 -0800 | [diff] [blame] | 779 | .flat_map(|disk| disk.image.as_ref()) |
| 780 | .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition)) |
| 781 | .or_service_specific_exception(-1)?; |
| 782 | config |
| 783 | .disks |
| 784 | .iter() |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 785 | .flat_map(|disk| disk.partitions.iter()) |
| 786 | .filter(|partition| { |
| 787 | if is_app_config { |
| 788 | !is_safe_app_partition(&partition.label) |
| 789 | } else { |
| 790 | !is_safe_raw_partition(&partition.label) |
| 791 | } |
| 792 | }) |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 793 | .try_for_each(|partition| check_label_for_partition(partition, calling_partition)) |
Jiyong Park | 3051ffe | 2024-11-26 14:41:58 +0900 | [diff] [blame] | 794 | .or_service_specific_exception(-1)?; |
| 795 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 796 | |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 797 | // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may |
| 798 | // have unstable interfaces. |
| 799 | // TODO(b/316431494): remove once Treble interfaces are stabilized. |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 800 | check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 801 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 802 | let zero_filler_path = temporary_directory.join("zero.img"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 803 | write_zero_filler(&zero_filler_path) |
| 804 | .context("Failed to make composite image") |
| 805 | .with_log() |
| 806 | .or_service_specific_exception(-1)?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 807 | |
| 808 | // Assemble disk images if needed. |
| 809 | let disks = config |
| 810 | .disks |
| 811 | .iter() |
| 812 | .map(|disk| { |
| 813 | assemble_disk_image( |
| 814 | disk, |
| 815 | &zero_filler_path, |
| 816 | &temporary_directory, |
| 817 | &mut next_temporary_image_id, |
| 818 | &mut indirect_files, |
| 819 | ) |
| 820 | }) |
| 821 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 822 | |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 823 | let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?; |
| 824 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 825 | let (vfio_devices, dtbo) = match &config.devices { |
| 826 | AssignedDevices::Devices(devices) if !devices.is_empty() => { |
| 827 | let mut set = HashSet::new(); |
| 828 | for device in devices.iter() { |
| 829 | let path = canonicalize(device) |
| 830 | .with_context(|| format!("can't canonicalize {device}")) |
| 831 | .or_service_specific_exception(-1)?; |
| 832 | if !set.insert(path) { |
| 833 | return Err(anyhow!("duplicated device {device}")) |
| 834 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
| 835 | } |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 836 | } |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 837 | let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?; |
| 838 | let dtbo_file = File::from( |
| 839 | GLOBAL_SERVICE |
| 840 | .getDtboFile()? |
| 841 | .as_ref() |
| 842 | .try_clone() |
| 843 | .context("Failed to create VM DTBO from ParcelFileDescriptor") |
| 844 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?, |
| 845 | ); |
| 846 | (devices, Some(dtbo_file)) |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 847 | } |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 848 | _ => (vec![], None), |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 849 | }; |
Jeongik Cha | 798401c | 2024-04-11 21:54:49 +0900 | [diff] [blame] | 850 | let display_config = if cfg!(paravirtualized_devices) { |
| 851 | config |
| 852 | .displayConfig |
| 853 | .as_ref() |
| 854 | .map(DisplayConfig::new) |
| 855 | .transpose() |
| 856 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 857 | } else { |
| 858 | None |
| 859 | }; |
Jason Macnak | ea7b0fa | 2024-05-08 17:02:44 -0700 | [diff] [blame] | 860 | let gpu_config = if cfg!(paravirtualized_devices) { |
| 861 | config |
| 862 | .gpuConfig |
| 863 | .as_ref() |
| 864 | .map(GpuConfig::new) |
| 865 | .transpose() |
| 866 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 867 | } else { |
| 868 | None |
| 869 | }; |
Jeongik Cha | 1df1c03 | 2024-04-03 16:03:12 +0900 | [diff] [blame] | 870 | |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 871 | let input_device_options = if cfg!(paravirtualized_devices) { |
| 872 | config |
| 873 | .inputDevices |
| 874 | .iter() |
| 875 | .map(to_input_device_option_from) |
| 876 | .collect::<Result<Vec<InputDeviceOption>, _>>() |
| 877 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)? |
| 878 | } else { |
| 879 | vec![] |
| 880 | }; |
| 881 | |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 882 | // Create TAP network interface if the VM supports network. |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 883 | let tap = if cfg!(network) && config.networkSupported { |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 884 | if *is_protected { |
| 885 | return Err(anyhow!("Network feature is not supported for pVM yet")) |
| 886 | .with_log() |
| 887 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?; |
| 888 | } |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 889 | Some(File::from( |
| 890 | GLOBAL_SERVICE |
| 891 | .createTapInterface(&get_this_pid().to_string())? |
| 892 | .as_ref() |
| 893 | .try_clone() |
| 894 | .context("Failed to get TAP interface from ParcelFileDescriptor") |
| 895 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?, |
| 896 | )) |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 897 | } else { |
| 898 | None |
| 899 | }; |
Mu-Le Lee | b2d5a31 | 2024-06-05 10:52:47 +0800 | [diff] [blame] | 900 | |
| 901 | let audio_config = if cfg!(paravirtualized_devices) { |
| 902 | config.audioConfig.as_ref().map(AudioConfig::new) |
| 903 | } else { |
| 904 | None |
| 905 | }; |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 906 | |
Elie Kheirallah | 29d7291 | 2024-08-07 20:17:26 +0000 | [diff] [blame] | 907 | let usb_config = config |
| 908 | .usbConfig |
| 909 | .as_ref() |
| 910 | .map(UsbConfig::new) |
| 911 | .unwrap_or(Ok(UsbConfig { controller: false })) |
| 912 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?; |
| 913 | |
Pierre-Clément Tosi | 3d70d46 | 2025-01-07 16:03:24 +0000 | [diff] [blame] | 914 | let detect_hangup = is_app_config && gdb_port.is_none(); |
| 915 | |
Frederick Mayle | 31cc5b2 | 2024-12-19 14:42:43 -0800 | [diff] [blame] | 916 | let custom_memory_backing_files = config |
| 917 | .customMemoryBackingFiles |
| 918 | .iter() |
| 919 | .map(|memory_backing_file| { |
| 920 | Ok(( |
| 921 | clone_file( |
| 922 | memory_backing_file |
| 923 | .file |
| 924 | .as_ref() |
| 925 | .context("missing CustomMemoryBackingFile FD") |
| 926 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?, |
| 927 | )? |
| 928 | .into(), |
| 929 | memory_backing_file.rangeStart as u64, |
| 930 | memory_backing_file.size as u64, |
| 931 | )) |
| 932 | }) |
| 933 | .collect::<binder::Result<_>>()?; |
| 934 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 935 | // Actually start the VM. |
| 936 | let crosvm_config = CrosvmConfig { |
| 937 | cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 938 | name: config.name.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 939 | bootloader: maybe_clone_file(&config.bootloader)?, |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 940 | kernel, |
| 941 | initrd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 942 | disks, |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 943 | shared_paths, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 944 | params: config.params.to_owned(), |
| 945 | protected: *is_protected, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 946 | debug_config, |
Frederick Mayle | 68d06e7 | 2024-07-12 17:18:11 -0700 | [diff] [blame] | 947 | memory_mib: config |
| 948 | .memoryMib |
| 949 | .try_into() |
| 950 | .ok() |
| 951 | .and_then(NonZeroU32::new) |
| 952 | .unwrap_or(NonZeroU32::new(256).unwrap()), |
Frederick Mayle | 384f5b5 | 2024-12-06 16:23:23 -0800 | [diff] [blame] | 953 | swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new), |
Elie Kheirallah | b4b2f24 | 2025-01-23 03:38:07 +0000 | [diff] [blame] | 954 | cpus: config.cpuOptions.clone(), |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 955 | console_out_fd, |
| 956 | console_in_fd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 957 | log_fd, |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 958 | ramdump, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 959 | indirect_files, |
| 960 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Pierre-Clément Tosi | 3d70d46 | 2025-01-07 16:03:24 +0000 | [diff] [blame] | 961 | detect_hangup, |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 962 | gdb_port, |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 963 | vfio_devices, |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 964 | dtbo, |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 965 | device_tree_overlays, |
Jeongik Cha | 1df1c03 | 2024-04-03 16:03:12 +0900 | [diff] [blame] | 966 | display_config, |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 967 | input_device_options, |
Vincent Donnefort | 538a2c6 | 2024-03-20 16:01:10 +0000 | [diff] [blame] | 968 | hugepages: config.hugePages, |
Seungjae Yoo | 986d7a4 | 2024-05-28 14:06:58 +0900 | [diff] [blame] | 969 | tap, |
Yi-Yo Chiang | 8dd3255 | 2024-05-22 19:38:16 +0800 | [diff] [blame] | 970 | console_input_device: config.consoleInputDevice.clone(), |
David Dai | 23cff71 | 2024-06-13 19:23:45 +0000 | [diff] [blame] | 971 | boost_uclamp: config.boostUclamp, |
Jason Macnak | ea7b0fa | 2024-05-08 17:02:44 -0700 | [diff] [blame] | 972 | gpu_config, |
Mu-Le Lee | b2d5a31 | 2024-06-05 10:52:47 +0800 | [diff] [blame] | 973 | audio_config, |
Frederick Mayle | cc4e2d7 | 2024-12-06 16:54:40 -0800 | [diff] [blame] | 974 | balloon: config.balloon, |
Elie Kheirallah | 29d7291 | 2024-08-07 20:17:26 +0000 | [diff] [blame] | 975 | usb_config, |
Elie Kheirallah | 5c807a2 | 2024-09-23 20:40:42 +0000 | [diff] [blame] | 976 | dump_dt_fd, |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 977 | enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod, |
| 978 | instance_id, |
Frederick Mayle | 31cc5b2 | 2024-12-19 14:42:43 -0800 | [diff] [blame] | 979 | custom_memory_backing_files, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 980 | }; |
| 981 | let instance = Arc::new( |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 982 | VmInstance::new( |
| 983 | crosvm_config, |
| 984 | temporary_directory, |
| 985 | requester_uid, |
| 986 | requester_debug_pid, |
| 987 | vm_context, |
| 988 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 989 | .with_context(|| format!("Failed to create VM with config {:?}", config)) |
| 990 | .with_log() |
| 991 | .or_service_specific_exception(-1)?, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 992 | ); |
| 993 | state.add_vm(Arc::downgrade(&instance)); |
| 994 | Ok(VirtualMachine::create(instance)) |
| 995 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 996 | } |
| 997 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 998 | /// Returns whether a VM config represents a "custom" virtual machine, which requires the |
| 999 | /// USE_CUSTOM_VIRTUAL_MACHINE. |
| 1000 | fn is_custom_config(config: &VirtualMachineConfig) -> bool { |
| 1001 | match config { |
| 1002 | // Any raw (non-Microdroid) VM is considered custom. |
| 1003 | VirtualMachineConfig::RawConfig(_) => true, |
| 1004 | VirtualMachineConfig::AppConfig(config) => { |
| 1005 | // Some features are reserved for platform apps only, even when using |
| 1006 | // VirtualMachineAppConfig. Almost all of these features are grouped in the |
| 1007 | // CustomConfig struct: |
| 1008 | // - controlling CPUs; |
| 1009 | // - gdbPort is set, meaning that crosvm will start a gdb server; |
| 1010 | // - using anything other than the default kernel; |
| 1011 | // - specifying devices to be assigned. |
| 1012 | if config.customConfig.is_some() { |
| 1013 | true |
| 1014 | } else { |
| 1015 | // Additional custom features not included in CustomConfig: |
| 1016 | // - specifying a config file; |
Alan Stokes | 736f682 | 2024-02-16 16:08:00 +0000 | [diff] [blame] | 1017 | // - specifying extra APKs; |
| 1018 | // - specifying an OS other than Microdroid. |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1019 | (match &config.payload { |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1020 | Payload::ConfigPath(_) => true, |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1021 | Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(), |
| 1022 | }) || config.osName != MICRODROID_OS_NAME |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | } |
| 1027 | |
Jiyong Park | 690c1ca | 2024-11-28 18:06:50 +0900 | [diff] [blame] | 1028 | /// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid |
| 1029 | /// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid |
| 1030 | /// VM. To handle the exceptional case, we use name as a second criteria; if the name is |
| 1031 | /// "microdroid" we run VirtualMachineService |
| 1032 | fn requires_vm_service(config: &VirtualMachineConfig) -> bool { |
| 1033 | match config { |
| 1034 | VirtualMachineConfig::AppConfig(_) => true, |
| 1035 | VirtualMachineConfig::RawConfig(config) => config.name == "microdroid", |
| 1036 | } |
| 1037 | } |
| 1038 | |
Seungjae Yoo | 14e6018 | 2024-02-21 13:28:31 +0900 | [diff] [blame] | 1039 | fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> { |
| 1040 | let VirtualMachineConfig::AppConfig(config) = config else { |
| 1041 | return Ok(None); |
| 1042 | }; |
| 1043 | let Some(custom_config) = &config.customConfig else { |
| 1044 | return Ok(None); |
| 1045 | }; |
| 1046 | let Some(file) = custom_config.vendorImage.as_ref() else { |
| 1047 | return Ok(None); |
| 1048 | }; |
| 1049 | |
| 1050 | let file = clone_file(file)?; |
| 1051 | let size = |
| 1052 | file.metadata().context("Failed to get metadata from microdroid vendor image")?.len(); |
| 1053 | let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size) |
| 1054 | .context("Failed to get vbmeta from microdroid-vendor.img")?; |
| 1055 | |
| 1056 | for descriptor in vbmeta.descriptors()?.iter() { |
| 1057 | if let vbmeta::Descriptor::Hashtree(_) = descriptor { |
| 1058 | let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest()); |
| 1059 | return Ok(Some(root_digest.as_bytes().to_vec())); |
| 1060 | } |
| 1061 | } |
| 1062 | Err(anyhow!("No hashtree digest is extracted from microdroid vendor image")) |
| 1063 | } |
| 1064 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1065 | fn maybe_create_reference_dt_overlay( |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1066 | config: &VirtualMachineConfig, |
Frederick Mayle | 196ca2b | 2024-12-18 15:27:43 -0800 | [diff] [blame] | 1067 | instance_id: &[u8; 64], |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1068 | temporary_directory: &Path, |
| 1069 | ) -> binder::Result<Option<File>> { |
| 1070 | // Currently, VirtMgr adds the host copy of reference DT & untrusted properties |
| 1071 | // (e.g. instance-id) |
| 1072 | let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH); |
| 1073 | let host_ref_dt = if host_ref_dt.exists() |
| 1074 | && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some() |
| 1075 | { |
| 1076 | Some(host_ref_dt) |
| 1077 | } else { |
| 1078 | warn!("VM reference DT doesn't exist in host DT"); |
| 1079 | None |
| 1080 | }; |
| 1081 | |
| 1082 | let vendor_hashtree_digest = extract_vendor_hashtree_digest(config) |
| 1083 | .context("Failed to extract vendor hashtree digest") |
| 1084 | .or_service_specific_exception(-1)?; |
| 1085 | |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1086 | 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] | 1087 | info!( |
| 1088 | "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \ |
| 1089 | match the trusted digest in the pvmfw config, causing the VM to fail to start." |
| 1090 | ); |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1091 | vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())] |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1092 | } else { |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1093 | vec![] |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1094 | }; |
| 1095 | |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1096 | let key_material; |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1097 | let mut untrusted_props = Vec::with_capacity(2); |
| 1098 | if cfg!(llpvm_changes) { |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1099 | untrusted_props.push((c"instance-id", &instance_id[..])); |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1100 | let want_updatable = extract_want_updatable(config); |
| 1101 | if want_updatable && is_secretkeeper_supported() { |
| 1102 | // Let guest know that it can defer rollback protection to Secretkeeper by setting |
| 1103 | // an empty property in untrusted node in DT. This enables Updatable VMs. |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1104 | untrusted_props.push((c"defer-rollback-protection", &[])); |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1105 | let sk: Strong<dyn ISecretkeeper> = |
| 1106 | binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?; |
| 1107 | if sk.getInterfaceVersion()? >= 2 { |
| 1108 | let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?; |
| 1109 | key_material = keyMaterial; |
Alan Stokes | f46a17c | 2025-01-05 15:50:18 +0000 | [diff] [blame] | 1110 | trusted_props.push((c"secretkeeper_public_key", key_material.as_slice())); |
Matt Gilbride | aade427 | 2024-12-05 13:52:42 +0000 | [diff] [blame] | 1111 | } |
Nikita Ioffe | b2c6f3a | 2024-06-06 12:51:53 +0000 | [diff] [blame] | 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | let device_tree_overlay = if host_ref_dt.is_some() |
| 1116 | || !untrusted_props.is_empty() |
| 1117 | || !trusted_props.is_empty() |
| 1118 | { |
| 1119 | let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH); |
| 1120 | let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE]; |
| 1121 | let fdt = |
| 1122 | create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props) |
| 1123 | .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}")) |
| 1124 | .or_service_specific_exception(-1)?; |
| 1125 | fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?; |
| 1126 | Some(File::open(dt_output).or_service_specific_exception(-1)?) |
| 1127 | } else { |
| 1128 | None |
| 1129 | }; |
| 1130 | Ok(device_tree_overlay) |
| 1131 | } |
| 1132 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1133 | fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> { |
| 1134 | let VirtualMachineConfig::RawConfig(config) = config else { |
| 1135 | return None; |
| 1136 | }; |
| 1137 | match &config.devices { |
| 1138 | AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(), |
| 1139 | _ => None, |
| 1140 | } |
| 1141 | } |
| 1142 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 1143 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1144 | let file = OpenOptions::new() |
| 1145 | .create_new(true) |
| 1146 | .read(true) |
| 1147 | .write(true) |
| 1148 | .open(zero_filler_path) |
| 1149 | .with_context(|| "Failed to create zero.img")?; |
| 1150 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 1151 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1152 | } |
| 1153 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1154 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 1155 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 1156 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 1157 | part.flush() |
| 1158 | } |
| 1159 | |
| 1160 | fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> { |
| 1161 | part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?; |
| 1162 | part.flush() |
| 1163 | } |
| 1164 | |
| 1165 | fn round_up(input: u64, granularity: u64) -> u64 { |
| 1166 | if granularity == 0 { |
| 1167 | return input; |
| 1168 | } |
| 1169 | // If the input is absurdly large we round down instead of up; it's going to fail anyway. |
| 1170 | let result = input.checked_add(granularity - 1).unwrap_or(input); |
| 1171 | (result / granularity) * granularity |
| 1172 | } |
| 1173 | |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 1174 | fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> { |
| 1175 | Ok(match input_device { |
| 1176 | InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch { |
| 1177 | file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1178 | height: u32::try_from(single_touch.height)?, |
| 1179 | width: u32::try_from(single_touch.width)?, |
| 1180 | name: if !single_touch.name.is_empty() { |
| 1181 | Some(single_touch.name.clone()) |
| 1182 | } else { |
| 1183 | None |
| 1184 | }, |
| 1185 | }, |
| 1186 | InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file( |
| 1187 | evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1188 | )?), |
Jeongik Cha | 985b640 | 2024-04-15 18:13:00 +0900 | [diff] [blame] | 1189 | InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file( |
| 1190 | keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1191 | )?), |
Jeongik Cha | 343894e | 2024-05-17 20:39:31 +0900 | [diff] [blame] | 1192 | InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file( |
| 1193 | mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1194 | )?), |
Jiyong Park | 6c1b9f0 | 2024-07-05 16:21:10 +0900 | [diff] [blame] | 1195 | InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file( |
| 1196 | switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?, |
| 1197 | )?), |
Jeongik Cha | 112a268 | 2024-07-09 12:28:45 +0900 | [diff] [blame] | 1198 | InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad { |
| 1199 | file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1200 | height: u32::try_from(trackpad.height)?, |
| 1201 | width: u32::try_from(trackpad.width)?, |
| 1202 | name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None }, |
| 1203 | }, |
Jeongik Cha | 1049491 | 2024-07-16 11:19:50 +0900 | [diff] [blame] | 1204 | InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch { |
| 1205 | file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?, |
| 1206 | height: u32::try_from(multi_touch.height)?, |
| 1207 | width: u32::try_from(multi_touch.width)?, |
| 1208 | name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None }, |
| 1209 | }, |
Jeongik Cha | c181be7 | 2024-03-27 00:18:30 +0900 | [diff] [blame] | 1210 | }) |
| 1211 | } |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 1212 | |
| 1213 | fn assemble_shared_paths( |
| 1214 | shared_paths: &[SharedPath], |
| 1215 | temporary_directory: &Path, |
| 1216 | ) -> Result<Vec<SharedPathConfig>, Status> { |
| 1217 | if shared_paths.is_empty() { |
| 1218 | return Ok(Vec::new()); // Return an empty vector if shared_paths is empty |
| 1219 | } |
| 1220 | |
| 1221 | shared_paths |
| 1222 | .iter() |
| 1223 | .map(|path| { |
| 1224 | Ok(SharedPathConfig { |
| 1225 | path: path.sharedPath.clone(), |
| 1226 | host_uid: path.hostUid, |
| 1227 | host_gid: path.hostGid, |
| 1228 | guest_uid: path.guestUid, |
| 1229 | guest_gid: path.guestGid, |
| 1230 | mask: path.mask, |
| 1231 | tag: path.tag.clone(), |
Akilesh Kailash | c9aa068 | 2024-11-25 10:27:24 -0800 | [diff] [blame] | 1232 | socket_path: temporary_directory |
| 1233 | .join(&path.socketPath) |
| 1234 | .to_string_lossy() |
| 1235 | .to_string(), |
| 1236 | socket_fd: maybe_clone_file(&path.socketFd)?, |
| 1237 | app_domain: path.appDomain, |
Akilesh Kailash | 05515dc | 2024-10-22 21:42:52 -0700 | [diff] [blame] | 1238 | }) |
| 1239 | }) |
| 1240 | .collect() |
| 1241 | } |
| 1242 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1243 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 1244 | /// |
| 1245 | /// This may involve assembling a composite disk from a set of partition images. |
| 1246 | fn assemble_disk_image( |
| 1247 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1248 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1249 | temporary_directory: &Path, |
| 1250 | next_temporary_image_id: &mut u64, |
| 1251 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1252 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1253 | let image = if !disk.partitions.is_empty() { |
| 1254 | if disk.image.is_some() { |
| 1255 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1256 | return Err(anyhow!("DiskImage contains both image and partitions")) |
| 1257 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1258 | } |
| 1259 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1260 | let composite_image_filenames = |
| 1261 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 1262 | let (image, partition_files) = make_composite_image( |
| 1263 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 1264 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1265 | &composite_image_filenames.composite, |
| 1266 | &composite_image_filenames.header, |
| 1267 | &composite_image_filenames.footer, |
| 1268 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1269 | .with_context(|| format!("Failed to make composite disk image with config {:?}", disk)) |
| 1270 | .with_log() |
| 1271 | .or_service_specific_exception(-1)?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1272 | |
| 1273 | // Pass the file descriptors for the various partition files to crosvm when it |
| 1274 | // is run. |
| 1275 | indirect_files.extend(partition_files); |
| 1276 | |
| 1277 | image |
| 1278 | } else if let Some(image) = &disk.image { |
| 1279 | clone_file(image)? |
| 1280 | } else { |
| 1281 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1282 | return Err(anyhow!("DiskImage didn't contain image or partitions.")) |
| 1283 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1284 | }; |
| 1285 | |
| 1286 | Ok(DiskFile { image, writable: disk.writable }) |
| 1287 | } |
| 1288 | |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 1289 | fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) { |
| 1290 | if let Some(ref mut params) = vm_config.params { |
| 1291 | params.push(' '); |
| 1292 | params.push_str(param) |
| 1293 | } else { |
| 1294 | vm_config.params = Some(param.to_owned()) |
| 1295 | } |
| 1296 | } |
| 1297 | |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 1298 | fn extract_os_name_from_config_path(config: &Path) -> Option<String> { |
| 1299 | if config.extension()?.to_str()? != "json" { |
| 1300 | return None; |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1301 | } |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 1302 | |
| 1303 | Some(config.with_extension("").file_name()?.to_str()?.to_owned()) |
| 1304 | } |
| 1305 | |
| 1306 | fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> { |
| 1307 | let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?; |
| 1308 | let os_names = |
| 1309 | configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>(); |
| 1310 | |
| 1311 | Ok(os_names) |
| 1312 | } |
| 1313 | |
| 1314 | fn get_supported_os_names() -> Result<HashSet<String>> { |
| 1315 | if !cfg!(vendor_modules) { |
| 1316 | return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect()); |
| 1317 | } |
| 1318 | |
| 1319 | extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json") |
| 1320 | } |
| 1321 | |
| 1322 | fn is_valid_os(os_name: &str) -> bool { |
| 1323 | SUPPORTED_OS_NAMES.contains(os_name) |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1324 | } |
| 1325 | |
Nikita Ioffe | 2cb75cf | 2024-06-04 16:43:56 +0000 | [diff] [blame] | 1326 | fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool { |
| 1327 | if !cfg!(vendor_modules) { |
| 1328 | return false; |
| 1329 | } |
| 1330 | match config { |
| 1331 | VirtualMachineConfig::RawConfig(_) => false, |
| 1332 | VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"), |
| 1333 | } |
| 1334 | } |
| 1335 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1336 | fn load_app_config( |
| 1337 | config: &VirtualMachineAppConfig, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1338 | debug_config: &DebugConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1339 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 1340 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1341 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 1342 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 1343 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1344 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 1345 | let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() { |
| 1346 | Some(clone_file(file)?) |
| 1347 | } else { |
| 1348 | None |
| 1349 | }; |
| 1350 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1351 | let vm_payload_config; |
| 1352 | let extra_apk_files: Vec<_>; |
| 1353 | match &config.payload { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1354 | Payload::ConfigPath(config_path) => { |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1355 | vm_payload_config = |
| 1356 | load_vm_payload_config_from_file(&apk_file, config_path.as_str()) |
| 1357 | .with_context(|| format!("Couldn't read config from {}", config_path))?; |
| 1358 | extra_apk_files = vm_payload_config |
| 1359 | .extra_apks |
| 1360 | .iter() |
| 1361 | .enumerate() |
| 1362 | .map(|(i, apk)| { |
| 1363 | File::open(PathBuf::from(&apk.path)) |
| 1364 | .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path)) |
| 1365 | }) |
| 1366 | .collect::<Result<_>>()?; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1367 | } |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1368 | Payload::PayloadConfig(payload_config) => { |
| 1369 | vm_payload_config = create_vm_payload_config(payload_config)?; |
| 1370 | extra_apk_files = |
| 1371 | payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?; |
| 1372 | } |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1373 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1374 | |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1375 | let payload_config_os = vm_payload_config.os.name.as_str(); |
| 1376 | if !payload_config_os.is_empty() && payload_config_os != "microdroid" { |
| 1377 | bail!("'os' in payload config is deprecated"); |
| 1378 | } |
| 1379 | |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1380 | // For now, the only supported OS is Microdroid and Microdroid GKI |
Inseob Kim | 89b2459 | 2024-02-23 18:59:43 +0900 | [diff] [blame] | 1381 | let os_name = config.osName.as_str(); |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1382 | if !is_valid_os(os_name) { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1383 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1384 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1385 | |
| 1386 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 1387 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1388 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 1389 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1390 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1391 | |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 1392 | if let Some(custom_config) = &config.customConfig { |
| 1393 | if let Some(file) = custom_config.customKernelImage.as_ref() { |
| 1394 | vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?)) |
| 1395 | } |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 1396 | vm_config.gdbPort = custom_config.gdbPort; |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 1397 | |
| 1398 | if let Some(file) = custom_config.vendorImage.as_ref() { |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 1399 | add_microdroid_vendor_image(clone_file(file)?, &mut vm_config); |
Pechetty Sravani (xWF) | faabfbd | 2024-09-24 15:27:48 +0000 | [diff] [blame] | 1400 | append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config) |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 1401 | } |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 1402 | |
Jaewan Kim | f43372b | 2024-12-13 18:33:58 +0900 | [diff] [blame] | 1403 | vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone()); |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 1404 | vm_config.networkSupported = custom_config.networkSupported; |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 1405 | |
| 1406 | for param in custom_config.extraKernelCmdlineParams.iter() { |
| 1407 | append_kernel_param(param, &mut vm_config); |
| 1408 | } |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 1409 | |
| 1410 | vm_config.teeServices.clone_from(&custom_config.teeServices); |
Nikita Ioffe | 26c35ed | 2023-06-05 17:49:08 +0100 | [diff] [blame] | 1411 | } |
| 1412 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 1413 | if config.memoryMib > 0 { |
| 1414 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 1415 | } |
| 1416 | |
Chris Wailes | 6177c66 | 2024-05-09 14:37:44 -0700 | [diff] [blame] | 1417 | vm_config.name.clone_from(&config.name); |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 1418 | vm_config.protectedVm = config.protectedVm; |
Elie Kheirallah | b4b2f24 | 2025-01-23 03:38:07 +0000 | [diff] [blame] | 1419 | vm_config.cpuOptions = config.cpuOptions.clone(); |
Vincent Donnefort | 538a2c6 | 2024-03-20 16:01:10 +0000 | [diff] [blame] | 1420 | vm_config.hugePages = config.hugePages || vm_payload_config.hugepages; |
David Dai | 23cff71 | 2024-06-13 19:23:45 +0000 | [diff] [blame] | 1421 | vm_config.boostUclamp = config.boostUclamp; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 1422 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 1423 | // Microdroid takes additional init ramdisk & (optionally) storage image |
Inseob Kim | 172f9eb | 2023-11-06 17:02:08 +0900 | [diff] [blame] | 1424 | 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] | 1425 | |
| 1426 | // Include Microdroid payload disk (contains apks, idsigs) in vm config |
| 1427 | add_microdroid_payload_images( |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1428 | config, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1429 | debug_config, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1430 | temporary_directory, |
| 1431 | apk_file, |
| 1432 | idsig_file, |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1433 | extra_apk_files, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1434 | &vm_payload_config, |
| 1435 | &mut vm_config, |
| 1436 | )?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1437 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 1438 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 1439 | } |
| 1440 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1441 | fn check_partition_for_file( |
| 1442 | fd: &ParcelFileDescriptor, |
| 1443 | calling_partition: CallingPartition, |
| 1444 | ) -> Result<()> { |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1445 | let path = format!("/proc/self/fd/{}", fd.as_raw_fd()); |
| 1446 | let link = fs::read_link(&path).context(format!("can't read_link {path}"))?; |
| 1447 | |
| 1448 | // microdroid vendor image is OK |
| 1449 | if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img") |
| 1450 | { |
| 1451 | return Ok(()); |
| 1452 | } |
| 1453 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1454 | let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm"); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1455 | let is_caller_vendor = |
| 1456 | calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm; |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1457 | |
| 1458 | if is_fd_vendor != is_caller_vendor { |
| 1459 | 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] | 1460 | } |
| 1461 | |
| 1462 | Ok(()) |
| 1463 | } |
| 1464 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1465 | fn check_partitions_for_files( |
| 1466 | config: &VirtualMachineRawConfig, |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 1467 | calling_partition: CallingPartition, |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1468 | ) -> Result<()> { |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1469 | config |
| 1470 | .disks |
| 1471 | .iter() |
| 1472 | .flat_map(|disk| disk.partitions.iter()) |
| 1473 | .filter_map(|partition| partition.image.as_ref()) |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1474 | .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1475 | |
Inseob Kim | e3e932d | 2024-12-16 20:06:57 +0900 | [diff] [blame] | 1476 | config |
| 1477 | .disks |
| 1478 | .iter() |
| 1479 | .filter_map(|disk| disk.image.as_ref()) |
| 1480 | .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?; |
| 1481 | |
| 1482 | config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
| 1483 | config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
| 1484 | config |
| 1485 | .bootloader |
| 1486 | .as_ref() |
| 1487 | .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?; |
Inseob Kim | ff48a7c | 2024-02-26 22:07:21 +0900 | [diff] [blame] | 1488 | |
| 1489 | Ok(()) |
| 1490 | } |
| 1491 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1492 | fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> { |
| 1493 | let mut apk_zip = ZipArchive::new(apk_file)?; |
| 1494 | let config_file = apk_zip.by_name(config_path)?; |
| 1495 | Ok(serde_json::from_reader(config_file)?) |
| 1496 | } |
| 1497 | |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 1498 | fn create_vm_payload_config( |
| 1499 | payload_config: &VirtualMachinePayloadConfig, |
| 1500 | ) -> Result<VmPayloadConfig> { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1501 | // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit |
| 1502 | // parameters we've been given. Microdroid will do something equivalent inside the VM using the |
| 1503 | // payload config that we send it via the metadata file. |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 1504 | |
| 1505 | let payload_binary_name = &payload_config.payloadBinaryName; |
| 1506 | if payload_binary_name.contains('/') { |
| 1507 | bail!("Payload binary name must not specify a path: {payload_binary_name}"); |
| 1508 | } |
| 1509 | |
| 1510 | let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() }; |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 1511 | |
| 1512 | // The VM only cares about how many there are, these names are actually ignored. |
| 1513 | let extra_apk_count = payload_config.extraApks.len(); |
| 1514 | let extra_apks = |
| 1515 | (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect(); |
| 1516 | |
Nikita Ioffe | 901083f | 2025-01-20 01:54:28 +0000 | [diff] [blame] | 1517 | if check_use_relaxed_microdroid_rollback_protection().is_ok() { |
| 1518 | // The only payload delivered via Mainline module in this release requires |
| 1519 | // com.android.i18n apex. However, we are past all the reasonable deadlines to add new |
| 1520 | // APIs, so we use the fact that the payload is granted |
| 1521 | // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include |
| 1522 | // com.android.i18n APEX. |
| 1523 | // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to |
| 1524 | // Microdroid pVMs. |
| 1525 | let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }]; |
| 1526 | Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() }) |
| 1527 | } else { |
| 1528 | Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() }) |
| 1529 | } |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 1530 | } |
| 1531 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1532 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1533 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1534 | temporary_directory: &Path, |
| 1535 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1536 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1537 | let id = *next_temporary_image_id; |
| 1538 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 1539 | CompositeImageFilenames { |
| 1540 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 1541 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 1542 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 1543 | } |
| 1544 | } |
| 1545 | |
| 1546 | /// Filenames for a composite disk image, including header and footer partitions. |
| 1547 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 1548 | struct CompositeImageFilenames { |
| 1549 | /// The composite disk image itself. |
| 1550 | composite: PathBuf, |
| 1551 | /// The header partition image. |
| 1552 | header: PathBuf, |
| 1553 | /// The footer partition image. |
| 1554 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1555 | } |
| 1556 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1557 | /// Checks whether the caller has a specific permission |
| 1558 | fn check_permission(perm: &str) -> binder::Result<()> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 1559 | if cfg!(early) { |
| 1560 | // Skip permission check for early VMs, in favor of SELinux |
| 1561 | return Ok(()); |
| 1562 | } |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 1563 | let calling_pid = get_calling_pid(); |
| 1564 | let calling_uid = get_calling_uid(); |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1565 | // Root can do anything |
| 1566 | if calling_uid == 0 { |
| 1567 | return Ok(()); |
| 1568 | } |
| 1569 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
Frederick Mayle | b2a0287 | 2024-05-08 13:35:12 -0700 | [diff] [blame] | 1570 | binder::wait_for_interface("permission")?; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1571 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1572 | Ok(()) |
| 1573 | } else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1574 | Err(anyhow!("does not have the {} permission", perm)) |
| 1575 | .or_binder_exception(ExceptionCode::SECURITY) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1576 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1577 | } |
| 1578 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1579 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 1580 | fn check_manage_access() -> binder::Result<()> { |
| 1581 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 1582 | } |
| 1583 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 1584 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 1585 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 1586 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 1587 | } |
| 1588 | |
Nikita Ioffe | 901083f | 2025-01-20 01:54:28 +0000 | [diff] [blame] | 1589 | /// Check whether the caller of the current binder method is allowed to use relaxed microdroid |
| 1590 | /// rollback protection schema. |
| 1591 | fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> { |
| 1592 | check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION") |
| 1593 | } |
| 1594 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1595 | /// Return whether a partition is exempt from selinux label checks, because we know that it does |
| 1596 | /// 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] | 1597 | fn is_safe_app_partition(label: &str) -> bool { |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 1598 | // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1599 | label == "vm-instance" |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 1600 | || label == "encryptedstore" |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1601 | || label == "microdroid-apk-idsig" |
| 1602 | || label == "payload-metadata" |
| 1603 | || label.starts_with("extra-idsig-") |
| 1604 | } |
| 1605 | |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 1606 | /// Returns whether a partition with the given label is safe for a raw config VM. |
| 1607 | fn is_safe_raw_partition(label: &str) -> bool { |
| 1608 | label == "vm-instance" |
| 1609 | } |
| 1610 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1611 | /// Check that a file SELinux label is acceptable. |
| 1612 | /// |
| 1613 | /// 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] | 1614 | /// system or vendor, do not have write access to. |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1615 | /// |
| 1616 | /// Note that sepolicy must also grant read access for these types to both virtualization |
| 1617 | /// service and crosvm. |
| 1618 | /// |
| 1619 | /// App private data files are deliberately excluded, to avoid arbitrary payloads being run on |
| 1620 | /// user devices (W^X). |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1621 | fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1622 | match context.selinux_type()? { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1623 | | "apk_data_file" // APKs of an installed app |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1624 | | "shell_data_file" // test files created via adb shell |
Alan Stokes | fe4bb0c | 2023-03-20 14:15:36 +0000 | [diff] [blame] | 1625 | | "staging_data_file" // updated/staged APEX images |
| 1626 | | "system_file" // immutable dm-verity protected partition |
| 1627 | | "virtualizationservice_data_file" // files created by VS / VirtMgr |
Seungjae Yoo | 2b74c44 | 2023-11-15 18:05:07 +0900 | [diff] [blame] | 1628 | | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*) |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1629 | => Ok(()), |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1630 | // It is difficult to require specific label types for vendor initiated VM's files, so we |
| 1631 | // allow anything with a vendor prefix. |
| 1632 | t if calling_partition == CallingPartition::Vendor && t.starts_with("vendor_") => Ok(()), |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1633 | _ => bail!("Label {} is not allowed", context), |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 1634 | } |
| 1635 | } |
| 1636 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1637 | fn check_label_for_partition( |
| 1638 | partition: &Partition, |
| 1639 | calling_partition: CallingPartition, |
| 1640 | ) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1641 | let file = partition.image.as_ref().unwrap().as_ref(); |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1642 | check_label_is_allowed(&getfilecon(file)?, calling_partition) |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1643 | .with_context(|| format!("Partition {} invalid", &partition.label)) |
| 1644 | } |
| 1645 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1646 | fn check_label_for_kernel_files( |
| 1647 | kernel: &Option<File>, |
| 1648 | initrd: &Option<File>, |
| 1649 | calling_partition: CallingPartition, |
| 1650 | ) -> Result<()> { |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1651 | if let Some(f) = kernel { |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1652 | check_label_for_file(f, "kernel", calling_partition)?; |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1653 | } |
| 1654 | if let Some(f) = initrd { |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1655 | check_label_for_file(f, "initrd", calling_partition)?; |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1656 | } |
| 1657 | Ok(()) |
| 1658 | } |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1659 | fn check_label_for_file( |
Frederick Mayle | 9539fb5 | 2025-02-13 13:08:15 -0800 | [diff] [blame] | 1660 | file: &impl AsRawFd, |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 1661 | name: &str, |
| 1662 | calling_partition: CallingPartition, |
| 1663 | ) -> Result<()> { |
| 1664 | check_label_is_allowed(&getfilecon(file)?, calling_partition) |
| 1665 | .with_context(|| format!("{} file invalid", name)) |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 1666 | } |
| 1667 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1668 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 1669 | #[derive(Debug)] |
| 1670 | struct VirtualMachine { |
| 1671 | instance: Arc<VmInstance>, |
| 1672 | } |
| 1673 | |
| 1674 | impl VirtualMachine { |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1675 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 1676 | BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1677 | } |
| 1678 | } |
| 1679 | |
| 1680 | impl Interface for VirtualMachine {} |
| 1681 | |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1682 | impl IVirtualMachine::IVirtualMachine for VirtualMachine { |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1683 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1684 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1685 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1686 | Ok(self.instance.cid as i32) |
| 1687 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1688 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1689 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1690 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1691 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1692 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1693 | } |
| 1694 | |
| 1695 | fn registerCallback( |
| 1696 | &self, |
| 1697 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 1698 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1699 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1700 | // others. |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1701 | |
| 1702 | // Only register callback if it may be notified. |
| 1703 | // This also ensures no cyclic reference between callback and VmInstance after VM is died. |
| 1704 | let vm_state = self.instance.vm_state.lock().unwrap(); |
| 1705 | if matches!(*vm_state, VmState::Dead) { |
| 1706 | warn!("Ignoring registerCallback() after VM is died"); |
| 1707 | } else { |
| 1708 | self.instance.callbacks.add(callback.clone()); |
| 1709 | } |
| 1710 | drop(vm_state); |
| 1711 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1712 | Ok(()) |
| 1713 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1714 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1715 | fn start(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1716 | self.instance |
| 1717 | .start() |
| 1718 | .with_context(|| format!("Error starting VM with CID {}", self.instance.cid)) |
| 1719 | .with_log() |
| 1720 | .or_service_specific_exception(-1) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1721 | } |
| 1722 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1723 | fn stop(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1724 | self.instance |
| 1725 | .kill() |
| 1726 | .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid)) |
| 1727 | .with_log() |
| 1728 | .or_service_specific_exception(-1) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1729 | } |
| 1730 | |
Keir Fraser | 48221ba | 2024-07-12 14:05:02 +0000 | [diff] [blame] | 1731 | fn getMemoryBalloon(&self) -> binder::Result<i64> { |
| 1732 | let balloon = self |
| 1733 | .instance |
| 1734 | .get_memory_balloon() |
| 1735 | .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid)) |
| 1736 | .with_log() |
| 1737 | .or_service_specific_exception(-1)?; |
| 1738 | Ok(balloon.try_into().unwrap()) |
| 1739 | } |
| 1740 | |
| 1741 | fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1742 | self.instance |
Keir Fraser | 48221ba | 2024-07-12 14:05:02 +0000 | [diff] [blame] | 1743 | .set_memory_balloon(num_bytes.try_into().unwrap()) |
| 1744 | .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] | 1745 | .with_log() |
| 1746 | .or_service_specific_exception(-1) |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 1747 | } |
| 1748 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1749 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1750 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1751 | return Err(Status::new_service_specific_error_str( |
| 1752 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1753 | Some("Virtual Machine is not running"), |
| 1754 | )); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1755 | } |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 1756 | let port = port as u32; |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1757 | if port < VSOCK_PRIV_PORT_MAX { |
| 1758 | return Err(Status::new_service_specific_error_str( |
| 1759 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1760 | Some("Can't connect to privileged port {port}"), |
| 1761 | )); |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 1762 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1763 | let stream = VsockStream::connect_with_cid_port(self.instance.cid, port) |
| 1764 | .context("Failed to connect") |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1765 | .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?; |
Jiyong Park | af63d1c | 2024-09-04 16:15:42 +0900 | [diff] [blame] | 1766 | Ok(vsock_stream_to_pfd(stream)) |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1767 | } |
Yi-Yo Chiang | 2fbf0da | 2024-06-14 22:56:56 +0800 | [diff] [blame] | 1768 | |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1769 | fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> { |
| 1770 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
| 1771 | return Err(Status::new_service_specific_error_str( |
| 1772 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1773 | Some("Virtual Machine is not running"), |
| 1774 | )); |
| 1775 | } |
| 1776 | let port = port as u32; |
| 1777 | if port < VSOCK_PRIV_PORT_MAX { |
| 1778 | return Err(Status::new_service_specific_error_str( |
| 1779 | IVirtualMachine::ERROR_UNEXPECTED, |
| 1780 | Some("Can't connect to privileged port {port}"), |
| 1781 | )); |
| 1782 | } |
| 1783 | let cid = self.instance.cid; |
Devin Moore | c8800a1 | 2024-10-17 17:56:18 +0000 | [diff] [blame] | 1784 | let addr = sockaddr_vm { |
| 1785 | svm_family: AF_VSOCK as sa_family_t, |
| 1786 | svm_reserved1: 0, |
| 1787 | svm_port: port, |
| 1788 | svm_cid: cid, |
| 1789 | svm_zero: [0u8; 4], |
| 1790 | }; |
| 1791 | let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr)); |
Devin Moore | 407df8f | 2024-08-27 19:39:16 +0000 | [diff] [blame] | 1792 | let accessor = Accessor::new(name, get_connection_info); |
| 1793 | accessor |
| 1794 | .as_binder() |
| 1795 | .context("The newly created Accessor should always have a binder") |
| 1796 | .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED) |
| 1797 | } |
| 1798 | |
Yi-Yo Chiang | 2fbf0da | 2024-06-14 22:56:56 +0800 | [diff] [blame] | 1799 | fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> { |
| 1800 | self.instance.vm_context.global_context.setHostConsoleName(ptsname) |
| 1801 | } |
Jiyong Park | 23b6739 | 2024-07-04 13:51:42 +0900 | [diff] [blame] | 1802 | |
| 1803 | fn suspend(&self) -> binder::Result<()> { |
| 1804 | self.instance |
| 1805 | .suspend() |
| 1806 | .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid)) |
| 1807 | .with_log() |
| 1808 | .or_service_specific_exception(-1) |
| 1809 | } |
| 1810 | |
| 1811 | fn resume(&self) -> binder::Result<()> { |
| 1812 | self.instance |
| 1813 | .resume() |
| 1814 | .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid)) |
| 1815 | .with_log() |
| 1816 | .or_service_specific_exception(-1) |
| 1817 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1818 | } |
| 1819 | |
| 1820 | impl Drop for VirtualMachine { |
| 1821 | fn drop(&mut self) { |
| 1822 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1823 | if let Err(e) = self.instance.kill() { |
| 1824 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 1825 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1826 | } |
| 1827 | } |
| 1828 | |
| 1829 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 1830 | /// dies. |
| 1831 | #[derive(Debug, Default)] |
| 1832 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 1833 | |
| 1834 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1835 | /// Call all registered callbacks to notify that the payload has started. |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1836 | pub fn notify_payload_started(&self, cid: Cid) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1837 | let callbacks = &*self.0.lock().unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1838 | for callback in callbacks { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1839 | if let Err(e) = callback.onPayloadStarted(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1840 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1841 | } |
| 1842 | } |
| 1843 | } |
| 1844 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1845 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 1846 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 1847 | let callbacks = &*self.0.lock().unwrap(); |
| 1848 | for callback in callbacks { |
| 1849 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1850 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1851 | } |
| 1852 | } |
| 1853 | } |
| 1854 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1855 | /// Call all registered callbacks to notify that the payload has finished. |
| 1856 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 1857 | let callbacks = &*self.0.lock().unwrap(); |
| 1858 | for callback in callbacks { |
| 1859 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1860 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1861 | } |
| 1862 | } |
| 1863 | } |
| 1864 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1865 | /// Call all registered callbacks to say that the VM encountered an error. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1866 | pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1867 | let callbacks = &*self.0.lock().unwrap(); |
| 1868 | for callback in callbacks { |
| 1869 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1870 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1871 | } |
| 1872 | } |
| 1873 | } |
| 1874 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1875 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1876 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1877 | let mut callbacks = self.0.lock().unwrap(); |
| 1878 | for callback in &*callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1879 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1880 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1881 | } |
| 1882 | } |
Jaewan Kim | 27ac183 | 2025-02-03 23:42:08 +0900 | [diff] [blame] | 1883 | |
| 1884 | // Nothing to notify afterward because VM cannot be restarted. |
| 1885 | // Explicitly clear callbacks to prevent potential cyclic references |
| 1886 | // between callback and VmInstance. |
| 1887 | (*callbacks).clear(); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1888 | } |
| 1889 | |
| 1890 | /// Add a new callback to the set. |
| 1891 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 1892 | self.0.lock().unwrap().push(callback); |
| 1893 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1894 | } |
| 1895 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 1896 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 1897 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 1898 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1899 | struct State { |
Alan Stokes | 3e5eec1 | 2023-09-07 12:10:00 +0100 | [diff] [blame] | 1900 | /// The VMs which have been started. When VMs are started a weak reference is added to this |
| 1901 | /// list while a strong reference is returned to the caller over Binder. Once all copies of |
| 1902 | /// the Binder client are dropped the weak reference here will become invalid, and will be |
| 1903 | /// removed from the list opportunistically the next time `add_vm` is called. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1904 | vms: Vec<Weak<VmInstance>>, |
| 1905 | } |
| 1906 | |
| 1907 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1908 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1909 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 1910 | // Attempt to upgrade the weak pointers to strong pointers. |
| 1911 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 1912 | } |
| 1913 | |
| 1914 | /// Add a new VM to the list. |
| 1915 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 1916 | // Garbage collect any entries from the stored list which no longer exist. |
| 1917 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 1918 | |
| 1919 | // Actually add the new VM. |
| 1920 | self.vms.push(vm); |
| 1921 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1922 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1923 | /// Get a VM that corresponds to the given cid |
| 1924 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 1925 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 1926 | } |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 1927 | } |
| 1928 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1929 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 1930 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1931 | match &*instance.vm_state.lock().unwrap() { |
| 1932 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 1933 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1934 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 1935 | PayloadState::Started => VirtualMachineState::STARTED, |
| 1936 | PayloadState::Ready => VirtualMachineState::READY, |
| 1937 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 1938 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1939 | }, |
| 1940 | VmState::Dead => VirtualMachineState::DEAD, |
| 1941 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1942 | } |
| 1943 | } |
| 1944 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1945 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1946 | pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> { |
| 1947 | file.as_ref() |
| 1948 | .try_clone() |
| 1949 | .context("Failed to clone File from ParcelFileDescriptor") |
| 1950 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Andrei Homescu | 11333c6 | 2023-11-09 04:26:39 +0000 | [diff] [blame] | 1951 | .map(File::from) |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1952 | } |
| 1953 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1954 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1955 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> { |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1956 | file.as_ref().map(clone_file).transpose() |
| 1957 | } |
| 1958 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1959 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
Jiyong Park | af63d1c | 2024-09-04 16:15:42 +0900 | [diff] [blame] | 1960 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1961 | // SAFETY: ownership is transferred from stream to f |
| 1962 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1963 | ParcelFileDescriptor::new(f) |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1964 | } |
| 1965 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1966 | /// Parses the platform version requirement string. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1967 | fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> { |
| 1968 | VersionReq::parse(s) |
| 1969 | .with_context(|| format!("Invalid platform version requirement {}", s)) |
| 1970 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1971 | } |
| 1972 | |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1973 | /// Create the empty ramdump file |
| 1974 | fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> { |
| 1975 | // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where |
| 1976 | // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM |
| 1977 | // owner) for readout. |
| 1978 | let ramdump_path = temporary_directory.join("ramdump"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1979 | let ramdump = File::create(ramdump_path) |
| 1980 | .context("Failed to prepare ramdump file") |
| 1981 | .with_log() |
| 1982 | .or_service_specific_exception(-1)?; |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1983 | Ok(ramdump) |
| 1984 | } |
| 1985 | |
Pierre-Clément Tosi | 9515d0f | 2024-04-15 15:58:07 +0100 | [diff] [blame] | 1986 | /// Create the empty device tree dump file |
| 1987 | fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> { |
| 1988 | let path = temporary_directory.join("device_tree.dtb"); |
| 1989 | let file = File::create(path) |
| 1990 | .context("Failed to prepare device tree dump file") |
| 1991 | .with_log() |
| 1992 | .or_service_specific_exception(-1)?; |
| 1993 | Ok(file) |
| 1994 | } |
| 1995 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1996 | fn is_protected(config: &VirtualMachineConfig) -> bool { |
| 1997 | match config { |
| 1998 | VirtualMachineConfig::RawConfig(config) => config.protectedVm, |
| 1999 | VirtualMachineConfig::AppConfig(config) => config.protectedVm, |
| 2000 | } |
| 2001 | } |
| 2002 | |
| 2003 | fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2004 | if is_protected(config) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2005 | return Err(anyhow!("Can't use gdb with protected VMs")) |
| 2006 | .or_binder_exception(ExceptionCode::SECURITY); |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2007 | } |
| 2008 | |
Pierre-Clément Tosi | d3bbe1d | 2024-04-15 18:03:51 +0100 | [diff] [blame] | 2009 | if get_debug_level(config) == Some(DebugLevel::NONE) { |
| 2010 | return Err(anyhow!("Can't use gdb with non-debuggable VMs")) |
| 2011 | .or_binder_exception(ExceptionCode::SECURITY); |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2012 | } |
Pierre-Clément Tosi | d3bbe1d | 2024-04-15 18:03:51 +0100 | [diff] [blame] | 2013 | |
| 2014 | Ok(()) |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2015 | } |
| 2016 | |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 2017 | fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] { |
| 2018 | match config { |
| 2019 | VirtualMachineConfig::RawConfig(config) => config.instanceId, |
| 2020 | VirtualMachineConfig::AppConfig(config) => config.instanceId, |
| 2021 | } |
| 2022 | } |
| 2023 | |
Alan Stokes | c96b35e | 2024-05-03 13:21:20 +0100 | [diff] [blame] | 2024 | fn extract_want_updatable(config: &VirtualMachineConfig) -> bool { |
| 2025 | match config { |
| 2026 | VirtualMachineConfig::RawConfig(_) => true, |
| 2027 | VirtualMachineConfig::AppConfig(config) => { |
| 2028 | let Some(custom) = &config.customConfig else { return true }; |
| 2029 | custom.wantUpdatable |
| 2030 | } |
| 2031 | } |
| 2032 | } |
| 2033 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2034 | fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> { |
| 2035 | match config { |
| 2036 | VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16), |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 2037 | VirtualMachineConfig::AppConfig(config) => { |
| 2038 | NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16) |
| 2039 | } |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 2040 | } |
| 2041 | } |
| 2042 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2043 | fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2044 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2045 | if let Some(custom_config) = &config.customConfig { |
| 2046 | if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() { |
| 2047 | return Err(anyhow!("vendor modules feature is disabled")) |
| 2048 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2049 | } |
| 2050 | } |
| 2051 | Ok(()) |
| 2052 | } |
| 2053 | |
Nikita Ioffe | 94a8a18 | 2023-11-16 16:37:48 +0000 | [diff] [blame] | 2054 | fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2055 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2056 | if let Some(custom_config) = &config.customConfig { |
| 2057 | if !custom_config.devices.is_empty() { |
| 2058 | return Err(anyhow!("device assignment feature is disabled")) |
| 2059 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2060 | } |
| 2061 | } |
| 2062 | Ok(()) |
| 2063 | } |
| 2064 | |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 2065 | fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2066 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2067 | let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) }; |
| 2068 | if !payload_config.extraApks.is_empty() { |
| 2069 | return Err(anyhow!("multi-tenant feature is disabled")) |
| 2070 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2071 | } |
| 2072 | Ok(()) |
| 2073 | } |
| 2074 | |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 2075 | fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2076 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 2077 | if let Some(custom_config) = &config.customConfig { |
| 2078 | if !custom_config.extraKernelCmdlineParams.is_empty() { |
| 2079 | return Err(anyhow!("debuggable_vms_improvements feature is disabled")) |
| 2080 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2081 | } |
| 2082 | } |
| 2083 | Ok(()) |
| 2084 | } |
| 2085 | |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 2086 | fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2087 | match config { |
| 2088 | VirtualMachineConfig::RawConfig(config) => { |
| 2089 | if !config.teeServices.is_empty() { |
| 2090 | return Err(anyhow!("tee_services_allowlist feature is disabled")) |
| 2091 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2092 | } |
| 2093 | } |
| 2094 | VirtualMachineConfig::AppConfig(config) => { |
| 2095 | if let Some(custom_config) = &config.customConfig { |
| 2096 | if !custom_config.teeServices.is_empty() { |
| 2097 | return Err(anyhow!("tee_services_allowlist feature is disabled")) |
| 2098 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 2099 | } |
| 2100 | } |
| 2101 | } |
| 2102 | }; |
| 2103 | Ok(()) |
| 2104 | } |
| 2105 | |
Nikita Ioffe | f934e81 | 2024-07-05 15:44:41 +0000 | [diff] [blame] | 2106 | fn check_protected_vm_is_supported() -> binder::Result<()> { |
| 2107 | let is_pvm_supported = |
| 2108 | hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?; |
| 2109 | if is_pvm_supported { |
| 2110 | Ok(()) |
| 2111 | } else { |
| 2112 | Err(anyhow!("pVM is not supported")) |
| 2113 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION) |
| 2114 | } |
| 2115 | } |
| 2116 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2117 | fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2118 | if !cfg!(vendor_modules) { |
| 2119 | check_no_vendor_modules(config)?; |
| 2120 | } |
Nikita Ioffe | 94a8a18 | 2023-11-16 16:37:48 +0000 | [diff] [blame] | 2121 | if !cfg!(device_assignment) { |
| 2122 | check_no_devices(config)?; |
| 2123 | } |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 2124 | if !cfg!(multi_tenant) { |
| 2125 | check_no_extra_apks(config)?; |
| 2126 | } |
Nikita Ioffe | b4268b3 | 2024-09-03 10:23:14 +0000 | [diff] [blame] | 2127 | if !cfg!(debuggable_vms_improvements) { |
| 2128 | check_no_extra_kernel_cmdline_params(config)?; |
| 2129 | } |
Nikita Ioffe | 9954838 | 2024-10-21 15:54:46 +0000 | [diff] [blame] | 2130 | if !cfg!(tee_services_allowlist) { |
| 2131 | check_no_tee_services(config)?; |
| 2132 | } |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 2133 | Ok(()) |
| 2134 | } |
| 2135 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2136 | fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 2137 | check_no_vendor_modules(config)?; |
| 2138 | check_no_devices(config)?; |
| 2139 | |
| 2140 | Ok(()) |
| 2141 | } |
| 2142 | |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2143 | fn clone_or_prepare_logger_fd( |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2144 | fd: Option<&ParcelFileDescriptor>, |
| 2145 | tag: String, |
| 2146 | ) -> Result<Option<File>, Status> { |
| 2147 | if let Some(fd) = fd { |
| 2148 | return Ok(Some(clone_file(fd)?)); |
| 2149 | } |
| 2150 | |
Frederick Mayle | fbbcfcd | 2024-04-08 16:31:54 -0700 | [diff] [blame] | 2151 | let (read_fd, write_fd) = |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2152 | pipe().context("Failed to create pipe").or_service_specific_exception(-1)?; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2153 | |
Frederick Mayle | fbbcfcd | 2024-04-08 16:31:54 -0700 | [diff] [blame] | 2154 | let mut reader = BufReader::new(File::from(read_fd)); |
| 2155 | let write_fd = File::from(write_fd); |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2156 | |
Frederick Mayle | 26e41af | 2025-02-05 18:30:29 -0800 | [diff] [blame] | 2157 | let mut buf = vec![]; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2158 | std::thread::spawn(move || loop { |
Frederick Mayle | 26e41af | 2025-02-05 18:30:29 -0800 | [diff] [blame] | 2159 | buf.clear(); |
| 2160 | buf.shrink_to(1024); |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2161 | match reader.read_until(b'\n', &mut buf) { |
| 2162 | Ok(0) => { |
| 2163 | // EOF |
| 2164 | return; |
| 2165 | } |
Frederick Mayle | 690ec2c | 2025-02-05 18:31:33 -0800 | [diff] [blame] | 2166 | Ok(_size) => { |
| 2167 | if buf.last() == Some(&b'\n') { |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2168 | buf.pop(); |
Frederick Mayle | 690ec2c | 2025-02-05 18:31:33 -0800 | [diff] [blame] | 2169 | // Logs sent via TTY usually end lines with "\r\n". |
| 2170 | if buf.last() == Some(&b'\r') { |
| 2171 | buf.pop(); |
| 2172 | } |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 2173 | } |
| 2174 | info!("{}: {}", &tag, &String::from_utf8_lossy(&buf)); |
| 2175 | } |
| 2176 | Err(e) => { |
| 2177 | error!("Could not read console pipe: {:?}", e); |
| 2178 | return; |
| 2179 | } |
| 2180 | }; |
| 2181 | }); |
| 2182 | |
| 2183 | Ok(Some(write_fd)) |
| 2184 | } |
| 2185 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2186 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 2187 | /// it doesn't require that T implements Clone. |
| 2188 | enum BorrowedOrOwned<'a, T> { |
| 2189 | Borrowed(&'a T), |
| 2190 | Owned(T), |
| 2191 | } |
| 2192 | |
Chris Wailes | 73a1eb7 | 2025-01-15 11:56:43 -0800 | [diff] [blame] | 2193 | impl<T> AsRef<T> for BorrowedOrOwned<'_, T> { |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2194 | fn as_ref(&self) -> &T { |
| 2195 | match self { |
| 2196 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 2197 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 2198 | } |
| 2199 | } |
| 2200 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2201 | |
| 2202 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 2203 | #[derive(Debug, Default)] |
| 2204 | struct VirtualMachineService { |
| 2205 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2206 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2207 | } |
| 2208 | |
| 2209 | impl Interface for VirtualMachineService {} |
| 2210 | |
| 2211 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2212 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 2213 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 2214 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2215 | info!("VM with CID {} started payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2216 | vm.update_payload_state(PayloadState::Started) |
| 2217 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 2218 | vm.callbacks.notify_payload_started(cid); |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 2219 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 2220 | let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp; |
| 2221 | 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] | 2222 | Ok(()) |
| 2223 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2224 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2225 | 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] | 2226 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2227 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2228 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2229 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 2230 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 2231 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2232 | info!("VM with CID {} reported payload is ready", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2233 | vm.update_payload_state(PayloadState::Ready) |
| 2234 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 2235 | vm.callbacks.notify_payload_ready(cid); |
| 2236 | Ok(()) |
| 2237 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2238 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2239 | 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] | 2240 | } |
| 2241 | } |
| 2242 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2243 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 2244 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2245 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2246 | info!("VM with CID {} finished payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2247 | vm.update_payload_state(PayloadState::Finished) |
| 2248 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 2249 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 2250 | Ok(()) |
| 2251 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2252 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2253 | 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] | 2254 | } |
| 2255 | } |
| 2256 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 2257 | fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2258 | let cid = self.cid; |
| 2259 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 2260 | info!("VM with CID {} encountered an error", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2261 | vm.update_payload_state(PayloadState::Finished) |
| 2262 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 2263 | vm.callbacks.notify_error(cid, error_code, message); |
| 2264 | Ok(()) |
| 2265 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 2266 | error!("notifyError is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 2267 | 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] | 2268 | } |
| 2269 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 2270 | |
Shikha Panwar | e45e942 | 2024-02-28 21:18:10 +0000 | [diff] [blame] | 2271 | fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> { |
| 2272 | if !is_secretkeeper_supported() { |
| 2273 | return Err(StatusCode::NAME_NOT_FOUND)?; |
| 2274 | } |
| 2275 | let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?; |
| 2276 | Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default())) |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 2277 | } |
| 2278 | |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 2279 | fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> { |
| 2280 | GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode) |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 2281 | } |
Shikha Panwar | eeae640 | 2025-02-06 19:05:31 +0000 | [diff] [blame] | 2282 | |
| 2283 | fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> { |
| 2284 | GLOBAL_SERVICE.claimSecretkeeperEntry(id) |
| 2285 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2286 | } |
| 2287 | |
Shikha Panwar | 8707f0f | 2024-02-28 20:40:42 +0000 | [diff] [blame] | 2288 | fn is_secretkeeper_supported() -> bool { |
Shikha Panwar | 81d13d3 | 2024-03-10 19:39:23 +0000 | [diff] [blame] | 2289 | binder::is_declared(SECRETKEEPER_IDENTIFIER) |
| 2290 | .expect("Could not check for declared Secretkeeper interface") |
Shikha Panwar | 8187ca2 | 2024-01-04 08:33:08 +0000 | [diff] [blame] | 2291 | } |
| 2292 | |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2293 | impl VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2294 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2295 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 2296 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 2297 | BinderFeatures::default(), |
| 2298 | ) |
| 2299 | } |
| 2300 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2301 | |
Stephen Hines | 4c1e2fc | 2024-02-09 16:34:47 -0800 | [diff] [blame] | 2302 | struct SecretkeeperProxy(Strong<dyn ISecretkeeper>); |
| 2303 | |
| 2304 | impl Interface for SecretkeeperProxy {} |
| 2305 | |
| 2306 | impl ISecretkeeper for SecretkeeperProxy { |
| 2307 | fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> { |
| 2308 | // Pass the request to the channel, and read the response. |
| 2309 | self.0.processSecretManagementRequest(req) |
| 2310 | } |
| 2311 | |
| 2312 | fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> { |
| 2313 | let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?); |
| 2314 | Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default())) |
| 2315 | } |
| 2316 | |
| 2317 | fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> { |
| 2318 | self.0.deleteIds(ids) |
| 2319 | } |
| 2320 | |
| 2321 | fn deleteAll(&self) -> binder::Result<()> { |
| 2322 | self.0.deleteAll() |
| 2323 | } |
Matt Gilbride | b57abcc | 2024-10-12 15:26:45 +0000 | [diff] [blame] | 2324 | |
| 2325 | fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> { |
| 2326 | // SecretkeeperProxy is really a RPC binder service for PVM (It is called by |
| 2327 | // MicrodroidManager). PVMs do not & must not (for security reason) rely on |
| 2328 | // getSecretKeeperIdentity, so we throw an exception if someone attempts to |
| 2329 | // use this API from the proxy. |
| 2330 | Err(ExceptionCode::SECURITY.into()) |
| 2331 | } |
Stephen Hines | 4c1e2fc | 2024-02-09 16:34:47 -0800 | [diff] [blame] | 2332 | } |
| 2333 | |
| 2334 | struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>); |
| 2335 | |
| 2336 | impl Interface for AuthGraphKeyExchangeProxy {} |
| 2337 | |
| 2338 | impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy { |
| 2339 | fn create(&self) -> binder::Result<SessionInitiationInfo> { |
| 2340 | self.0.create() |
| 2341 | } |
| 2342 | |
| 2343 | fn init( |
| 2344 | &self, |
| 2345 | peer_pub_key: &PubKey, |
| 2346 | peer_id: &Identity, |
| 2347 | peer_nonce: &[u8], |
| 2348 | peer_version: i32, |
| 2349 | ) -> binder::Result<KeInitResult> { |
| 2350 | self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version) |
| 2351 | } |
| 2352 | |
| 2353 | fn finish( |
| 2354 | &self, |
| 2355 | peer_pub_key: &PubKey, |
| 2356 | peer_id: &Identity, |
| 2357 | peer_signature: &SessionIdSignature, |
| 2358 | peer_nonce: &[u8], |
| 2359 | peer_version: i32, |
| 2360 | own_key: &Key, |
| 2361 | ) -> binder::Result<SessionInfo> { |
| 2362 | self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key) |
| 2363 | } |
| 2364 | |
| 2365 | fn authenticationComplete( |
| 2366 | &self, |
| 2367 | peer_signature: &SessionIdSignature, |
| 2368 | shared_keys: &[AuthgraphArc; 2], |
| 2369 | ) -> binder::Result<[AuthgraphArc; 2]> { |
| 2370 | self.0.authenticationComplete(peer_signature, shared_keys) |
| 2371 | } |
| 2372 | } |
| 2373 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2374 | // KEEP IN SYNC WITH early_vms.xsd |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2375 | #[derive(Clone, Debug, Deserialize, PartialEq)] |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2376 | struct EarlyVm { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2377 | name: String, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2378 | cid: i32, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2379 | path: String, |
| 2380 | } |
| 2381 | |
| 2382 | #[derive(Debug, Default, Deserialize)] |
| 2383 | struct EarlyVms { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2384 | early_vm: Vec<EarlyVm>, |
| 2385 | } |
| 2386 | |
Alice Wang | 78dd87a | 2025-02-13 08:56:07 +0000 | [diff] [blame] | 2387 | impl EarlyVm { |
| 2388 | /// Verifies that the provided executable path matches the expected path stored in the XML |
| 2389 | /// configuration. |
| 2390 | /// If the provided path starts with `/system`, it will be stripped before comparison. |
| 2391 | fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> { |
| 2392 | let actual_path = calling_exe_path.as_ref(); |
| 2393 | if Path::new(&self.path) |
| 2394 | == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path)) |
| 2395 | { |
| 2396 | return Ok(()); |
| 2397 | } |
| 2398 | Err(Status::new_service_specific_error_str( |
| 2399 | -1, |
| 2400 | Some(format!( |
| 2401 | "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.", |
| 2402 | self.name, |
| 2403 | self.path, |
| 2404 | actual_path.display() |
| 2405 | )), |
| 2406 | )) |
| 2407 | } |
| 2408 | } |
| 2409 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2410 | static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> = |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2411 | LazyLock::new(|| Mutex::new(HashMap::new())); |
| 2412 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2413 | fn range_for_partition(partition: CallingPartition) -> Range<Cid> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2414 | match partition { |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2415 | CallingPartition::System => 100..200, |
| 2416 | CallingPartition::SystemExt | CallingPartition::Product => 200..300, |
| 2417 | CallingPartition::Vendor | CallingPartition::Odm => 300..400, |
| 2418 | CallingPartition::Unknown => 0..0, |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2419 | } |
| 2420 | } |
| 2421 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2422 | fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2423 | if !xml_path.exists() { |
| 2424 | bail!("{} doesn't exist", xml_path.display()); |
| 2425 | } |
| 2426 | |
| 2427 | let xml = |
| 2428 | fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?; |
| 2429 | let xml = String::from_utf8(xml) |
| 2430 | .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?; |
| 2431 | let early_vms: EarlyVms = serde_xml_rs::from_str(&xml) |
| 2432 | .with_context(|| format!("Can't parse {}", xml_path.display()))?; |
| 2433 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2434 | Ok(early_vms.early_vm) |
| 2435 | } |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2436 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2437 | fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> { |
| 2438 | for early_vm in early_vms { |
| 2439 | let cid = early_vm |
| 2440 | .cid |
| 2441 | .try_into() |
| 2442 | .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?; |
| 2443 | |
| 2444 | ensure!( |
| 2445 | cid_range.contains(&cid), |
| 2446 | "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}", |
| 2447 | early_vm.name |
| 2448 | ); |
| 2449 | } |
| 2450 | Ok(()) |
| 2451 | } |
| 2452 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2453 | fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2454 | let mut cache = EARLY_VMS_CACHE.lock().unwrap(); |
| 2455 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2456 | if let Some(result) = cache.get(&partition) { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2457 | return Ok(result.clone()); |
| 2458 | } |
| 2459 | |
| 2460 | let pattern = format!("/{partition}/etc/avf/early_vms*.xml"); |
| 2461 | let mut early_vms = Vec::new(); |
| 2462 | for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? { |
| 2463 | match entry { |
| 2464 | Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?), |
| 2465 | Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e), |
| 2466 | } |
| 2467 | } |
| 2468 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2469 | validate_cid_range(&early_vms, &range_for_partition(partition)) |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2470 | .with_context(|| format!("CID validation for {partition} failed"))?; |
| 2471 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2472 | cache.insert(partition, early_vms.clone()); |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2473 | |
| 2474 | Ok(early_vms) |
| 2475 | } |
| 2476 | |
| 2477 | fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> { |
| 2478 | let mut found_vm: Option<&EarlyVm> = None; |
| 2479 | |
| 2480 | for early_vm in early_vms { |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2481 | if early_vm.name != name { |
| 2482 | continue; |
| 2483 | } |
| 2484 | |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2485 | if found_vm.is_some() { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2486 | bail!("Multiple VMs named '{name}' are found"); |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2487 | } |
| 2488 | |
| 2489 | found_vm = Some(early_vm); |
| 2490 | } |
| 2491 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2492 | 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] | 2493 | } |
| 2494 | |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2495 | fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> { |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2496 | let early_vms = get_early_vms_in_partition(partition) |
| 2497 | .with_context(|| format!("Failed to get early VMs from {partition}"))?; |
| 2498 | |
| 2499 | Ok(find_early_vm(&early_vms, name) |
| 2500 | .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))? |
| 2501 | .clone()) |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2502 | } |
| 2503 | |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2504 | #[cfg(test)] |
| 2505 | mod tests { |
| 2506 | use super::*; |
| 2507 | |
| 2508 | #[test] |
| 2509 | fn test_is_allowed_label_for_partition() -> Result<()> { |
| 2510 | let expected_results = vec![ |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2511 | (CallingPartition::System, "u:object_r:system_file:s0", true), |
| 2512 | (CallingPartition::System, "u:object_r:apk_data_file:s0", true), |
| 2513 | (CallingPartition::System, "u:object_r:app_data_file:s0", false), |
| 2514 | (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false), |
| 2515 | (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false), |
| 2516 | (CallingPartition::System, "invalid", false), |
| 2517 | (CallingPartition::System, "user:role:apk_data_file:severity:categories", true), |
| 2518 | ( |
| 2519 | CallingPartition::System, |
| 2520 | "user:role:apk_data_file:severity:categories:extraneous", |
| 2521 | false, |
| 2522 | ), |
| 2523 | (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false), |
| 2524 | (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true), |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2525 | ]; |
| 2526 | |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2527 | for (calling_partition, label, expected_valid) in expected_results { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2528 | let context = SeContext::new(label)?; |
Frederick Mayle | 50c2b6a | 2025-02-11 18:26:04 -0800 | [diff] [blame] | 2529 | let result = check_label_is_allowed(&context, calling_partition); |
| 2530 | if expected_valid != result.is_ok() { |
| 2531 | bail!( |
| 2532 | "Expected label {label} to be {} for {calling_partition} partition", |
| 2533 | if expected_valid { "allowed" } else { "disallowed" } |
| 2534 | ); |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2535 | } |
| 2536 | } |
| 2537 | Ok(()) |
| 2538 | } |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 2539 | |
| 2540 | #[test] |
| 2541 | fn test_create_or_update_idsig_file_empty_apk() -> Result<()> { |
| 2542 | let apk = tempfile::tempfile().unwrap(); |
| 2543 | let idsig = tempfile::tempfile().unwrap(); |
| 2544 | |
| 2545 | let ret = create_or_update_idsig_file( |
| 2546 | &ParcelFileDescriptor::new(apk), |
| 2547 | &ParcelFileDescriptor::new(idsig), |
| 2548 | ); |
| 2549 | assert!(ret.is_err(), "should fail"); |
| 2550 | Ok(()) |
| 2551 | } |
| 2552 | |
| 2553 | #[test] |
| 2554 | fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> { |
| 2555 | let tmp_dir = tempfile::TempDir::new().unwrap(); |
| 2556 | let apk = File::open(tmp_dir.path()).unwrap(); |
| 2557 | let idsig = tempfile::tempfile().unwrap(); |
| 2558 | |
| 2559 | let ret = create_or_update_idsig_file( |
| 2560 | &ParcelFileDescriptor::new(apk), |
| 2561 | &ParcelFileDescriptor::new(idsig), |
| 2562 | ); |
| 2563 | assert!(ret.is_err(), "should fail"); |
| 2564 | Ok(()) |
| 2565 | } |
| 2566 | |
| 2567 | /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory |
| 2568 | /// on ext4 filesystem is passed. |
| 2569 | /// On ext4 lseek on a directory fd will return (off_t)-1 (see: |
| 2570 | /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in |
| 2571 | /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory. |
| 2572 | #[test] |
| 2573 | fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> { |
| 2574 | // APEXes are backed by the ext4. |
| 2575 | let apk = File::open("/apex/com.android.virt/").unwrap(); |
| 2576 | let idsig = tempfile::tempfile().unwrap(); |
| 2577 | |
| 2578 | let ret = create_or_update_idsig_file( |
| 2579 | &ParcelFileDescriptor::new(apk), |
| 2580 | &ParcelFileDescriptor::new(idsig), |
| 2581 | ); |
| 2582 | assert!(ret.is_err(), "should fail"); |
| 2583 | Ok(()) |
| 2584 | } |
Jiyong Park | 8d19295 | 2023-06-26 14:29:51 +0900 | [diff] [blame] | 2585 | |
| 2586 | #[test] |
| 2587 | fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> { |
| 2588 | use std::io::Seek; |
| 2589 | |
| 2590 | // Pick any APK |
| 2591 | let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap(); |
| 2592 | let mut idsig = tempfile::tempfile().unwrap(); |
| 2593 | |
| 2594 | create_or_update_idsig_file( |
| 2595 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2596 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 2597 | )?; |
| 2598 | let modified_orig = idsig.metadata()?.modified()?; |
| 2599 | apk.rewind()?; |
| 2600 | idsig.rewind()?; |
| 2601 | |
| 2602 | // Call the function again |
| 2603 | create_or_update_idsig_file( |
| 2604 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2605 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 2606 | )?; |
| 2607 | let modified_new = idsig.metadata()?.modified()?; |
| 2608 | assert!(modified_orig == modified_new, "idsig file was updated unnecessarily"); |
| 2609 | Ok(()) |
| 2610 | } |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 2611 | |
| 2612 | #[test] |
Shikha Panwar | 9ae2e62 | 2024-01-30 12:22:30 +0000 | [diff] [blame] | 2613 | fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> { |
| 2614 | use std::io::Read; |
| 2615 | |
| 2616 | // Pick any APK |
| 2617 | let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap(); |
| 2618 | let idsig_empty = tempfile::tempfile().unwrap(); |
| 2619 | let mut idsig_invalid = tempfile::tempfile().unwrap(); |
| 2620 | idsig_invalid.write_all(b"Oops")?; |
| 2621 | |
| 2622 | // Create new idsig |
| 2623 | create_or_update_idsig_file( |
| 2624 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2625 | &ParcelFileDescriptor::new(idsig_empty.try_clone()?), |
| 2626 | )?; |
| 2627 | apk.rewind()?; |
| 2628 | |
| 2629 | // Update idsig_invalid |
| 2630 | create_or_update_idsig_file( |
| 2631 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 2632 | &ParcelFileDescriptor::new(idsig_invalid.try_clone()?), |
| 2633 | )?; |
| 2634 | |
| 2635 | // Ensure the 2 idsig files have same size! |
| 2636 | assert!( |
| 2637 | idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(), |
| 2638 | "idsig files differ in size" |
| 2639 | ); |
| 2640 | // Ensure the 2 idsig files have same content! |
| 2641 | for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) { |
| 2642 | assert!(b1.unwrap() == b2.unwrap(), "idsig files differ") |
| 2643 | } |
| 2644 | Ok(()) |
| 2645 | } |
| 2646 | #[test] |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 2647 | fn test_append_kernel_param_first_param() { |
| 2648 | let mut vm_config = VirtualMachineRawConfig { ..Default::default() }; |
| 2649 | append_kernel_param("foo=1", &mut vm_config); |
| 2650 | assert_eq!(vm_config.params, Some("foo=1".to_owned())) |
| 2651 | } |
| 2652 | |
| 2653 | #[test] |
| 2654 | fn test_append_kernel_param() { |
| 2655 | let mut vm_config = |
| 2656 | VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() }; |
| 2657 | append_kernel_param("bar=42", &mut vm_config); |
| 2658 | assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned())) |
| 2659 | } |
Seungjae Yoo | ec3bc52 | 2023-11-09 10:14:30 +0900 | [diff] [blame] | 2660 | |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 2661 | fn test_extract_os_name_from_config_path( |
| 2662 | path: &Path, |
| 2663 | expected_result: Option<&str>, |
| 2664 | ) -> Result<()> { |
| 2665 | let result = extract_os_name_from_config_path(path); |
| 2666 | if result.as_deref() != expected_result { |
| 2667 | bail!("Expected {:?} but was {:?}", expected_result, &result) |
| 2668 | } |
| 2669 | Ok(()) |
| 2670 | } |
| 2671 | |
| 2672 | #[test] |
| 2673 | fn test_extract_os_name_from_microdroid_config() -> Result<()> { |
| 2674 | test_extract_os_name_from_config_path( |
| 2675 | Path::new("/apex/com.android.virt/etc/microdroid.json"), |
| 2676 | Some("microdroid"), |
| 2677 | ) |
| 2678 | } |
| 2679 | |
| 2680 | #[test] |
Nikita Ioffe | f49350e | 2024-11-01 16:11:48 +0000 | [diff] [blame] | 2681 | fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> { |
| 2682 | test_extract_os_name_from_config_path( |
| 2683 | Path::new("/apex/com.android.virt/etc/microdroid_16k.json"), |
| 2684 | Some("microdroid_16k"), |
| 2685 | ) |
| 2686 | } |
| 2687 | |
| 2688 | #[test] |
Inseob Kim | 4625738 | 2024-01-03 15:41:22 +0900 | [diff] [blame] | 2689 | fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> { |
| 2690 | test_extract_os_name_from_config_path( |
| 2691 | Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"), |
| 2692 | Some("microdroid_gki-android14-6.1"), |
| 2693 | ) |
| 2694 | } |
| 2695 | |
| 2696 | #[test] |
| 2697 | fn test_extract_os_name_from_invalid_path() -> Result<()> { |
| 2698 | test_extract_os_name_from_config_path( |
| 2699 | Path::new("/apex/com.android.virt/etc/microdroid.img"), |
| 2700 | None, |
| 2701 | ) |
| 2702 | } |
| 2703 | |
| 2704 | #[test] |
| 2705 | fn test_extract_os_name_from_configs() -> Result<()> { |
| 2706 | let tmp_dir = tempfile::TempDir::new()?; |
| 2707 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2708 | |
| 2709 | let mut os_names: HashSet<String> = HashSet::new(); |
| 2710 | os_names.insert("microdroid".to_owned()); |
| 2711 | os_names.insert("microdroid_gki-android14-6.1".to_owned()); |
| 2712 | os_names.insert("microdroid_gki-android15-6.1".to_owned()); |
| 2713 | |
| 2714 | // config files |
| 2715 | for os_name in &os_names { |
| 2716 | std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?; |
| 2717 | } |
| 2718 | |
| 2719 | // fake files not related to configs |
| 2720 | std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?; |
| 2721 | std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?; |
| 2722 | |
| 2723 | let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() { |
| 2724 | Some(s) => s.to_owned(), |
| 2725 | None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path), |
| 2726 | }; |
| 2727 | |
| 2728 | let result = extract_os_names_from_configs(&glob_pattern)?; |
| 2729 | if result != os_names { |
| 2730 | bail!("Expected {:?} but was {:?}", os_names, result); |
| 2731 | } |
| 2732 | Ok(()) |
| 2733 | } |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2734 | |
| 2735 | #[test] |
| 2736 | fn test_find_early_vms_from_xml() -> Result<()> { |
| 2737 | let tmp_dir = tempfile::TempDir::new()?; |
| 2738 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2739 | let xml_path = tmp_dir_path.join("early_vms.xml"); |
| 2740 | |
| 2741 | std::fs::write( |
| 2742 | &xml_path, |
| 2743 | br#"<?xml version="1.0" encoding="utf-8"?> |
| 2744 | <early_vms> |
| 2745 | <early_vm> |
| 2746 | <name>vm_demo_native_early</name> |
| 2747 | <cid>123</cid> |
| 2748 | <path>/system/bin/vm_demo_native_early</path> |
| 2749 | </early_vm> |
| 2750 | <early_vm> |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2751 | <name>vm_demo_native_early_2</name> |
| 2752 | <cid>456</cid> |
| 2753 | <path>/system/bin/vm_demo_native_early_2</path> |
| 2754 | </early_vm> |
| 2755 | </early_vms> |
| 2756 | "#, |
| 2757 | )?; |
| 2758 | |
| 2759 | let cid_range = 100..1000; |
| 2760 | |
| 2761 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2762 | validate_cid_range(&early_vms, &cid_range)?; |
| 2763 | |
| 2764 | let test_cases = [ |
| 2765 | ( |
| 2766 | "vm_demo_native_early", |
| 2767 | EarlyVm { |
| 2768 | name: "vm_demo_native_early".to_owned(), |
| 2769 | cid: 123, |
| 2770 | path: "/system/bin/vm_demo_native_early".to_owned(), |
| 2771 | }, |
| 2772 | ), |
| 2773 | ( |
| 2774 | "vm_demo_native_early_2", |
| 2775 | EarlyVm { |
| 2776 | name: "vm_demo_native_early_2".to_owned(), |
| 2777 | cid: 456, |
| 2778 | path: "/system/bin/vm_demo_native_early_2".to_owned(), |
| 2779 | }, |
| 2780 | ), |
| 2781 | ]; |
| 2782 | |
| 2783 | for (name, expected) in test_cases { |
| 2784 | let result = find_early_vm(&early_vms, name)?; |
| 2785 | assert_eq!(result, &expected); |
| 2786 | } |
| 2787 | |
| 2788 | Ok(()) |
| 2789 | } |
| 2790 | |
| 2791 | #[test] |
| 2792 | fn test_invalid_cid_validation() -> Result<()> { |
| 2793 | let tmp_dir = tempfile::TempDir::new()?; |
| 2794 | let xml_path = tmp_dir.path().join("early_vms.xml"); |
| 2795 | |
| 2796 | let cid_range = 100..1000; |
| 2797 | |
| 2798 | for cid in [-1, 999999] { |
| 2799 | std::fs::write( |
| 2800 | &xml_path, |
| 2801 | format!( |
| 2802 | r#"<?xml version="1.0" encoding="utf-8"?> |
| 2803 | <early_vms> |
| 2804 | <early_vm> |
| 2805 | <name>vm_demo_invalid_cid</name> |
| 2806 | <cid>{cid}</cid> |
| 2807 | <path>/system/bin/vm_demo_invalid_cid</path> |
| 2808 | </early_vm> |
| 2809 | </early_vms> |
| 2810 | "# |
| 2811 | ), |
| 2812 | )?; |
| 2813 | |
| 2814 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2815 | assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail"); |
| 2816 | } |
| 2817 | |
| 2818 | Ok(()) |
| 2819 | } |
| 2820 | |
| 2821 | #[test] |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2822 | fn test_symlink_to_system_ext_supported() -> Result<()> { |
| 2823 | let link_path = Path::new("/system/system_ext/file"); |
| 2824 | let partition = find_partition(Some(link_path)).unwrap(); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2825 | assert_eq!(CallingPartition::SystemExt, partition); |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2826 | Ok(()) |
| 2827 | } |
| 2828 | |
| 2829 | #[test] |
| 2830 | fn test_symlink_to_product_supported() -> Result<()> { |
| 2831 | let link_path = Path::new("/system/product/file"); |
| 2832 | let partition = find_partition(Some(link_path)).unwrap(); |
Frederick Mayle | 3a46b27 | 2025-02-10 21:55:49 -0800 | [diff] [blame] | 2833 | assert_eq!(CallingPartition::Product, partition); |
Armelle Laine | 1a25d98 | 2025-01-31 06:39:54 +0000 | [diff] [blame] | 2834 | Ok(()) |
| 2835 | } |
| 2836 | |
| 2837 | #[test] |
Frederick Mayle | 2192baf | 2025-02-26 11:27:22 -0800 | [diff] [blame] | 2838 | fn test_vendor_in_data() { |
| 2839 | assert_eq!( |
| 2840 | CallingPartition::Vendor, |
| 2841 | find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap() |
| 2842 | ); |
| 2843 | } |
| 2844 | |
| 2845 | #[test] |
Alice Wang | 78dd87a | 2025-02-13 08:56:07 +0000 | [diff] [blame] | 2846 | fn early_vm_exe_paths_match_succeeds_with_same_paths() { |
| 2847 | let early_vm = EarlyVm { |
| 2848 | name: "vm_demo_native_early".to_owned(), |
| 2849 | cid: 123, |
| 2850 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2851 | }; |
| 2852 | let calling_exe_path = "/system_ext/bin/vm_demo_native_early"; |
| 2853 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok()) |
| 2854 | } |
| 2855 | |
| 2856 | #[test] |
| 2857 | fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() { |
| 2858 | let early_vm = EarlyVm { |
| 2859 | name: "vm_demo_native_early".to_owned(), |
| 2860 | cid: 123, |
| 2861 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2862 | }; |
| 2863 | let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early"; |
| 2864 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok()) |
| 2865 | } |
| 2866 | |
| 2867 | #[test] |
| 2868 | fn early_vm_exe_paths_match_fails_with_unmatched_paths() { |
| 2869 | let early_vm = EarlyVm { |
| 2870 | name: "vm_demo_native_early".to_owned(), |
| 2871 | cid: 123, |
| 2872 | path: "/system_ext/bin/vm_demo_native_early".to_owned(), |
| 2873 | }; |
| 2874 | let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early"; |
| 2875 | assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err()) |
| 2876 | } |
| 2877 | |
| 2878 | #[test] |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2879 | fn test_duplicated_early_vms() -> Result<()> { |
| 2880 | let tmp_dir = tempfile::TempDir::new()?; |
| 2881 | let tmp_dir_path = tmp_dir.path().to_owned(); |
| 2882 | let xml_path = tmp_dir_path.join("early_vms.xml"); |
| 2883 | |
| 2884 | std::fs::write( |
| 2885 | &xml_path, |
| 2886 | br#"<?xml version="1.0" encoding="utf-8"?> |
| 2887 | <early_vms> |
| 2888 | <early_vm> |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2889 | <name>vm_demo_duplicated_name</name> |
| 2890 | <cid>456</cid> |
| 2891 | <path>/system/bin/vm_demo_duplicated_name_1</path> |
| 2892 | </early_vm> |
| 2893 | <early_vm> |
| 2894 | <name>vm_demo_duplicated_name</name> |
| 2895 | <cid>789</cid> |
| 2896 | <path>/system/bin/vm_demo_duplicated_name_2</path> |
| 2897 | </early_vm> |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2898 | </early_vms> |
| 2899 | "#, |
| 2900 | )?; |
| 2901 | |
| 2902 | let cid_range = 100..1000; |
| 2903 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2904 | let early_vms = get_early_vms_in_path(&xml_path)?; |
| 2905 | validate_cid_range(&early_vms, &cid_range)?; |
Inseob Kim | ecde8c0 | 2024-09-03 13:11:08 +0900 | [diff] [blame] | 2906 | |
Inseob Kim | 7e1877b | 2024-11-07 17:28:56 +0900 | [diff] [blame] | 2907 | 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] | 2908 | |
| 2909 | Ok(()) |
| 2910 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 2911 | } |