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