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