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