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 | |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 17 | use crate::{get_calling_pid, get_calling_uid}; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 18 | use crate::atom::{ |
| 19 | forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom, |
| 20 | write_vm_booted_stats, write_vm_creation_stats}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 21 | use crate::composite::make_composite_image; |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 22 | use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState}; |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 23 | use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images}; |
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::{ |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 27 | DeathReason::DeathReason, |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 28 | ErrorCode::ErrorCode, |
| 29 | }; |
| 30 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 31 | DiskImage::DiskImage, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 32 | IVirtualMachine::{BnVirtualMachine, IVirtualMachine}, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 33 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 34 | IVirtualizationService::IVirtualizationService, |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 35 | MemoryTrimLevel::MemoryTrimLevel, |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 36 | Partition::Partition, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 37 | PartitionType::PartitionType, |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 38 | VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig}, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 39 | VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 40 | VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 41 | VirtualMachinePayloadConfig::VirtualMachinePayloadConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 42 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 43 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 44 | }; |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 45 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{ |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 46 | AtomVmBooted::AtomVmBooted, |
| 47 | AtomVmCreationRequested::AtomVmCreationRequested, |
| 48 | AtomVmExited::AtomVmExited, |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 49 | IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext}, |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 50 | IVirtualizationServiceInternal::IVirtualizationServiceInternal, |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 51 | }; |
Seungjae Yoo | dd91f0f | 2022-11-09 15:25:21 +0900 | [diff] [blame] | 52 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{ |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 53 | BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT, |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 54 | }; |
| 55 | use anyhow::{anyhow, bail, Context, Result}; |
| 56 | use apkverify::{HashAlgorithm, V4Signature}; |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 57 | use binder::{ |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 58 | self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, |
| 59 | ParcelFileDescriptor, Status, StatusCode, Strong, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 60 | }; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 61 | use disk::QcowFile; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 62 | use lazy_static::lazy_static; |
David Brazdil | a07a179 | 2022-10-25 13:37:57 +0100 | [diff] [blame] | 63 | use libc::VMADDR_CID_HOST; |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 64 | use log::{debug, error, info, warn}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 65 | use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig}; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 66 | use rpcbinder::RpcServer; |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 67 | use rustutils::system_properties; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 68 | use semver::VersionReq; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 69 | use std::collections::HashMap; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 70 | use std::convert::TryInto; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 71 | use std::ffi::CStr; |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 72 | use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, File, OpenOptions, Permissions}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 73 | use std::io::{Error, ErrorKind, Read, Write}; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 74 | use std::num::NonZeroU32; |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 75 | use std::os::unix::fs::PermissionsExt; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 76 | use std::os::unix::io::{FromRawFd, IntoRawFd}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 77 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 78 | use std::sync::{Arc, Mutex, Weak}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 79 | use tombstoned_client::{DebuggerdDumpType, TombstonedConnection}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 80 | use vmconfig::VmConfig; |
Andrew Walbran | add38cb | 2022-10-06 17:01:03 +0000 | [diff] [blame] | 81 | use vsock::{VsockListener, VsockStream}; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 82 | use zip::ZipArchive; |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 83 | use nix::unistd::{chown, Uid}; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 84 | |
David Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 85 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 86 | pub type Cid = u32; |
| 87 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 88 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
| 89 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 90 | /// Directory in which to write disk image files used while running VMs. |
Andrew Walbran | 488bd07 | 2021-07-14 13:29:51 +0000 | [diff] [blame] | 91 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 92 | |
David Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 93 | /// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this |
| 94 | /// are reserved for the host or other usage. |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 95 | const GUEST_CID_MIN: Cid = 2048; |
| 96 | const GUEST_CID_MAX: Cid = 65535; |
David Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 97 | |
| 98 | const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid"; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 99 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 100 | /// The size of zero.img. |
| 101 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 102 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 103 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 104 | /// Magic string for the instance image |
| 105 | const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance"; |
| 106 | |
| 107 | /// Version of the instance image format |
| 108 | const ANDROID_VM_INSTANCE_VERSION: u16 = 1; |
| 109 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 110 | const CHUNK_RECV_MAX_LEN: usize = 1024; |
| 111 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 112 | const MICRODROID_OS_NAME: &str = "microdroid"; |
| 113 | |
Shikha Panwar | 9fd198f | 2022-11-18 17:43:43 +0000 | [diff] [blame] | 114 | const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE"; |
| 115 | |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 116 | lazy_static! { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 117 | pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> = |
| 118 | wait_for_interface(BINDER_SERVICE_IDENTIFIER) |
| 119 | .expect("Could not connect to VirtualizationServiceInternal"); |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 120 | } |
| 121 | |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 122 | fn is_valid_guest_cid(cid: Cid) -> bool { |
| 123 | (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid) |
| 124 | } |
| 125 | |
| 126 | fn next_guest_cid(cid: Cid) -> Cid { |
| 127 | assert!(is_valid_guest_cid(cid)); |
| 128 | if cid == GUEST_CID_MAX { |
| 129 | GUEST_CID_MIN |
| 130 | } else { |
| 131 | cid + 1 |
| 132 | } |
| 133 | } |
| 134 | |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 135 | fn create_or_update_idsig_file( |
| 136 | input_fd: &ParcelFileDescriptor, |
| 137 | idsig_fd: &ParcelFileDescriptor, |
| 138 | ) -> Result<()> { |
| 139 | let mut input = clone_file(input_fd)?; |
| 140 | let metadata = input.metadata().context("failed to get input metadata")?; |
| 141 | if !metadata.is_file() { |
| 142 | bail!("input is not a regular file"); |
| 143 | } |
| 144 | let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256) |
| 145 | .context("failed to create idsig")?; |
| 146 | |
| 147 | let mut output = clone_file(idsig_fd)?; |
Nikita Ioffe | c09b049 | 2022-12-14 20:18:33 +0000 | [diff] [blame] | 148 | output.set_len(0).context("failed to set_len on the idsig output")?; |
| 149 | sig.write_into(&mut output).context("failed to write idsig")?; |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 150 | Ok(()) |
| 151 | } |
| 152 | |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 153 | /// Singleton service for allocating globally-unique VM resources, such as the CID, and running |
| 154 | /// singleton servers, like tombstone receiver. |
Jooyung Han | 9900f3d | 2021-07-06 10:27:54 +0900 | [diff] [blame] | 155 | #[derive(Debug, Default)] |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 156 | pub struct VirtualizationServiceInternal { |
| 157 | state: Arc<Mutex<GlobalState>>, |
| 158 | } |
| 159 | |
| 160 | impl VirtualizationServiceInternal { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 161 | // TODO(b/245727626): Remove after the source files for virtualizationservice |
| 162 | // and virtmgr binaries are split from each other. |
| 163 | #[allow(dead_code)] |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 164 | pub fn init() -> VirtualizationServiceInternal { |
| 165 | let service = VirtualizationServiceInternal::default(); |
| 166 | |
| 167 | std::thread::spawn(|| { |
| 168 | if let Err(e) = handle_stream_connection_tombstoned() { |
| 169 | warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e); |
| 170 | } |
| 171 | }); |
| 172 | |
| 173 | service |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | impl Interface for VirtualizationServiceInternal {} |
| 178 | |
| 179 | impl IVirtualizationServiceInternal for VirtualizationServiceInternal { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 180 | fn removeMemlockRlimit(&self) -> binder::Result<()> { |
| 181 | let pid = get_calling_pid(); |
| 182 | let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY }; |
| 183 | |
| 184 | // SAFETY - borrowing the new limit struct only |
| 185 | let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) }; |
| 186 | |
| 187 | match ret { |
| 188 | 0 => Ok(()), |
| 189 | -1 => Err(Status::new_exception_str( |
| 190 | ExceptionCode::ILLEGAL_STATE, |
| 191 | Some(std::io::Error::last_os_error().to_string()), |
| 192 | )), |
| 193 | n => Err(Status::new_exception_str( |
| 194 | ExceptionCode::ILLEGAL_STATE, |
| 195 | Some(format!("Unexpected return value from prlimit(): {n}")), |
| 196 | )), |
| 197 | } |
| 198 | } |
| 199 | |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 200 | fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 201 | let client_uid = Uid::from_raw(get_calling_uid()); |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 202 | let state = &mut *self.state.lock().unwrap(); |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 203 | state.allocate_vm_context(client_uid).map_err(|e| { |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 204 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 205 | }) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 206 | } |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 207 | |
| 208 | fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> { |
| 209 | forward_vm_booted_atom(atom); |
| 210 | Ok(()) |
| 211 | } |
| 212 | |
| 213 | fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> { |
| 214 | forward_vm_creation_atom(atom); |
| 215 | Ok(()) |
| 216 | } |
| 217 | |
| 218 | fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> { |
| 219 | forward_vm_exited_atom(atom); |
| 220 | Ok(()) |
| 221 | } |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | /// The mutable state of the VirtualizationServiceInternal. There should only be one instance |
| 225 | /// of this struct. |
| 226 | #[derive(Debug, Default)] |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 227 | struct GlobalState { |
| 228 | /// CIDs currently allocated to running VMs. A CID is never recycled as long |
| 229 | /// as there is a strong reference held by a GlobalVmContext. |
| 230 | held_cids: HashMap<Cid, Weak<Cid>>, |
| 231 | } |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 232 | |
| 233 | impl GlobalState { |
| 234 | /// Get the next available CID, or an error if we have run out. The last CID used is stored in |
| 235 | /// a system property so that restart of virtualizationservice doesn't reuse CID while the host |
| 236 | /// Android is up. |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 237 | fn allocate_cid(&mut self) -> Result<Arc<Cid>> { |
| 238 | // Garbage collect unused CIDs. |
| 239 | self.held_cids.retain(|_, cid| cid.strong_count() > 0); |
| 240 | |
| 241 | // Start trying to find a CID from the last used CID + 1. This ensures |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 242 | // that we do not eagerly recycle CIDs. It makes debugging easier but |
| 243 | // also means that retrying to allocate a CID, eg. because it is |
| 244 | // erroneously occupied by a process, will not recycle the same CID. |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 245 | let last_cid_prop = |
| 246 | system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() { |
| 247 | Ok(num) => { |
| 248 | if is_valid_guest_cid(num) { |
| 249 | Some(num) |
| 250 | } else { |
| 251 | error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID); |
| 252 | None |
| 253 | } |
| 254 | } |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 255 | Err(_) => { |
| 256 | error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID); |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 257 | None |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 258 | } |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 259 | }); |
| 260 | |
| 261 | let first_cid = if let Some(last_cid) = last_cid_prop { |
| 262 | next_guest_cid(last_cid) |
| 263 | } else { |
| 264 | GUEST_CID_MIN |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 265 | }; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 266 | |
| 267 | let cid = self |
| 268 | .find_available_cid(first_cid..=GUEST_CID_MAX) |
| 269 | .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid)); |
| 270 | |
| 271 | if let Some(cid) = cid { |
| 272 | let cid_arc = Arc::new(cid); |
| 273 | self.held_cids.insert(cid, Arc::downgrade(&cid_arc)); |
| 274 | system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?; |
| 275 | Ok(cid_arc) |
| 276 | } else { |
| 277 | Err(anyhow!("Could not find an available CID.")) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn find_available_cid<I>(&self, mut range: I) -> Option<Cid> |
| 282 | where |
| 283 | I: Iterator<Item = Cid>, |
| 284 | { |
| 285 | range.find(|cid| !self.held_cids.contains_key(cid)) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 286 | } |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 287 | |
| 288 | fn allocate_vm_context(&mut self, client_uid: Uid) -> Result<Strong<dyn IGlobalVmContext>> { |
| 289 | let cid = self.allocate_cid()?; |
| 290 | let temp_dir = create_vm_directory(client_uid, *cid)?; |
| 291 | let binder = GlobalVmContext { cid, temp_dir, ..Default::default() }; |
| 292 | Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default())) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | fn create_vm_directory(client_uid: Uid, cid: Cid) -> Result<PathBuf> { |
| 297 | let path: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into(); |
| 298 | if path.as_path().exists() { |
| 299 | remove_temporary_dir(&path).unwrap_or_else(|e| { |
| 300 | warn!("Could not delete temporary directory {:?}: {}", path, e); |
| 301 | }); |
| 302 | } |
| 303 | // Create a directory that is owned by client's UID but system's GID, and permissions 0700. |
| 304 | // If the chown() fails, this will leave behind an empty directory that will get removed |
| 305 | // at the next attempt, or if virtualizationservice is restarted. |
| 306 | create_dir(&path) |
| 307 | .with_context(|| format!("Could not create temporary directory {:?}", path))?; |
| 308 | chown(&path, Some(client_uid), None) |
| 309 | .with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?; |
| 310 | Ok(path) |
| 311 | } |
| 312 | |
| 313 | /// Removes a directory owned by a different user by first changing its owner back |
| 314 | /// to VirtualizationService. |
| 315 | pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> { |
| 316 | if !path.as_path().is_dir() { |
| 317 | bail!("Path {:?} is not a directory", path); |
| 318 | } |
| 319 | chown(path, Some(Uid::current()), None)?; |
| 320 | set_permissions(path, Permissions::from_mode(0o700))?; |
| 321 | remove_temporary_files(path)?; |
| 322 | remove_dir(path)?; |
| 323 | Ok(()) |
| 324 | } |
| 325 | |
| 326 | pub fn remove_temporary_files(path: &PathBuf) -> Result<()> { |
| 327 | for dir_entry in read_dir(path)? { |
| 328 | remove_file(dir_entry?.path())?; |
| 329 | } |
| 330 | Ok(()) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 331 | } |
| 332 | |
| 333 | /// Implementation of the AIDL `IGlobalVmContext` interface. |
| 334 | #[derive(Debug, Default)] |
| 335 | struct GlobalVmContext { |
| 336 | /// The unique CID assigned to the VM for vsock communication. |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 337 | cid: Arc<Cid>, |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 338 | /// The temporary folder created for the VM and owned by the creator's UID. |
| 339 | temp_dir: PathBuf, |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 340 | /// Keeps our service process running as long as this VM context exists. |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 341 | #[allow(dead_code)] |
| 342 | lazy_service_guard: LazyServiceGuard, |
| 343 | } |
| 344 | |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 345 | impl Interface for GlobalVmContext {} |
| 346 | |
| 347 | impl IGlobalVmContext for GlobalVmContext { |
| 348 | fn getCid(&self) -> binder::Result<i32> { |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 349 | Ok(*self.cid as i32) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 350 | } |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 351 | |
| 352 | fn getTemporaryDirectory(&self) -> binder::Result<String> { |
| 353 | Ok(self.temp_dir.to_string_lossy().to_string()) |
| 354 | } |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 355 | } |
| 356 | |
| 357 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 358 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 359 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 360 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 361 | } |
| 362 | |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 363 | impl Interface for VirtualizationService { |
| 364 | fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> { |
| 365 | check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?; |
| 366 | let state = &mut *self.state.lock().unwrap(); |
| 367 | let vms = state.vms(); |
| 368 | writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 369 | for vm in vms { |
| 370 | writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 371 | writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap()) |
| 372 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 373 | writeln!(file, "\tPayload state {:?}", vm.payload_state()) |
| 374 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 375 | writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 376 | writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy()) |
| 377 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 378 | writeln!(file, "\trequester_uid: {}", vm.requester_uid) |
| 379 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 380 | writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid) |
| 381 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 382 | } |
| 383 | Ok(()) |
| 384 | } |
| 385 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 386 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 387 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 388 | /// Creates (but does not start) a new VM with the given configuration, assigning it the next |
| 389 | /// available CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 390 | /// |
| 391 | /// 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] | 392 | fn createVm( |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 393 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 394 | config: &VirtualMachineConfig, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 395 | console_fd: Option<&ParcelFileDescriptor>, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 396 | log_fd: Option<&ParcelFileDescriptor>, |
| 397 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 398 | let mut is_protected = false; |
| 399 | let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected); |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 400 | write_vm_creation_stats(config, is_protected, &ret); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 401 | ret |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 402 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 403 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 404 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 405 | fn initializeWritablePartition( |
| 406 | &self, |
| 407 | image_fd: &ParcelFileDescriptor, |
| 408 | size: i64, |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 409 | partition_type: PartitionType, |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 410 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 411 | check_manage_access()?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 412 | let size = size.try_into().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 413 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 414 | ExceptionCode::ILLEGAL_ARGUMENT, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 415 | Some(format!("Invalid size {}: {:?}", size, e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 416 | ) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 417 | })?; |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 418 | let image = clone_file(image_fd)?; |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 419 | // initialize the file. Any data in the file will be erased. |
| 420 | image.set_len(0).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 421 | Status::new_service_specific_error_str( |
| 422 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 423 | Some(format!("Failed to reset a file: {:?}", e)), |
Jooyung Han | 1edd5b9 | 2021-10-28 10:58:05 +0900 | [diff] [blame] | 424 | ) |
| 425 | })?; |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 426 | let mut part = QcowFile::new(image, size).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 427 | Status::new_service_specific_error_str( |
| 428 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 429 | Some(format!("Failed to create QCOW2 image: {:?}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 430 | ) |
Andrew Walbran | dfc953d | 2021-06-10 13:59:56 +0000 | [diff] [blame] | 431 | })?; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 432 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 433 | match partition_type { |
| 434 | PartitionType::RAW => Ok(()), |
| 435 | PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part), |
Shikha Panwar | 9fd198f | 2022-11-18 17:43:43 +0000 | [diff] [blame] | 436 | PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part), |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 437 | _ => Err(Error::new( |
| 438 | ErrorKind::Unsupported, |
| 439 | format!("Unsupported partition type {:?}", partition_type), |
| 440 | )), |
| 441 | } |
| 442 | .map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 443 | Status::new_service_specific_error_str( |
| 444 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 445 | Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)), |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 446 | ) |
| 447 | })?; |
| 448 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 449 | Ok(()) |
| 450 | } |
| 451 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 452 | /// Creates or update the idsig file by digesting the input APK file. |
| 453 | fn createOrUpdateIdsigFile( |
| 454 | &self, |
| 455 | input_fd: &ParcelFileDescriptor, |
| 456 | idsig_fd: &ParcelFileDescriptor, |
| 457 | ) -> binder::Result<()> { |
| 458 | // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in |
| 459 | // idsig_fd is different from APK digest in input_fd |
| 460 | |
Jiyong Park | c3ca24f | 2022-06-28 10:45:15 +0900 | [diff] [blame] | 461 | check_manage_access()?; |
| 462 | |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 463 | create_or_update_idsig_file(input_fd, idsig_fd) |
| 464 | .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?; |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 465 | Ok(()) |
| 466 | } |
| 467 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 468 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 469 | /// and as such is only permitted from the shell user. |
| 470 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 471 | check_debug_access()?; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 472 | |
| 473 | let state = &mut *self.state.lock().unwrap(); |
| 474 | let vms = state.vms(); |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 475 | let cids = vms |
| 476 | .into_iter() |
| 477 | .map(|vm| VirtualMachineDebugInfo { |
| 478 | cid: vm.cid as i32, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 479 | temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(), |
Andrew Walbran | 1ef19ae | 2021-04-07 11:31:57 +0000 | [diff] [blame] | 480 | requesterUid: vm.requester_uid as i32, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 481 | requesterPid: vm.requester_debug_pid, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 482 | state: get_state(&vm), |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 483 | }) |
| 484 | .collect(); |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 485 | Ok(cids) |
| 486 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 487 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 488 | /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for |
| 489 | /// debug purposes, and as such is only permitted from the shell user. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 490 | fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 491 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 492 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 493 | let state = &mut *self.state.lock().unwrap(); |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 494 | state.debug_hold_vm(vmref.clone()); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 495 | Ok(()) |
| 496 | } |
| 497 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 498 | /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if |
| 499 | /// the VM was found and None otherwise. This method is only intended for debug purposes, and as |
| 500 | /// such is only permitted from the shell user. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 501 | fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 502 | check_debug_access()?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 503 | |
| 504 | let state = &mut *self.state.lock().unwrap(); |
| 505 | Ok(state.debug_drop_vm(cid)) |
| 506 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 507 | } |
| 508 | |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 509 | fn handle_stream_connection_tombstoned() -> Result<()> { |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 510 | // Should not listen for tombstones on a guest VM's port. |
| 511 | assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid)); |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 512 | let listener = |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 513 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?; |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 514 | for incoming_stream in listener.incoming() { |
| 515 | let mut incoming_stream = match incoming_stream { |
| 516 | Err(e) => { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 517 | warn!("invalid incoming connection: {:?}", e); |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 518 | continue; |
| 519 | } |
| 520 | Ok(s) => s, |
| 521 | }; |
| 522 | std::thread::spawn(move || { |
| 523 | if let Err(e) = handle_tombstone(&mut incoming_stream) { |
| 524 | error!("Failed to write tombstone- {:?}", e); |
| 525 | } |
| 526 | }); |
| 527 | } |
| 528 | Ok(()) |
| 529 | } |
| 530 | |
| 531 | fn handle_tombstone(stream: &mut VsockStream) -> Result<()> { |
Andrew Walbran | add38cb | 2022-10-06 17:01:03 +0000 | [diff] [blame] | 532 | if let Ok(addr) = stream.peer_addr() { |
Shikha Panwar | 7afc139 | 2022-03-24 08:54:43 +0000 | [diff] [blame] | 533 | info!("Vsock Stream connected to cid={} for tombstones", addr.cid()); |
| 534 | } |
| 535 | let tb_connection = |
| 536 | TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone) |
| 537 | .context("Failed to connect to tombstoned")?; |
| 538 | let mut text_output = tb_connection |
| 539 | .text_output |
| 540 | .as_ref() |
| 541 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 542 | let mut num_bytes_read = 0; |
| 543 | loop { |
| 544 | let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN]; |
| 545 | let n = stream |
| 546 | .read(&mut chunk_recv) |
| 547 | .context("Failed to read tombstone data from Vsock stream")?; |
| 548 | if n == 0 { |
| 549 | break; |
| 550 | } |
| 551 | num_bytes_read += n; |
| 552 | text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?; |
| 553 | } |
| 554 | info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read); |
| 555 | tb_connection.notify_completion()?; |
| 556 | Ok(()) |
| 557 | } |
| 558 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 559 | impl VirtualizationService { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 560 | // TODO(b/245727626): Remove after the source files for virtualizationservice |
| 561 | // and virtmgr binaries are split from each other. |
| 562 | #[allow(dead_code)] |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 563 | pub fn init() -> VirtualizationService { |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 564 | VirtualizationService::default() |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 565 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 566 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 567 | fn create_vm_context(&self) -> Result<(VmContext, Cid, PathBuf)> { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 568 | const NUM_ATTEMPTS: usize = 5; |
| 569 | |
| 570 | for _ in 0..NUM_ATTEMPTS { |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 571 | let global_context = GLOBAL_SERVICE.allocateGlobalVmContext()?; |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 572 | let cid = global_context.getCid()? as Cid; |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 573 | let temp_dir: PathBuf = global_context.getTemporaryDirectory()?.into(); |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 574 | let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder(); |
| 575 | |
| 576 | // 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] | 577 | let port = cid; |
David Brazdil | 3238da4 | 2022-11-18 10:04:51 +0000 | [diff] [blame] | 578 | match RpcServer::new_vsock(service, cid, port) { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 579 | Ok(vm_server) => { |
| 580 | vm_server.start(); |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 581 | return Ok((VmContext::new(global_context, vm_server), cid, temp_dir)); |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 582 | } |
| 583 | Err(err) => { |
| 584 | warn!("Could not start RpcServer on port {}: {}", port, err); |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | bail!("Too many attempts to create VM context failed."); |
| 589 | } |
| 590 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 591 | fn create_vm_internal( |
| 592 | &self, |
| 593 | config: &VirtualMachineConfig, |
| 594 | console_fd: Option<&ParcelFileDescriptor>, |
| 595 | log_fd: Option<&ParcelFileDescriptor>, |
| 596 | is_protected: &mut bool, |
| 597 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
| 598 | check_manage_access()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 599 | |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 600 | let is_custom = match config { |
| 601 | VirtualMachineConfig::RawConfig(_) => true, |
| 602 | VirtualMachineConfig::AppConfig(config) => { |
| 603 | // Some features are reserved for platform apps only, even when using |
| 604 | // VirtualMachineAppConfig: |
| 605 | // - controlling CPUs; |
| 606 | // - specifying a config file in the APK. |
| 607 | !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_)) |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 608 | } |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 609 | }; |
| 610 | if is_custom { |
| 611 | check_use_custom_virtual_machine()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 612 | } |
| 613 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 614 | let (vm_context, cid, temporary_directory) = self.create_vm_context().map_err(|e| { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 615 | error!("Failed to create VmContext: {:?}", e); |
| 616 | Status::new_service_specific_error_str( |
| 617 | -1, |
| 618 | Some(format!("Failed to create VmContext: {:?}", e)), |
| 619 | ) |
| 620 | })?; |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 621 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 622 | let state = &mut *self.state.lock().unwrap(); |
| 623 | let console_fd = console_fd.map(clone_file).transpose()?; |
| 624 | let log_fd = log_fd.map(clone_file).transpose()?; |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 625 | let requester_uid = get_calling_uid(); |
| 626 | let requester_debug_pid = get_calling_pid(); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 627 | |
| 628 | // Counter to generate unique IDs for temporary image files. |
| 629 | let mut next_temporary_image_id = 0; |
| 630 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 631 | // child process, and not closed before it is started. |
| 632 | let mut indirect_files = vec![]; |
| 633 | |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 634 | let (is_app_config, config) = match config { |
| 635 | VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)), |
| 636 | VirtualMachineConfig::AppConfig(config) => { |
| 637 | let config = load_app_config(config, &temporary_directory).map_err(|e| { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 638 | *is_protected = config.protectedVm; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 639 | let message = format!("Failed to load app config: {:?}", e); |
| 640 | error!("{}", message); |
| 641 | Status::new_service_specific_error_str(-1, Some(message)) |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 642 | })?; |
| 643 | (true, BorrowedOrOwned::Owned(config)) |
| 644 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 645 | }; |
| 646 | let config = config.as_ref(); |
| 647 | *is_protected = config.protectedVm; |
| 648 | |
| 649 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 650 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 651 | // being loaded in a pVM. This applies to everything in the raw config, and everything but |
| 652 | // the non-executable, generated partitions in the app config. |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 653 | config |
| 654 | .disks |
| 655 | .iter() |
| 656 | .flat_map(|disk| disk.partitions.iter()) |
| 657 | .filter(|partition| { |
| 658 | if is_app_config { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 659 | !is_safe_app_partition(&partition.label) |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 660 | } else { |
| 661 | true // all partitions are checked |
| 662 | } |
| 663 | }) |
| 664 | .try_for_each(check_label_for_partition) |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 665 | .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 666 | |
| 667 | let zero_filler_path = temporary_directory.join("zero.img"); |
| 668 | write_zero_filler(&zero_filler_path).map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 669 | error!("Failed to make composite image: {:?}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 670 | Status::new_service_specific_error_str( |
| 671 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 672 | Some(format!("Failed to make composite image: {:?}", e)), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 673 | ) |
| 674 | })?; |
| 675 | |
| 676 | // Assemble disk images if needed. |
| 677 | let disks = config |
| 678 | .disks |
| 679 | .iter() |
| 680 | .map(|disk| { |
| 681 | assemble_disk_image( |
| 682 | disk, |
| 683 | &zero_filler_path, |
| 684 | &temporary_directory, |
| 685 | &mut next_temporary_image_id, |
| 686 | &mut indirect_files, |
| 687 | ) |
| 688 | }) |
| 689 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 690 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 691 | // Creating this ramdump file unconditionally is not harmful as ramdump will be created |
| 692 | // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 693 | // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read` |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 694 | // will be sent back to the client (i.e. the VM owner) for readout. |
| 695 | let ramdump_path = temporary_directory.join("ramdump"); |
| 696 | let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 697 | error!("Failed to prepare ramdump file: {:?}", e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 698 | Status::new_service_specific_error_str( |
| 699 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 700 | Some(format!("Failed to prepare ramdump file: {:?}", e)), |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 701 | ) |
| 702 | })?; |
| 703 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 704 | // Actually start the VM. |
| 705 | let crosvm_config = CrosvmConfig { |
| 706 | cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 707 | name: config.name.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 708 | bootloader: maybe_clone_file(&config.bootloader)?, |
| 709 | kernel: maybe_clone_file(&config.kernel)?, |
| 710 | initrd: maybe_clone_file(&config.initrd)?, |
| 711 | disks, |
| 712 | params: config.params.to_owned(), |
| 713 | protected: *is_protected, |
| 714 | memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new), |
| 715 | cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new), |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 716 | task_profiles: config.taskProfiles.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 717 | console_fd, |
| 718 | log_fd, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 719 | ramdump: Some(ramdump), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 720 | indirect_files, |
| 721 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 722 | detect_hangup: is_app_config, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 723 | }; |
| 724 | let instance = Arc::new( |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 725 | VmInstance::new( |
| 726 | crosvm_config, |
| 727 | temporary_directory, |
| 728 | requester_uid, |
| 729 | requester_debug_pid, |
| 730 | vm_context, |
| 731 | ) |
| 732 | .map_err(|e| { |
| 733 | error!("Failed to create VM with config {:?}: {:?}", config, e); |
| 734 | Status::new_service_specific_error_str( |
| 735 | -1, |
| 736 | Some(format!("Failed to create VM: {:?}", e)), |
| 737 | ) |
| 738 | })?, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 739 | ); |
| 740 | state.add_vm(Arc::downgrade(&instance)); |
| 741 | Ok(VirtualMachine::create(instance)) |
| 742 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 743 | } |
| 744 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 745 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 746 | let file = OpenOptions::new() |
| 747 | .create_new(true) |
| 748 | .read(true) |
| 749 | .write(true) |
| 750 | .open(zero_filler_path) |
| 751 | .with_context(|| "Failed to create zero.img")?; |
| 752 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 753 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 754 | } |
| 755 | |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 756 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 757 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 758 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 759 | part.flush() |
| 760 | } |
| 761 | |
Shikha Panwar | 9fd198f | 2022-11-18 17:43:43 +0000 | [diff] [blame] | 762 | fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> { |
| 763 | part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?; |
| 764 | part.flush() |
| 765 | } |
| 766 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 767 | fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> { |
Chris Wailes | 9b866f0 | 2022-11-16 15:17:16 -0800 | [diff] [blame] | 768 | File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path)) |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 769 | } |
| 770 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 771 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 772 | /// |
| 773 | /// This may involve assembling a composite disk from a set of partition images. |
| 774 | fn assemble_disk_image( |
| 775 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 776 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 777 | temporary_directory: &Path, |
| 778 | next_temporary_image_id: &mut u64, |
| 779 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 780 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 781 | let image = if !disk.partitions.is_empty() { |
| 782 | if disk.image.is_some() { |
| 783 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 784 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 785 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 786 | Some("DiskImage contains both image and partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 787 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 788 | } |
| 789 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 790 | let composite_image_filenames = |
| 791 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 792 | let (image, partition_files) = make_composite_image( |
| 793 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 794 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 795 | &composite_image_filenames.composite, |
| 796 | &composite_image_filenames.header, |
| 797 | &composite_image_filenames.footer, |
| 798 | ) |
| 799 | .map_err(|e| { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 800 | error!("Failed to make composite image with config {:?}: {:?}", disk, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 801 | Status::new_service_specific_error_str( |
| 802 | -1, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 803 | Some(format!("Failed to make composite image: {:?}", e)), |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 804 | ) |
| 805 | })?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 806 | |
| 807 | // Pass the file descriptors for the various partition files to crosvm when it |
| 808 | // is run. |
| 809 | indirect_files.extend(partition_files); |
| 810 | |
| 811 | image |
| 812 | } else if let Some(image) = &disk.image { |
| 813 | clone_file(image)? |
| 814 | } else { |
| 815 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 816 | return Err(Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 817 | ExceptionCode::ILLEGAL_ARGUMENT, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 818 | Some("DiskImage didn't contain image or partitions."), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 819 | )); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 820 | }; |
| 821 | |
| 822 | Ok(DiskFile { image, writable: disk.writable }) |
| 823 | } |
| 824 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 825 | fn load_app_config( |
| 826 | config: &VirtualMachineAppConfig, |
| 827 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 828 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 829 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 830 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 831 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 832 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 833 | let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() { |
| 834 | Some(clone_file(file)?) |
| 835 | } else { |
| 836 | None |
| 837 | }; |
| 838 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 839 | let vm_payload_config = match &config.payload { |
| 840 | Payload::ConfigPath(config_path) => { |
| 841 | load_vm_payload_config_from_file(&apk_file, config_path.as_str()) |
| 842 | .with_context(|| format!("Couldn't read config from {}", config_path))? |
| 843 | } |
| 844 | Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config), |
| 845 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 846 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 847 | // For now, the only supported OS is Microdroid |
| 848 | let os_name = vm_payload_config.os.name.as_str(); |
| 849 | if os_name != MICRODROID_OS_NAME { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 850 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 851 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 852 | |
| 853 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 854 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 855 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 856 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 857 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 858 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 859 | if config.memoryMib > 0 { |
| 860 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 861 | } |
| 862 | |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 863 | vm_config.name = config.name.clone(); |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 864 | vm_config.protectedVm = config.protectedVm; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 865 | vm_config.numCpus = config.numCpus; |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 866 | vm_config.taskProfiles = config.taskProfiles.clone(); |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 867 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 868 | // Microdroid takes additional init ramdisk & (optionally) storage image |
| 869 | add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?; |
| 870 | |
| 871 | // Include Microdroid payload disk (contains apks, idsigs) in vm config |
| 872 | add_microdroid_payload_images( |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 873 | config, |
| 874 | temporary_directory, |
| 875 | apk_file, |
| 876 | idsig_file, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 877 | &vm_payload_config, |
| 878 | &mut vm_config, |
| 879 | )?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 880 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 881 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 882 | } |
| 883 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 884 | fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> { |
| 885 | let mut apk_zip = ZipArchive::new(apk_file)?; |
| 886 | let config_file = apk_zip.by_name(config_path)?; |
| 887 | Ok(serde_json::from_reader(config_file)?) |
| 888 | } |
| 889 | |
| 890 | fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig { |
| 891 | // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit |
| 892 | // parameters we've been given. Microdroid will do something equivalent inside the VM using the |
| 893 | // payload config that we send it via the metadata file. |
Alan Stokes | 52d3c72 | 2022-10-04 17:27:13 +0100 | [diff] [blame] | 894 | let task = |
| 895 | Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() }; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 896 | VmPayloadConfig { |
| 897 | os: OsConfig { name: MICRODROID_OS_NAME.to_owned() }, |
| 898 | task: Some(task), |
| 899 | apexes: vec![], |
| 900 | extra_apks: vec![], |
| 901 | prefer_staged: false, |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 902 | export_tombstones: false, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 903 | enable_authfs: false, |
| 904 | } |
| 905 | } |
| 906 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 907 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 908 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 909 | temporary_directory: &Path, |
| 910 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 911 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 912 | let id = *next_temporary_image_id; |
| 913 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 914 | CompositeImageFilenames { |
| 915 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 916 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 917 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | /// Filenames for a composite disk image, including header and footer partitions. |
| 922 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 923 | struct CompositeImageFilenames { |
| 924 | /// The composite disk image itself. |
| 925 | composite: PathBuf, |
| 926 | /// The header partition image. |
| 927 | header: PathBuf, |
| 928 | /// The footer partition image. |
| 929 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 930 | } |
| 931 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 932 | /// Checks whether the caller has a specific permission |
| 933 | fn check_permission(perm: &str) -> binder::Result<()> { |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 934 | let calling_pid = get_calling_pid(); |
| 935 | let calling_uid = get_calling_uid(); |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 936 | // Root can do anything |
| 937 | if calling_uid == 0 { |
| 938 | return Ok(()); |
| 939 | } |
| 940 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 941 | binder::get_interface("permission")?; |
| 942 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 943 | Ok(()) |
| 944 | } else { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 945 | Err(Status::new_exception_str( |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 946 | ExceptionCode::SECURITY, |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 947 | Some(format!("does not have the {} permission", perm)), |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 948 | )) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 949 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 950 | } |
| 951 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 952 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 953 | fn check_debug_access() -> binder::Result<()> { |
| 954 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 955 | } |
| 956 | |
| 957 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 958 | fn check_manage_access() -> binder::Result<()> { |
| 959 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 960 | } |
| 961 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 962 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 963 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 964 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 965 | } |
| 966 | |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 967 | /// Check if a partition has selinux labels that are not allowed |
| 968 | fn check_label_for_partition(partition: &Partition) -> Result<()> { |
| 969 | let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?; |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 970 | check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label)) |
| 971 | } |
| 972 | |
| 973 | // Return whether a partition is exempt from selinux label checks, because we know that it does |
| 974 | // not contain code and is likely to be generated in an app-writable directory. |
| 975 | fn is_safe_app_partition(label: &str) -> bool { |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 976 | // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 977 | label == "vm-instance" |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 978 | || label == "encryptedstore" |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 979 | || label == "microdroid-apk-idsig" |
| 980 | || label == "payload-metadata" |
| 981 | || label.starts_with("extra-idsig-") |
| 982 | } |
| 983 | |
| 984 | fn check_label_is_allowed(ctx: &SeContext) -> Result<()> { |
| 985 | // We only want to allow code in a VM payload to be sourced from places that apps, and the |
| 986 | // system, do not have write access to. |
| 987 | // (Note that sepolicy must also grant read access for these types to both virtualization |
| 988 | // service and crosvm.) |
| 989 | // App private data files are deliberately excluded, to avoid arbitrary payloads being run on |
| 990 | // user devices (W^X). |
| 991 | match ctx.selinux_type()? { |
| 992 | | "system_file" // immutable dm-verity protected partition |
| 993 | | "apk_data_file" // APKs of an installed app |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 994 | | "staging_data_file" // updated/staged APEX images |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 995 | | "shell_data_file" // test files created via adb shell |
| 996 | => Ok(()), |
| 997 | _ => bail!("Label {} is not allowed", ctx), |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 998 | } |
| 999 | } |
| 1000 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1001 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 1002 | #[derive(Debug)] |
| 1003 | struct VirtualMachine { |
| 1004 | instance: Arc<VmInstance>, |
| 1005 | } |
| 1006 | |
| 1007 | impl VirtualMachine { |
| 1008 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 1009 | BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | impl Interface for VirtualMachine {} |
| 1014 | |
| 1015 | impl IVirtualMachine for VirtualMachine { |
| 1016 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1017 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1018 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1019 | Ok(self.instance.cid as i32) |
| 1020 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1021 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1022 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1023 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1024 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1025 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1026 | } |
| 1027 | |
| 1028 | fn registerCallback( |
| 1029 | &self, |
| 1030 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 1031 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 1032 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 1033 | // others. |
| 1034 | // |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1035 | // TODO: Should this give an error if the VM is already dead? |
| 1036 | self.instance.callbacks.add(callback.clone()); |
| 1037 | Ok(()) |
| 1038 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1039 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1040 | fn start(&self) -> binder::Result<()> { |
| 1041 | self.instance.start().map_err(|e| { |
| 1042 | error!("Error starting VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1043 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1044 | }) |
| 1045 | } |
| 1046 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1047 | fn stop(&self) -> binder::Result<()> { |
| 1048 | self.instance.kill().map_err(|e| { |
| 1049 | error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1050 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1051 | }) |
| 1052 | } |
| 1053 | |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 1054 | fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> { |
| 1055 | self.instance.trim_memory(level).map_err(|e| { |
| 1056 | error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e); |
| 1057 | Status::new_service_specific_error_str(-1, Some(e.to_string())) |
| 1058 | }) |
| 1059 | } |
| 1060 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1061 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1062 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1063 | return Err(Status::new_service_specific_error_str(-1, Some("VM is not running"))); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1064 | } |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 1065 | let port = port as u32; |
| 1066 | if port < 1024 { |
| 1067 | return Err(Status::new_service_specific_error_str( |
| 1068 | -1, |
| 1069 | Some(format!("Can't connect to privileged port {port}")), |
| 1070 | )); |
| 1071 | } |
| 1072 | let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| { |
| 1073 | Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e))) |
| 1074 | })?; |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1075 | Ok(vsock_stream_to_pfd(stream)) |
| 1076 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1077 | } |
| 1078 | |
| 1079 | impl Drop for VirtualMachine { |
| 1080 | fn drop(&mut self) { |
| 1081 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 1082 | if let Err(e) = self.instance.kill() { |
| 1083 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 1084 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1085 | } |
| 1086 | } |
| 1087 | |
| 1088 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 1089 | /// dies. |
| 1090 | #[derive(Debug, Default)] |
| 1091 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 1092 | |
| 1093 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1094 | /// Call all registered callbacks to notify that the payload has started. |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1095 | pub fn notify_payload_started(&self, cid: Cid) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1096 | let callbacks = &*self.0.lock().unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1097 | for callback in callbacks { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1098 | if let Err(e) = callback.onPayloadStarted(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1099 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1100 | } |
| 1101 | } |
| 1102 | } |
| 1103 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1104 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 1105 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 1106 | let callbacks = &*self.0.lock().unwrap(); |
| 1107 | for callback in callbacks { |
| 1108 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1109 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1110 | } |
| 1111 | } |
| 1112 | } |
| 1113 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1114 | /// Call all registered callbacks to notify that the payload has finished. |
| 1115 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 1116 | let callbacks = &*self.0.lock().unwrap(); |
| 1117 | for callback in callbacks { |
| 1118 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1119 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1120 | } |
| 1121 | } |
| 1122 | } |
| 1123 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1124 | /// Call all registered callbacks to say that the VM encountered an error. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1125 | pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1126 | let callbacks = &*self.0.lock().unwrap(); |
| 1127 | for callback in callbacks { |
| 1128 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1129 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1130 | } |
| 1131 | } |
| 1132 | } |
| 1133 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1134 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1135 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1136 | let callbacks = &*self.0.lock().unwrap(); |
| 1137 | for callback in callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 1138 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 1139 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1140 | } |
| 1141 | } |
| 1142 | } |
| 1143 | |
| 1144 | /// Add a new callback to the set. |
| 1145 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 1146 | self.0.lock().unwrap().push(callback); |
| 1147 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1148 | } |
| 1149 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 1150 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 1151 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 1152 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1153 | struct State { |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1154 | /// The VMs which have been started. When VMs are started a weak reference is added to this list |
| 1155 | /// while a strong reference is returned to the caller over Binder. Once all copies of the |
| 1156 | /// Binder client are dropped the weak reference here will become invalid, and will be removed |
| 1157 | /// from the list opportunistically the next time `add_vm` is called. |
| 1158 | vms: Vec<Weak<VmInstance>>, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1159 | |
| 1160 | /// Vector of strong VM references held on behalf of users that cannot hold them themselves. |
| 1161 | /// This is only used for debugging purposes. |
| 1162 | debug_held_vms: Vec<Strong<dyn IVirtualMachine>>, |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1163 | } |
| 1164 | |
| 1165 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 1166 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1167 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 1168 | // Attempt to upgrade the weak pointers to strong pointers. |
| 1169 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 1170 | } |
| 1171 | |
| 1172 | /// Add a new VM to the list. |
| 1173 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 1174 | // Garbage collect any entries from the stored list which no longer exist. |
| 1175 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 1176 | |
| 1177 | // Actually add the new VM. |
| 1178 | self.vms.push(vm); |
| 1179 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1180 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1181 | /// Get a VM that corresponds to the given cid |
| 1182 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 1183 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 1184 | } |
| 1185 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1186 | /// Store a strong VM reference. |
| 1187 | fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) { |
| 1188 | self.debug_held_vms.push(vm); |
| 1189 | } |
| 1190 | |
| 1191 | /// Retrieve and remove a strong VM reference. |
| 1192 | fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> { |
| 1193 | let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?; |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 1194 | let vm = self.debug_held_vms.swap_remove(pos); |
Alan Stokes | 7e54e29 | 2021-09-09 11:37:56 +0100 | [diff] [blame] | 1195 | Some(vm) |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1196 | } |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 1197 | } |
| 1198 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1199 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 1200 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1201 | match &*instance.vm_state.lock().unwrap() { |
| 1202 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 1203 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1204 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 1205 | PayloadState::Started => VirtualMachineState::STARTED, |
| 1206 | PayloadState::Ready => VirtualMachineState::READY, |
| 1207 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 1208 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1209 | }, |
| 1210 | VmState::Dead => VirtualMachineState::DEAD, |
| 1211 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1212 | } |
| 1213 | } |
| 1214 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 1215 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 1216 | pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1217 | file.as_ref().try_clone().map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1218 | Status::new_exception_str( |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1219 | ExceptionCode::BAD_PARCELABLE, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1220 | Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)), |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 1221 | ) |
| 1222 | }) |
| 1223 | } |
| 1224 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1225 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
| 1226 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> { |
| 1227 | file.as_ref().map(clone_file).transpose() |
| 1228 | } |
| 1229 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1230 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
| 1231 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1232 | // SAFETY: ownership is transferred from stream to f |
| 1233 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1234 | ParcelFileDescriptor::new(f) |
| 1235 | } |
| 1236 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1237 | /// Parses the platform version requirement string. |
| 1238 | fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> { |
| 1239 | VersionReq::parse(s).map_err(|e| { |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1240 | Status::new_exception_str( |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1241 | ExceptionCode::BAD_PARCELABLE, |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1242 | Some(format!("Invalid platform version requirement {}: {:?}", s, e)), |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1243 | ) |
| 1244 | }) |
| 1245 | } |
| 1246 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1247 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 1248 | /// it doesn't require that T implements Clone. |
| 1249 | enum BorrowedOrOwned<'a, T> { |
| 1250 | Borrowed(&'a T), |
| 1251 | Owned(T), |
| 1252 | } |
| 1253 | |
| 1254 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 1255 | fn as_ref(&self) -> &T { |
| 1256 | match self { |
| 1257 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 1258 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1259 | } |
| 1260 | } |
| 1261 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1262 | |
| 1263 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 1264 | #[derive(Debug, Default)] |
| 1265 | struct VirtualMachineService { |
| 1266 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1267 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1268 | } |
| 1269 | |
| 1270 | impl Interface for VirtualMachineService {} |
| 1271 | |
| 1272 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1273 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 1274 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1275 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1276 | info!("VM with CID {} started payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1277 | vm.update_payload_state(PayloadState::Started).map_err(|e| { |
| 1278 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1279 | })?; |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1280 | vm.callbacks.notify_payload_started(cid); |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 1281 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 1282 | let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp; |
| 1283 | 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] | 1284 | Ok(()) |
| 1285 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1286 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1287 | Err(Status::new_service_specific_error_str( |
| 1288 | -1, |
| 1289 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1290 | )) |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1291 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1292 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1293 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1294 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 1295 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1296 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1297 | info!("VM with CID {} reported payload is ready", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1298 | vm.update_payload_state(PayloadState::Ready).map_err(|e| { |
| 1299 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1300 | })?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1301 | vm.callbacks.notify_payload_ready(cid); |
| 1302 | Ok(()) |
| 1303 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1304 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1305 | Err(Status::new_service_specific_error_str( |
| 1306 | -1, |
| 1307 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1308 | )) |
| 1309 | } |
| 1310 | } |
| 1311 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1312 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 1313 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1314 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1315 | info!("VM with CID {} finished payload", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1316 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1317 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1318 | })?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1319 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 1320 | Ok(()) |
| 1321 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1322 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1323 | Err(Status::new_service_specific_error_str( |
| 1324 | -1, |
| 1325 | Some(format!("cannot find a VM with CID {}", cid)), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1326 | )) |
| 1327 | } |
| 1328 | } |
| 1329 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1330 | fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1331 | let cid = self.cid; |
| 1332 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1333 | info!("VM with CID {} encountered an error", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1334 | vm.update_payload_state(PayloadState::Finished).map_err(|e| { |
| 1335 | Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string())) |
| 1336 | })?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1337 | vm.callbacks.notify_error(cid, error_code, message); |
| 1338 | Ok(()) |
| 1339 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 1340 | error!("notifyError is called from an unknown CID {}", cid); |
Andrew Walbran | dcf9d58 | 2022-08-03 11:25:24 +0000 | [diff] [blame] | 1341 | Err(Status::new_service_specific_error_str( |
| 1342 | -1, |
| 1343 | Some(format!("cannot find a VM with CID {}", cid)), |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1344 | )) |
| 1345 | } |
| 1346 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1347 | } |
| 1348 | |
| 1349 | impl VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1350 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1351 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1352 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1353 | BinderFeatures::default(), |
| 1354 | ) |
| 1355 | } |
| 1356 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1357 | |
| 1358 | #[cfg(test)] |
| 1359 | mod tests { |
| 1360 | use super::*; |
| 1361 | |
| 1362 | #[test] |
| 1363 | fn test_is_allowed_label_for_partition() -> Result<()> { |
| 1364 | let expected_results = vec![ |
| 1365 | ("u:object_r:system_file:s0", true), |
| 1366 | ("u:object_r:apk_data_file:s0", true), |
| 1367 | ("u:object_r:app_data_file:s0", false), |
| 1368 | ("u:object_r:app_data_file:s0:c512,c768", false), |
| 1369 | ("u:object_r:privapp_data_file:s0:c512,c768", false), |
| 1370 | ("invalid", false), |
| 1371 | ("user:role:apk_data_file:severity:categories", true), |
| 1372 | ("user:role:apk_data_file:severity:categories:extraneous", false), |
| 1373 | ]; |
| 1374 | |
| 1375 | for (label, expected_valid) in expected_results { |
| 1376 | let context = SeContext::new(label)?; |
| 1377 | let result = check_label_is_allowed(&context); |
| 1378 | if expected_valid { |
| 1379 | assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result); |
| 1380 | } else if result.is_ok() { |
| 1381 | bail!("Expected label {} to be disallowed", label); |
| 1382 | } |
| 1383 | } |
| 1384 | Ok(()) |
| 1385 | } |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 1386 | |
| 1387 | #[test] |
| 1388 | fn test_create_or_update_idsig_file_empty_apk() -> Result<()> { |
| 1389 | let apk = tempfile::tempfile().unwrap(); |
| 1390 | let idsig = tempfile::tempfile().unwrap(); |
| 1391 | |
| 1392 | let ret = create_or_update_idsig_file( |
| 1393 | &ParcelFileDescriptor::new(apk), |
| 1394 | &ParcelFileDescriptor::new(idsig), |
| 1395 | ); |
| 1396 | assert!(ret.is_err(), "should fail"); |
| 1397 | Ok(()) |
| 1398 | } |
| 1399 | |
| 1400 | #[test] |
| 1401 | fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> { |
| 1402 | let tmp_dir = tempfile::TempDir::new().unwrap(); |
| 1403 | let apk = File::open(tmp_dir.path()).unwrap(); |
| 1404 | let idsig = tempfile::tempfile().unwrap(); |
| 1405 | |
| 1406 | let ret = create_or_update_idsig_file( |
| 1407 | &ParcelFileDescriptor::new(apk), |
| 1408 | &ParcelFileDescriptor::new(idsig), |
| 1409 | ); |
| 1410 | assert!(ret.is_err(), "should fail"); |
| 1411 | Ok(()) |
| 1412 | } |
| 1413 | |
| 1414 | /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory |
| 1415 | /// on ext4 filesystem is passed. |
| 1416 | /// On ext4 lseek on a directory fd will return (off_t)-1 (see: |
| 1417 | /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in |
| 1418 | /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory. |
| 1419 | #[test] |
| 1420 | fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> { |
| 1421 | // APEXes are backed by the ext4. |
| 1422 | let apk = File::open("/apex/com.android.virt/").unwrap(); |
| 1423 | let idsig = tempfile::tempfile().unwrap(); |
| 1424 | |
| 1425 | let ret = create_or_update_idsig_file( |
| 1426 | &ParcelFileDescriptor::new(apk), |
| 1427 | &ParcelFileDescriptor::new(idsig), |
| 1428 | ); |
| 1429 | assert!(ret.is_err(), "should fail"); |
| 1430 | Ok(()) |
| 1431 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1432 | } |