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