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