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