blob: 0859a76c81c44d0769cec122f7d62397cd17732d [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// 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 Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
David Brazdil1f530702022-10-03 12:18:10 +010017use crate::{get_calling_pid, get_calling_uid};
David Brazdil49f96f52022-12-16 21:29:13 +000018use 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 Walbranf5fbb7d2021-05-12 17:15:48 +000021use crate::composite::make_composite_image;
David Brazdil8cf8f482022-11-23 14:21:26 +000022use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000027 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000028 ErrorCode::ErrorCode,
29};
30use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000031 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010032 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000033 IVirtualMachineCallback::IVirtualMachineCallback,
34 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000035 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090036 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090038 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090039 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010041 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090044};
David Brazdil528e0472022-10-10 15:06:02 +010045use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
David Brazdil49f96f52022-12-16 21:29:13 +000046 AtomVmBooted::AtomVmBooted,
47 AtomVmCreationRequested::AtomVmCreationRequested,
48 AtomVmExited::AtomVmExited,
David Brazdil528e0472022-10-10 15:06:02 +010049 IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
David Brazdil4b4c5102022-12-19 22:56:20 +000050 IVirtualizationServiceInternal::IVirtualizationServiceInternal,
David Brazdil528e0472022-10-10 15:06:02 +010051};
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdil73988ea2022-11-11 15:10:32 +000053 BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
55use anyhow::{anyhow, bail, Context, Result};
56use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010057use binder::{
David Brazdil4b4c5102022-12-19 22:56:20 +000058 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard,
59 ParcelFileDescriptor, Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000060};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000061use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000062use lazy_static::lazy_static;
David Brazdila07a1792022-10-25 13:37:57 +010063use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000064use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090065use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
David Brazdil73988ea2022-11-11 15:10:32 +000066use rpcbinder::RpcServer;
Jiyong Parkd50a0242021-09-16 21:00:14 +090067use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090068use semver::VersionReq;
David Brazdil73988ea2022-11-11 15:10:32 +000069use std::collections::HashMap;
Andrew Walbrandff3b942021-06-09 15:20:36 +000070use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000071use std::ffi::CStr;
David Brazdil4b4c5102022-12-19 22:56:20 +000072use std::fs::{create_dir, read_dir, remove_dir, remove_file, set_permissions, File, OpenOptions, Permissions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090073use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000074use std::num::NonZeroU32;
David Brazdil4b4c5102022-12-19 22:56:20 +000075use std::os::unix::fs::PermissionsExt;
Andrew Walbrand3a84182021-09-07 14:48:52 +000076use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000077use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000078use std::sync::{Arc, Mutex, Weak};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090079use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000080use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000081use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090082use zip::ZipArchive;
David Brazdil4b4c5102022-12-19 22:56:20 +000083use nix::unistd::{chown, Uid};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000084
David Brazdil41d1a872022-10-05 14:44:19 +010085/// The unique ID of a VM used (together with a port number) for vsock communication.
86pub type Cid = u32;
87
David Brazdil4b4c5102022-12-19 22:56:20 +000088pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
89
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000091pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000092
David Brazdil41d1a872022-10-05 14:44:19 +010093/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
94/// are reserved for the host or other usage.
David Brazdil73988ea2022-11-11 15:10:32 +000095const GUEST_CID_MIN: Cid = 2048;
96const GUEST_CID_MAX: Cid = 65535;
David Brazdil41d1a872022-10-05 14:44:19 +010097
98const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
Jiyong Park8611a6c2021-07-09 18:17:44 +090099
Jooyung Han95884632021-07-06 22:27:54 +0900100/// The size of zero.img.
101/// Gaps in composite disk images are filled with a shared zero.img.
102const ZERO_FILLER_SIZE: u64 = 4096;
103
Jiyong Park9dd389e2021-08-23 20:42:59 +0900104/// Magic string for the instance image
105const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
106
107/// Version of the instance image format
108const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
109
Shikha Panwar7afc1392022-03-24 08:54:43 +0000110const CHUNK_RECV_MAX_LEN: usize = 1024;
111
Alan Stokes0d1ef782022-09-27 13:46:35 +0100112const MICRODROID_OS_NAME: &str = "microdroid";
113
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000114const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
115
David Brazdil49f96f52022-12-16 21:29:13 +0000116lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000117 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
118 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
119 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000120}
121
David Brazdil73988ea2022-11-11 15:10:32 +0000122fn is_valid_guest_cid(cid: Cid) -> bool {
123 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
124}
125
126fn next_guest_cid(cid: Cid) -> Cid {
127 assert!(is_valid_guest_cid(cid));
128 if cid == GUEST_CID_MAX {
129 GUEST_CID_MIN
130 } else {
131 cid + 1
132 }
133}
134
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000135fn create_or_update_idsig_file(
136 input_fd: &ParcelFileDescriptor,
137 idsig_fd: &ParcelFileDescriptor,
138) -> Result<()> {
139 let mut input = clone_file(input_fd)?;
140 let metadata = input.metadata().context("failed to get input metadata")?;
141 if !metadata.is_file() {
142 bail!("input is not a regular file");
143 }
144 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
145 .context("failed to create idsig")?;
146
147 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000148 output.set_len(0).context("failed to set_len on the idsig output")?;
149 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000150 Ok(())
151}
152
David Brazdil528e0472022-10-10 15:06:02 +0100153/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
154/// singleton servers, like tombstone receiver.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900155#[derive(Debug, Default)]
David Brazdil528e0472022-10-10 15:06:02 +0100156pub struct VirtualizationServiceInternal {
157 state: Arc<Mutex<GlobalState>>,
158}
159
160impl VirtualizationServiceInternal {
David Brazdil4b4c5102022-12-19 22:56:20 +0000161 // TODO(b/245727626): Remove after the source files for virtualizationservice
162 // and virtmgr binaries are split from each other.
163 #[allow(dead_code)]
David Brazdil528e0472022-10-10 15:06:02 +0100164 pub fn init() -> VirtualizationServiceInternal {
165 let service = VirtualizationServiceInternal::default();
166
167 std::thread::spawn(|| {
168 if let Err(e) = handle_stream_connection_tombstoned() {
169 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
170 }
171 });
172
173 service
174 }
175}
176
177impl Interface for VirtualizationServiceInternal {}
178
179impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
David Brazdil4b4c5102022-12-19 22:56:20 +0000180 fn removeMemlockRlimit(&self) -> binder::Result<()> {
181 let pid = get_calling_pid();
182 let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY };
183
184 // SAFETY - borrowing the new limit struct only
185 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
186
187 match ret {
188 0 => Ok(()),
189 -1 => Err(Status::new_exception_str(
190 ExceptionCode::ILLEGAL_STATE,
191 Some(std::io::Error::last_os_error().to_string()),
192 )),
193 n => Err(Status::new_exception_str(
194 ExceptionCode::ILLEGAL_STATE,
195 Some(format!("Unexpected return value from prlimit(): {n}")),
196 )),
197 }
198 }
199
David Brazdil528e0472022-10-10 15:06:02 +0100200 fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000201 let client_uid = Uid::from_raw(get_calling_uid());
David Brazdil528e0472022-10-10 15:06:02 +0100202 let state = &mut *self.state.lock().unwrap();
David Brazdil4b4c5102022-12-19 22:56:20 +0000203 state.allocate_vm_context(client_uid).map_err(|e| {
David Brazdil528e0472022-10-10 15:06:02 +0100204 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
David Brazdil4b4c5102022-12-19 22:56:20 +0000205 })
David Brazdil528e0472022-10-10 15:06:02 +0100206 }
David Brazdil49f96f52022-12-16 21:29:13 +0000207
208 fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> {
209 forward_vm_booted_atom(atom);
210 Ok(())
211 }
212
213 fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> {
214 forward_vm_creation_atom(atom);
215 Ok(())
216 }
217
218 fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> {
219 forward_vm_exited_atom(atom);
220 Ok(())
221 }
David Brazdil528e0472022-10-10 15:06:02 +0100222}
223
224/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
225/// of this struct.
226#[derive(Debug, Default)]
David Brazdil73988ea2022-11-11 15:10:32 +0000227struct GlobalState {
228 /// CIDs currently allocated to running VMs. A CID is never recycled as long
229 /// as there is a strong reference held by a GlobalVmContext.
230 held_cids: HashMap<Cid, Weak<Cid>>,
231}
David Brazdil528e0472022-10-10 15:06:02 +0100232
233impl GlobalState {
234 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
235 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
236 /// Android is up.
David Brazdil73988ea2022-11-11 15:10:32 +0000237 fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
238 // Garbage collect unused CIDs.
239 self.held_cids.retain(|_, cid| cid.strong_count() > 0);
240
241 // Start trying to find a CID from the last used CID + 1. This ensures
David Brazdil8cf8f482022-11-23 14:21:26 +0000242 // that we do not eagerly recycle CIDs. It makes debugging easier but
243 // also means that retrying to allocate a CID, eg. because it is
244 // erroneously occupied by a process, will not recycle the same CID.
David Brazdil73988ea2022-11-11 15:10:32 +0000245 let last_cid_prop =
246 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
247 Ok(num) => {
248 if is_valid_guest_cid(num) {
249 Some(num)
250 } else {
251 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
252 None
253 }
254 }
David Brazdil528e0472022-10-10 15:06:02 +0100255 Err(_) => {
256 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000257 None
David Brazdil528e0472022-10-10 15:06:02 +0100258 }
David Brazdil73988ea2022-11-11 15:10:32 +0000259 });
260
261 let first_cid = if let Some(last_cid) = last_cid_prop {
262 next_guest_cid(last_cid)
263 } else {
264 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100265 };
David Brazdil73988ea2022-11-11 15:10:32 +0000266
267 let cid = self
268 .find_available_cid(first_cid..=GUEST_CID_MAX)
269 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
270
271 if let Some(cid) = cid {
272 let cid_arc = Arc::new(cid);
273 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
274 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
275 Ok(cid_arc)
276 } else {
277 Err(anyhow!("Could not find an available CID."))
278 }
279 }
280
281 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
282 where
283 I: Iterator<Item = Cid>,
284 {
285 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100286 }
David Brazdil4b4c5102022-12-19 22:56:20 +0000287
288 fn allocate_vm_context(&mut self, client_uid: Uid) -> Result<Strong<dyn IGlobalVmContext>> {
289 let cid = self.allocate_cid()?;
290 let temp_dir = create_vm_directory(client_uid, *cid)?;
291 let binder = GlobalVmContext { cid, temp_dir, ..Default::default() };
292 Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default()))
293 }
294}
295
296fn create_vm_directory(client_uid: Uid, cid: Cid) -> Result<PathBuf> {
297 let path: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
298 if path.as_path().exists() {
299 remove_temporary_dir(&path).unwrap_or_else(|e| {
300 warn!("Could not delete temporary directory {:?}: {}", path, e);
301 });
302 }
303 // Create a directory that is owned by client's UID but system's GID, and permissions 0700.
304 // If the chown() fails, this will leave behind an empty directory that will get removed
305 // at the next attempt, or if virtualizationservice is restarted.
306 create_dir(&path)
307 .with_context(|| format!("Could not create temporary directory {:?}", path))?;
308 chown(&path, Some(client_uid), None)
309 .with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?;
310 Ok(path)
311}
312
313/// Removes a directory owned by a different user by first changing its owner back
314/// to VirtualizationService.
315pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> {
316 if !path.as_path().is_dir() {
317 bail!("Path {:?} is not a directory", path);
318 }
319 chown(path, Some(Uid::current()), None)?;
320 set_permissions(path, Permissions::from_mode(0o700))?;
321 remove_temporary_files(path)?;
322 remove_dir(path)?;
323 Ok(())
324}
325
326pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
327 for dir_entry in read_dir(path)? {
328 remove_file(dir_entry?.path())?;
329 }
330 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100331}
332
333/// Implementation of the AIDL `IGlobalVmContext` interface.
334#[derive(Debug, Default)]
335struct GlobalVmContext {
336 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000337 cid: Arc<Cid>,
David Brazdil4b4c5102022-12-19 22:56:20 +0000338 /// The temporary folder created for the VM and owned by the creator's UID.
339 temp_dir: PathBuf,
David Brazdil73988ea2022-11-11 15:10:32 +0000340 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100341 #[allow(dead_code)]
342 lazy_service_guard: LazyServiceGuard,
343}
344
David Brazdil528e0472022-10-10 15:06:02 +0100345impl Interface for GlobalVmContext {}
346
347impl IGlobalVmContext for GlobalVmContext {
348 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000349 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100350 }
David Brazdil4b4c5102022-12-19 22:56:20 +0000351
352 fn getTemporaryDirectory(&self) -> binder::Result<String> {
353 Ok(self.temp_dir.to_string_lossy().to_string())
354 }
David Brazdil528e0472022-10-10 15:06:02 +0100355}
356
357/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000358#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000359pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900360 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000361}
362
Shikha Panward8e35422021-10-11 13:51:27 +0000363impl Interface for VirtualizationService {
364 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
365 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
366 let state = &mut *self.state.lock().unwrap();
367 let vms = state.vms();
368 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
369 for vm in vms {
370 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
371 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
372 .or(Err(StatusCode::UNKNOWN_ERROR))?;
373 writeln!(file, "\tPayload state {:?}", vm.payload_state())
374 .or(Err(StatusCode::UNKNOWN_ERROR))?;
375 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
376 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
377 .or(Err(StatusCode::UNKNOWN_ERROR))?;
378 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
379 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000380 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
381 .or(Err(StatusCode::UNKNOWN_ERROR))?;
382 }
383 Ok(())
384 }
385}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000386
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000387impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000388 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
389 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000390 ///
391 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000392 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000393 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000394 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900395 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000396 log_fd: Option<&ParcelFileDescriptor>,
397 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000398 let mut is_protected = false;
399 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000400 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000401 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000402 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000403
Andrew Walbrandff3b942021-06-09 15:20:36 +0000404 /// Initialise an empty partition image of the given size to be used as a writable partition.
405 fn initializeWritablePartition(
406 &self,
407 image_fd: &ParcelFileDescriptor,
408 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900409 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000410 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900411 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000412 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000413 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000414 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100415 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000416 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000417 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000418 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900419 // initialize the file. Any data in the file will be erased.
420 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000421 Status::new_service_specific_error_str(
422 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100423 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900424 )
425 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900426 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000427 Status::new_service_specific_error_str(
428 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100429 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000430 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000431 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000432
Jiyong Park9dd389e2021-08-23 20:42:59 +0900433 match partition_type {
434 PartitionType::RAW => Ok(()),
435 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000436 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900437 _ => Err(Error::new(
438 ErrorKind::Unsupported,
439 format!("Unsupported partition type {:?}", partition_type),
440 )),
441 }
442 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000443 Status::new_service_specific_error_str(
444 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100445 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900446 )
447 })?;
448
Andrew Walbrandff3b942021-06-09 15:20:36 +0000449 Ok(())
450 }
451
Jiyong Park0a248432021-08-20 23:32:39 +0900452 /// Creates or update the idsig file by digesting the input APK file.
453 fn createOrUpdateIdsigFile(
454 &self,
455 input_fd: &ParcelFileDescriptor,
456 idsig_fd: &ParcelFileDescriptor,
457 ) -> binder::Result<()> {
458 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
459 // idsig_fd is different from APK digest in input_fd
460
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900461 check_manage_access()?;
462
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000463 create_or_update_idsig_file(input_fd, idsig_fd)
464 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900465 Ok(())
466 }
467
Andrew Walbran320b5602021-03-04 16:11:12 +0000468 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
469 /// and as such is only permitted from the shell user.
470 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000471 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000472
473 let state = &mut *self.state.lock().unwrap();
474 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000475 let cids = vms
476 .into_iter()
477 .map(|vm| VirtualMachineDebugInfo {
478 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000479 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000480 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000481 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000482 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000483 })
484 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000485 Ok(cids)
486 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000487
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000488 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
489 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000490 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000491 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000492
David Brazdil3c2ddef2021-03-18 13:09:57 +0000493 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000494 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000495 Ok(())
496 }
497
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000498 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
499 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
500 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000501 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000502 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000503
504 let state = &mut *self.state.lock().unwrap();
505 Ok(state.debug_drop_vm(cid))
506 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000507}
508
Shikha Panwar7afc1392022-03-24 08:54:43 +0000509fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000510 // Should not listen for tombstones on a guest VM's port.
511 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000512 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000513 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000514 for incoming_stream in listener.incoming() {
515 let mut incoming_stream = match incoming_stream {
516 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100517 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000518 continue;
519 }
520 Ok(s) => s,
521 };
522 std::thread::spawn(move || {
523 if let Err(e) = handle_tombstone(&mut incoming_stream) {
524 error!("Failed to write tombstone- {:?}", e);
525 }
526 });
527 }
528 Ok(())
529}
530
531fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000532 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000533 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
534 }
535 let tb_connection =
536 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
537 .context("Failed to connect to tombstoned")?;
538 let mut text_output = tb_connection
539 .text_output
540 .as_ref()
541 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
542 let mut num_bytes_read = 0;
543 loop {
544 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
545 let n = stream
546 .read(&mut chunk_recv)
547 .context("Failed to read tombstone data from Vsock stream")?;
548 if n == 0 {
549 break;
550 }
551 num_bytes_read += n;
552 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
553 }
554 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
555 tb_connection.notify_completion()?;
556 Ok(())
557}
558
Jiyong Park8611a6c2021-07-09 18:17:44 +0900559impl VirtualizationService {
David Brazdil4b4c5102022-12-19 22:56:20 +0000560 // TODO(b/245727626): Remove after the source files for virtualizationservice
561 // and virtmgr binaries are split from each other.
562 #[allow(dead_code)]
Jiyong Park8611a6c2021-07-09 18:17:44 +0900563 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000564 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900565 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000566
David Brazdil4b4c5102022-12-19 22:56:20 +0000567 fn create_vm_context(&self) -> Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000568 const NUM_ATTEMPTS: usize = 5;
569
570 for _ in 0..NUM_ATTEMPTS {
David Brazdil49f96f52022-12-16 21:29:13 +0000571 let global_context = GLOBAL_SERVICE.allocateGlobalVmContext()?;
David Brazdil8cf8f482022-11-23 14:21:26 +0000572 let cid = global_context.getCid()? as Cid;
David Brazdil4b4c5102022-12-19 22:56:20 +0000573 let temp_dir: PathBuf = global_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000574 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
575
576 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000577 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000578 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000579 Ok(vm_server) => {
580 vm_server.start();
David Brazdil4b4c5102022-12-19 22:56:20 +0000581 return Ok((VmContext::new(global_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000582 }
583 Err(err) => {
584 warn!("Could not start RpcServer on port {}: {}", port, err);
585 }
586 }
587 }
588 bail!("Too many attempts to create VM context failed.");
589 }
590
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000591 fn create_vm_internal(
592 &self,
593 config: &VirtualMachineConfig,
594 console_fd: Option<&ParcelFileDescriptor>,
595 log_fd: Option<&ParcelFileDescriptor>,
596 is_protected: &mut bool,
597 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
598 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900599
Alan Stokes7bc146c2022-10-20 17:10:32 +0100600 let is_custom = match config {
601 VirtualMachineConfig::RawConfig(_) => true,
602 VirtualMachineConfig::AppConfig(config) => {
603 // Some features are reserved for platform apps only, even when using
604 // VirtualMachineAppConfig:
605 // - controlling CPUs;
606 // - specifying a config file in the APK.
607 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900608 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100609 };
610 if is_custom {
611 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900612 }
613
David Brazdil4b4c5102022-12-19 22:56:20 +0000614 let (vm_context, cid, temporary_directory) = self.create_vm_context().map_err(|e| {
David Brazdil8cf8f482022-11-23 14:21:26 +0000615 error!("Failed to create VmContext: {:?}", e);
616 Status::new_service_specific_error_str(
617 -1,
618 Some(format!("Failed to create VmContext: {:?}", e)),
619 )
620 })?;
David Brazdil528e0472022-10-10 15:06:02 +0100621
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000622 let state = &mut *self.state.lock().unwrap();
623 let console_fd = console_fd.map(clone_file).transpose()?;
624 let log_fd = log_fd.map(clone_file).transpose()?;
David Brazdil1f530702022-10-03 12:18:10 +0100625 let requester_uid = get_calling_uid();
626 let requester_debug_pid = get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000627
628 // Counter to generate unique IDs for temporary image files.
629 let mut next_temporary_image_id = 0;
630 // Files which are referred to from composite images. These must be mapped to the crosvm
631 // child process, and not closed before it is started.
632 let mut indirect_files = vec![];
633
Alan Stokes7bc146c2022-10-20 17:10:32 +0100634 let (is_app_config, config) = match config {
635 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
636 VirtualMachineConfig::AppConfig(config) => {
637 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000638 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100639 let message = format!("Failed to load app config: {:?}", e);
640 error!("{}", message);
641 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100642 })?;
643 (true, BorrowedOrOwned::Owned(config))
644 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000645 };
646 let config = config.as_ref();
647 *is_protected = config.protectedVm;
648
649 // Check if partition images are labeled incorrectly. This is to prevent random images
650 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100651 // being loaded in a pVM. This applies to everything in the raw config, and everything but
652 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000653 config
654 .disks
655 .iter()
656 .flat_map(|disk| disk.partitions.iter())
657 .filter(|partition| {
658 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100659 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000660 } else {
661 true // all partitions are checked
662 }
663 })
664 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100665 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000666
667 let zero_filler_path = temporary_directory.join("zero.img");
668 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100669 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000670 Status::new_service_specific_error_str(
671 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100672 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000673 )
674 })?;
675
676 // Assemble disk images if needed.
677 let disks = config
678 .disks
679 .iter()
680 .map(|disk| {
681 assemble_disk_image(
682 disk,
683 &zero_filler_path,
684 &temporary_directory,
685 &mut next_temporary_image_id,
686 &mut indirect_files,
687 )
688 })
689 .collect::<Result<Vec<DiskFile>, _>>()?;
690
Jiyong Parke558ab12022-07-07 20:18:55 +0900691 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
692 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900693 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900694 // will be sent back to the client (i.e. the VM owner) for readout.
695 let ramdump_path = temporary_directory.join("ramdump");
696 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100697 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000698 Status::new_service_specific_error_str(
699 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100700 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900701 )
702 })?;
703
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000704 // Actually start the VM.
705 let crosvm_config = CrosvmConfig {
706 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000707 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000708 bootloader: maybe_clone_file(&config.bootloader)?,
709 kernel: maybe_clone_file(&config.kernel)?,
710 initrd: maybe_clone_file(&config.initrd)?,
711 disks,
712 params: config.params.to_owned(),
713 protected: *is_protected,
714 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
715 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900716 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000717 console_fd,
718 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900719 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000720 indirect_files,
721 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900722 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000723 };
724 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100725 VmInstance::new(
726 crosvm_config,
727 temporary_directory,
728 requester_uid,
729 requester_debug_pid,
730 vm_context,
731 )
732 .map_err(|e| {
733 error!("Failed to create VM with config {:?}: {:?}", config, e);
734 Status::new_service_specific_error_str(
735 -1,
736 Some(format!("Failed to create VM: {:?}", e)),
737 )
738 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000739 );
740 state.add_vm(Arc::downgrade(&instance));
741 Ok(VirtualMachine::create(instance))
742 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900743}
744
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000745fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900746 let file = OpenOptions::new()
747 .create_new(true)
748 .read(true)
749 .write(true)
750 .open(zero_filler_path)
751 .with_context(|| "Failed to create zero.img")?;
752 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000753 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900754}
755
Jiyong Park9dd389e2021-08-23 20:42:59 +0900756fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
757 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
758 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
759 part.flush()
760}
761
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000762fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
763 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
764 part.flush()
765}
766
Jiyong Parke558ab12022-07-07 20:18:55 +0900767fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800768 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900769}
770
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000771/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
772///
773/// This may involve assembling a composite disk from a set of partition images.
774fn assemble_disk_image(
775 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900776 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000777 temporary_directory: &Path,
778 next_temporary_image_id: &mut u64,
779 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000780) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000781 let image = if !disk.partitions.is_empty() {
782 if disk.image.is_some() {
783 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000784 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000785 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000786 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000787 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000788 }
789
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000790 let composite_image_filenames =
791 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
792 let (image, partition_files) = make_composite_image(
793 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900794 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000795 &composite_image_filenames.composite,
796 &composite_image_filenames.header,
797 &composite_image_filenames.footer,
798 )
799 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100800 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000801 Status::new_service_specific_error_str(
802 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100803 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000804 )
805 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000806
807 // Pass the file descriptors for the various partition files to crosvm when it
808 // is run.
809 indirect_files.extend(partition_files);
810
811 image
812 } else if let Some(image) = &disk.image {
813 clone_file(image)?
814 } else {
815 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000816 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000817 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000818 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000819 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000820 };
821
822 Ok(DiskFile { image, writable: disk.writable })
823}
824
Jooyung Han21e9b922021-06-26 04:14:16 +0900825fn load_app_config(
826 config: &VirtualMachineAppConfig,
827 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900828) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000829 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
830 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900831 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900832
Shikha Panwar22e70452022-10-10 18:32:55 +0000833 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
834 Some(clone_file(file)?)
835 } else {
836 None
837 };
838
Alan Stokes0d1ef782022-09-27 13:46:35 +0100839 let vm_payload_config = match &config.payload {
840 Payload::ConfigPath(config_path) => {
841 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
842 .with_context(|| format!("Couldn't read config from {}", config_path))?
843 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000844 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100845 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900846
Alan Stokes0d1ef782022-09-27 13:46:35 +0100847 // For now, the only supported OS is Microdroid
848 let os_name = vm_payload_config.os.name.as_str();
849 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000850 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900851 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000852
853 // It is safe to construct a filename based on the os_name because we've already checked that it
854 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900855 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
856 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000857 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900858
Andrew Walbrancc045902021-07-27 16:06:17 +0000859 if config.memoryMib > 0 {
860 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000861 }
862
Seungjae Yoo62085c02022-08-12 04:44:52 +0000863 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000864 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900865 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900866 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900867
Shikha Panwar22e70452022-10-10 18:32:55 +0000868 // Microdroid takes additional init ramdisk & (optionally) storage image
869 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
870
871 // Include Microdroid payload disk (contains apks, idsigs) in vm config
872 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100873 config,
874 temporary_directory,
875 apk_file,
876 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100877 &vm_payload_config,
878 &mut vm_config,
879 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900880
Andrew Walbrancc0db522021-07-12 17:03:42 +0000881 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900882}
883
Alan Stokes0d1ef782022-09-27 13:46:35 +0100884fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
885 let mut apk_zip = ZipArchive::new(apk_file)?;
886 let config_file = apk_zip.by_name(config_path)?;
887 Ok(serde_json::from_reader(config_file)?)
888}
889
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000890fn create_vm_payload_config(
891 payload_config: &VirtualMachinePayloadConfig,
892) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100893 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
894 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
895 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000896
897 let payload_binary_name = &payload_config.payloadBinaryName;
898 if payload_binary_name.contains('/') {
899 bail!("Payload binary name must not specify a path: {payload_binary_name}");
900 }
901
902 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
903 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100904 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
905 task: Some(task),
906 apexes: vec![],
907 extra_apks: vec![],
908 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100909 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100910 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000911 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100912}
913
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000914/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000915fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000916 temporary_directory: &Path,
917 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000918) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000919 let id = *next_temporary_image_id;
920 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000921 CompositeImageFilenames {
922 composite: temporary_directory.join(format!("composite-{}.img", id)),
923 header: temporary_directory.join(format!("composite-{}-header.img", id)),
924 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
925 }
926}
927
928/// Filenames for a composite disk image, including header and footer partitions.
929#[derive(Clone, Debug, Eq, PartialEq)]
930struct CompositeImageFilenames {
931 /// The composite disk image itself.
932 composite: PathBuf,
933 /// The header partition image.
934 header: PathBuf,
935 /// The footer partition image.
936 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000937}
938
Jiyong Park753553b2021-07-12 21:21:09 +0900939/// Checks whether the caller has a specific permission
940fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100941 let calling_pid = get_calling_pid();
942 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900943 // Root can do anything
944 if calling_uid == 0 {
945 return Ok(());
946 }
947 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
948 binder::get_interface("permission")?;
949 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000950 Ok(())
951 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000952 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900953 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000954 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900955 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000956 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000957}
958
Jiyong Park753553b2021-07-12 21:21:09 +0900959/// Check whether the caller of the current Binder method is allowed to call debug methods.
960fn check_debug_access() -> binder::Result<()> {
961 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
962}
963
964/// Check whether the caller of the current Binder method is allowed to manage VMs
965fn check_manage_access() -> binder::Result<()> {
966 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
967}
968
Inseob Kim1119d702022-05-02 18:01:58 +0900969/// Check whether the caller of the current Binder method is allowed to create custom VMs
970fn check_use_custom_virtual_machine() -> binder::Result<()> {
971 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
972}
973
Jiyong Park029977d2021-11-24 21:56:49 +0900974/// Check if a partition has selinux labels that are not allowed
975fn check_label_for_partition(partition: &Partition) -> Result<()> {
976 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100977 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
978}
979
980// Return whether a partition is exempt from selinux label checks, because we know that it does
981// not contain code and is likely to be generated in an app-writable directory.
982fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000983 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100984 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000985 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100986 || label == "microdroid-apk-idsig"
987 || label == "payload-metadata"
988 || label.starts_with("extra-idsig-")
989}
990
991fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
992 // We only want to allow code in a VM payload to be sourced from places that apps, and the
993 // system, do not have write access to.
994 // (Note that sepolicy must also grant read access for these types to both virtualization
995 // service and crosvm.)
996 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
997 // user devices (W^X).
998 match ctx.selinux_type()? {
999 | "system_file" // immutable dm-verity protected partition
1000 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001001 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001002 | "shell_data_file" // test files created via adb shell
1003 => Ok(()),
1004 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +09001005 }
1006}
1007
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001008/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1009#[derive(Debug)]
1010struct VirtualMachine {
1011 instance: Arc<VmInstance>,
1012}
1013
1014impl VirtualMachine {
1015 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001016 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001017 }
1018}
1019
1020impl Interface for VirtualMachine {}
1021
1022impl IVirtualMachine for VirtualMachine {
1023 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001024 // Don't check permission. The owner of the VM might have passed this binder object to
1025 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001026 Ok(self.instance.cid as i32)
1027 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001028
Andrew Walbran6b650662021-09-07 13:13:23 +00001029 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001030 // Don't check permission. The owner of the VM might have passed this binder object to
1031 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001032 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001033 }
1034
1035 fn registerCallback(
1036 &self,
1037 callback: &Strong<dyn IVirtualMachineCallback>,
1038 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001039 // Don't check permission. The owner of the VM might have passed this binder object to
1040 // others.
1041 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001042 // TODO: Should this give an error if the VM is already dead?
1043 self.instance.callbacks.add(callback.clone());
1044 Ok(())
1045 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001046
Andrew Walbranf8d94112021-09-07 11:45:36 +00001047 fn start(&self) -> binder::Result<()> {
1048 self.instance.start().map_err(|e| {
1049 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001050 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +00001051 })
1052 }
1053
Inseob Kima446f802022-07-11 19:46:37 +09001054 fn stop(&self) -> binder::Result<()> {
1055 self.instance.kill().map_err(|e| {
1056 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001057 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +09001058 })
1059 }
1060
Keir Frasercdd4b112022-11-24 14:02:25 +00001061 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
1062 self.instance.trim_memory(level).map_err(|e| {
1063 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
1064 Status::new_service_specific_error_str(-1, Some(e.to_string()))
1065 })
1066 }
1067
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001068 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001069 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001070 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001071 }
Alan Stokes10c47672022-12-13 17:17:08 +00001072 let port = port as u32;
1073 if port < 1024 {
1074 return Err(Status::new_service_specific_error_str(
1075 -1,
1076 Some(format!("Can't connect to privileged port {port}")),
1077 ));
1078 }
1079 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
1080 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
1081 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001082 Ok(vsock_stream_to_pfd(stream))
1083 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001084}
1085
1086impl Drop for VirtualMachine {
1087 fn drop(&mut self) {
1088 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001089 if let Err(e) = self.instance.kill() {
1090 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1091 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001092 }
1093}
1094
1095/// A set of Binders to be called back in response to various events on the VM, such as when it
1096/// dies.
1097#[derive(Debug, Default)]
1098pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1099
1100impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001101 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001102 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001103 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001104 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001105 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001106 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001107 }
1108 }
1109 }
1110
Inseob Kim14cb8692021-08-31 21:50:39 +09001111 /// Call all registered callbacks to notify that the payload is ready to serve.
1112 pub fn notify_payload_ready(&self, cid: Cid) {
1113 let callbacks = &*self.0.lock().unwrap();
1114 for callback in callbacks {
1115 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001116 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001117 }
1118 }
1119 }
1120
Inseob Kim2444af92021-08-31 01:22:50 +09001121 /// Call all registered callbacks to notify that the payload has finished.
1122 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1123 let callbacks = &*self.0.lock().unwrap();
1124 for callback in callbacks {
1125 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001126 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001127 }
1128 }
1129 }
1130
Jooyung Handd0a1732021-11-23 15:26:20 +09001131 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001132 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001133 let callbacks = &*self.0.lock().unwrap();
1134 for callback in callbacks {
1135 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001136 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001137 }
1138 }
1139 }
1140
Andrew Walbrandae07162021-03-12 17:05:20 +00001141 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001142 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001143 let callbacks = &*self.0.lock().unwrap();
1144 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001145 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001146 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001147 }
1148 }
1149 }
1150
1151 /// Add a new callback to the set.
1152 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1153 self.0.lock().unwrap().push(callback);
1154 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001155}
1156
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001157/// The mutable state of the VirtualizationService. There should only be one instance of this
1158/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001159#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001160struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001161 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1162 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1163 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1164 /// from the list opportunistically the next time `add_vm` is called.
1165 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001166
1167 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1168 /// This is only used for debugging purposes.
1169 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001170}
1171
1172impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001173 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001174 fn vms(&self) -> Vec<Arc<VmInstance>> {
1175 // Attempt to upgrade the weak pointers to strong pointers.
1176 self.vms.iter().filter_map(Weak::upgrade).collect()
1177 }
1178
1179 /// Add a new VM to the list.
1180 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1181 // Garbage collect any entries from the stored list which no longer exist.
1182 self.vms.retain(|vm| vm.strong_count() > 0);
1183
1184 // Actually add the new VM.
1185 self.vms.push(vm);
1186 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001187
Jiyong Park8611a6c2021-07-09 18:17:44 +09001188 /// Get a VM that corresponds to the given cid
1189 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1190 self.vms().into_iter().find(|vm| vm.cid == cid)
1191 }
1192
David Brazdil3c2ddef2021-03-18 13:09:57 +00001193 /// Store a strong VM reference.
1194 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1195 self.debug_held_vms.push(vm);
1196 }
1197
1198 /// Retrieve and remove a strong VM reference.
1199 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1200 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001201 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001202 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001203 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001204}
1205
Andrew Walbran6b650662021-09-07 13:13:23 +00001206/// Gets the `VirtualMachineState` of the given `VmInstance`.
1207fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001208 match &*instance.vm_state.lock().unwrap() {
1209 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1210 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001211 PayloadState::Starting => VirtualMachineState::STARTING,
1212 PayloadState::Started => VirtualMachineState::STARTED,
1213 PayloadState::Ready => VirtualMachineState::READY,
1214 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001215 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001216 },
1217 VmState::Dead => VirtualMachineState::DEAD,
1218 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001219 }
1220}
1221
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001222/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001223pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001224 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001225 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001226 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001227 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001228 )
1229 })
1230}
1231
Andrew Walbrand3a84182021-09-07 14:48:52 +00001232/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1233fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1234 file.as_ref().map(clone_file).transpose()
1235}
1236
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001237/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1238fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1239 // SAFETY: ownership is transferred from stream to f
1240 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1241 ParcelFileDescriptor::new(f)
1242}
1243
Jiyong Parkdcf17412022-02-08 15:07:23 +09001244/// Parses the platform version requirement string.
1245fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1246 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001247 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001248 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001249 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001250 )
1251 })
1252}
1253
Jooyung Han35edb8f2021-07-01 16:17:16 +09001254/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1255/// it doesn't require that T implements Clone.
1256enum BorrowedOrOwned<'a, T> {
1257 Borrowed(&'a T),
1258 Owned(T),
1259}
1260
1261impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1262 fn as_ref(&self) -> &T {
1263 match self {
1264 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001265 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001266 }
1267 }
1268}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001269
1270/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1271#[derive(Debug, Default)]
1272struct VirtualMachineService {
1273 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001274 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001275}
1276
1277impl Interface for VirtualMachineService {}
1278
1279impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001280 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1281 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001282 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001283 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001284 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1285 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1286 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001287 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001288
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001289 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1290 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001291 Ok(())
1292 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001293 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001294 Err(Status::new_service_specific_error_str(
1295 -1,
1296 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001297 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001298 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001299 }
Inseob Kim2444af92021-08-31 01:22:50 +09001300
Inseob Kimc7d28c72021-10-25 14:28:10 +00001301 fn notifyPayloadReady(&self) -> binder::Result<()> {
1302 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001303 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001304 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001305 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1306 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1307 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001308 vm.callbacks.notify_payload_ready(cid);
1309 Ok(())
1310 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001311 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001312 Err(Status::new_service_specific_error_str(
1313 -1,
1314 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001315 ))
1316 }
1317 }
1318
Inseob Kimc7d28c72021-10-25 14:28:10 +00001319 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1320 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001321 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001322 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001323 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1324 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1325 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001326 vm.callbacks.notify_payload_finished(cid, exit_code);
1327 Ok(())
1328 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001329 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001330 Err(Status::new_service_specific_error_str(
1331 -1,
1332 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001333 ))
1334 }
1335 }
1336
Alan Stokes2bead0d2022-09-05 16:58:34 +01001337 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001338 let cid = self.cid;
1339 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001340 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001341 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1342 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1343 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001344 vm.callbacks.notify_error(cid, error_code, message);
1345 Ok(())
1346 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001347 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001348 Err(Status::new_service_specific_error_str(
1349 -1,
1350 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001351 ))
1352 }
1353 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001354}
1355
1356impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001357 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001358 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001359 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001360 BinderFeatures::default(),
1361 )
1362 }
1363}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001364
1365#[cfg(test)]
1366mod tests {
1367 use super::*;
1368
1369 #[test]
1370 fn test_is_allowed_label_for_partition() -> Result<()> {
1371 let expected_results = vec![
1372 ("u:object_r:system_file:s0", true),
1373 ("u:object_r:apk_data_file:s0", true),
1374 ("u:object_r:app_data_file:s0", false),
1375 ("u:object_r:app_data_file:s0:c512,c768", false),
1376 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1377 ("invalid", false),
1378 ("user:role:apk_data_file:severity:categories", true),
1379 ("user:role:apk_data_file:severity:categories:extraneous", false),
1380 ];
1381
1382 for (label, expected_valid) in expected_results {
1383 let context = SeContext::new(label)?;
1384 let result = check_label_is_allowed(&context);
1385 if expected_valid {
1386 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1387 } else if result.is_ok() {
1388 bail!("Expected label {} to be disallowed", label);
1389 }
1390 }
1391 Ok(())
1392 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001393
1394 #[test]
1395 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1396 let apk = tempfile::tempfile().unwrap();
1397 let idsig = tempfile::tempfile().unwrap();
1398
1399 let ret = create_or_update_idsig_file(
1400 &ParcelFileDescriptor::new(apk),
1401 &ParcelFileDescriptor::new(idsig),
1402 );
1403 assert!(ret.is_err(), "should fail");
1404 Ok(())
1405 }
1406
1407 #[test]
1408 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1409 let tmp_dir = tempfile::TempDir::new().unwrap();
1410 let apk = File::open(tmp_dir.path()).unwrap();
1411 let idsig = tempfile::tempfile().unwrap();
1412
1413 let ret = create_or_update_idsig_file(
1414 &ParcelFileDescriptor::new(apk),
1415 &ParcelFileDescriptor::new(idsig),
1416 );
1417 assert!(ret.is_err(), "should fail");
1418 Ok(())
1419 }
1420
1421 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1422 /// on ext4 filesystem is passed.
1423 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1424 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1425 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1426 #[test]
1427 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1428 // APEXes are backed by the ext4.
1429 let apk = File::open("/apex/com.android.virt/").unwrap();
1430 let idsig = tempfile::tempfile().unwrap();
1431
1432 let ret = create_or_update_idsig_file(
1433 &ParcelFileDescriptor::new(apk),
1434 &ParcelFileDescriptor::new(idsig),
1435 );
1436 assert!(ret.is_err(), "should fail");
1437 Ok(())
1438 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001439}