blob: 3e7eca1cf188cb576e4389181c92150d7c73a986 [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 Brazdil49f96f52022-12-16 21:29:13 +000017use crate::atom::{
18 forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom,
19 write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020use crate::composite::make_composite_image;
David Brazdil8cf8f482022-11-23 14:21:26 +000021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
Shikha Panwar22e70452022-10-10 18:32:55 +000022use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090023use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090024use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000025use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000026 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000027 ErrorCode::ErrorCode,
28};
29use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000030 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010031 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000032 IVirtualMachineCallback::IVirtualMachineCallback,
33 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000034 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090035 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 PartitionType::PartitionType,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090037 VirtualMachineAppConfig::{Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090038 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000039 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010040 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090041 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090043};
David Brazdil528e0472022-10-10 15:06:02 +010044use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
David Brazdil49f96f52022-12-16 21:29:13 +000045 AtomVmBooted::AtomVmBooted,
46 AtomVmCreationRequested::AtomVmCreationRequested,
47 AtomVmExited::AtomVmExited,
David Brazdil528e0472022-10-10 15:06:02 +010048 IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
49 IVirtualizationServiceInternal::{BnVirtualizationServiceInternal, IVirtualizationServiceInternal},
50};
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdil73988ea2022-11-11 15:10:32 +000052 BnVirtualMachineService, IVirtualMachineService, VM_TOMBSTONES_SERVICE_PORT,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
54use anyhow::{anyhow, bail, Context, Result};
55use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010056use binder::{
Andrew Walbran46999c92022-08-04 17:33:46 +000057 self, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, ParcelFileDescriptor,
David Brazdil73988ea2022-11-11 15:10:32 +000058 Status, StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000059};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000060use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000061use lazy_static::lazy_static;
David Brazdila07a1792022-10-25 13:37:57 +010062use libc::VMADDR_CID_HOST;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000063use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
David Brazdil73988ea2022-11-11 15:10:32 +000065use rpcbinder::RpcServer;
Jiyong Parkd50a0242021-09-16 21:00:14 +090066use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090067use semver::VersionReq;
David Brazdil73988ea2022-11-11 15:10:32 +000068use std::collections::HashMap;
Andrew Walbrandff3b942021-06-09 15:20:36 +000069use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000070use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010071use std::fs::{create_dir, File, OpenOptions};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090072use std::io::{Error, ErrorKind, Read, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000073use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000074use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000076use std::sync::{Arc, Mutex, Weak};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090077use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
Andrew Walbrancc0db522021-07-12 17:03:42 +000078use vmconfig::VmConfig;
Andrew Walbranadd38cb2022-10-06 17:01:03 +000079use vsock::{VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090080use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000081
David Brazdil41d1a872022-10-05 14:44:19 +010082/// The unique ID of a VM used (together with a port number) for vsock communication.
83pub type Cid = u32;
84
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000088pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089
David Brazdil41d1a872022-10-05 14:44:19 +010090/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
91/// are reserved for the host or other usage.
David Brazdil73988ea2022-11-11 15:10:32 +000092const GUEST_CID_MIN: Cid = 2048;
93const GUEST_CID_MAX: Cid = 65535;
David Brazdil41d1a872022-10-05 14:44:19 +010094
95const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
Jiyong Park8611a6c2021-07-09 18:17:44 +090096
Jooyung Han95884632021-07-06 22:27:54 +090097/// The size of zero.img.
98/// Gaps in composite disk images are filled with a shared zero.img.
99const ZERO_FILLER_SIZE: u64 = 4096;
100
Jiyong Park9dd389e2021-08-23 20:42:59 +0900101/// Magic string for the instance image
102const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
103
104/// Version of the instance image format
105const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
106
Shikha Panwar7afc1392022-03-24 08:54:43 +0000107const CHUNK_RECV_MAX_LEN: usize = 1024;
108
Alan Stokes0d1ef782022-09-27 13:46:35 +0100109const MICRODROID_OS_NAME: &str = "microdroid";
110
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000111const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
112
David Brazdil49f96f52022-12-16 21:29:13 +0000113lazy_static! {
114 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> = {
115 let service = VirtualizationServiceInternal::init();
116 BnVirtualizationServiceInternal::new_binder(service, BinderFeatures::default())
117 };
118}
119
David Brazdil73988ea2022-11-11 15:10:32 +0000120fn is_valid_guest_cid(cid: Cid) -> bool {
121 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
122}
123
124fn next_guest_cid(cid: Cid) -> Cid {
125 assert!(is_valid_guest_cid(cid));
126 if cid == GUEST_CID_MAX {
127 GUEST_CID_MIN
128 } else {
129 cid + 1
130 }
131}
132
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000133fn create_or_update_idsig_file(
134 input_fd: &ParcelFileDescriptor,
135 idsig_fd: &ParcelFileDescriptor,
136) -> Result<()> {
137 let mut input = clone_file(input_fd)?;
138 let metadata = input.metadata().context("failed to get input metadata")?;
139 if !metadata.is_file() {
140 bail!("input is not a regular file");
141 }
142 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
143 .context("failed to create idsig")?;
144
145 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000146 output.set_len(0).context("failed to set_len on the idsig output")?;
147 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000148 Ok(())
149}
150
David Brazdil528e0472022-10-10 15:06:02 +0100151/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
152/// singleton servers, like tombstone receiver.
Jooyung Han9900f3d2021-07-06 10:27:54 +0900153#[derive(Debug, Default)]
David Brazdil528e0472022-10-10 15:06:02 +0100154pub struct VirtualizationServiceInternal {
155 state: Arc<Mutex<GlobalState>>,
156}
157
158impl VirtualizationServiceInternal {
159 pub fn init() -> VirtualizationServiceInternal {
160 let service = VirtualizationServiceInternal::default();
161
162 std::thread::spawn(|| {
163 if let Err(e) = handle_stream_connection_tombstoned() {
164 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
165 }
166 });
167
168 service
169 }
170}
171
172impl Interface for VirtualizationServiceInternal {}
173
174impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
175 fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
176 let state = &mut *self.state.lock().unwrap();
177 let cid = state.allocate_cid().map_err(|e| {
178 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
179 })?;
180 Ok(GlobalVmContext::create(cid))
181 }
David Brazdil49f96f52022-12-16 21:29:13 +0000182
183 fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> {
184 forward_vm_booted_atom(atom);
185 Ok(())
186 }
187
188 fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> {
189 forward_vm_creation_atom(atom);
190 Ok(())
191 }
192
193 fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> {
194 forward_vm_exited_atom(atom);
195 Ok(())
196 }
David Brazdil528e0472022-10-10 15:06:02 +0100197}
198
199/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
200/// of this struct.
201#[derive(Debug, Default)]
David Brazdil73988ea2022-11-11 15:10:32 +0000202struct GlobalState {
203 /// CIDs currently allocated to running VMs. A CID is never recycled as long
204 /// as there is a strong reference held by a GlobalVmContext.
205 held_cids: HashMap<Cid, Weak<Cid>>,
206}
David Brazdil528e0472022-10-10 15:06:02 +0100207
208impl GlobalState {
209 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
210 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
211 /// Android is up.
David Brazdil73988ea2022-11-11 15:10:32 +0000212 fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
213 // Garbage collect unused CIDs.
214 self.held_cids.retain(|_, cid| cid.strong_count() > 0);
215
216 // Start trying to find a CID from the last used CID + 1. This ensures
David Brazdil8cf8f482022-11-23 14:21:26 +0000217 // that we do not eagerly recycle CIDs. It makes debugging easier but
218 // also means that retrying to allocate a CID, eg. because it is
219 // erroneously occupied by a process, will not recycle the same CID.
David Brazdil73988ea2022-11-11 15:10:32 +0000220 let last_cid_prop =
221 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
222 Ok(num) => {
223 if is_valid_guest_cid(num) {
224 Some(num)
225 } else {
226 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
227 None
228 }
229 }
David Brazdil528e0472022-10-10 15:06:02 +0100230 Err(_) => {
231 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
David Brazdil73988ea2022-11-11 15:10:32 +0000232 None
David Brazdil528e0472022-10-10 15:06:02 +0100233 }
David Brazdil73988ea2022-11-11 15:10:32 +0000234 });
235
236 let first_cid = if let Some(last_cid) = last_cid_prop {
237 next_guest_cid(last_cid)
238 } else {
239 GUEST_CID_MIN
David Brazdil528e0472022-10-10 15:06:02 +0100240 };
David Brazdil73988ea2022-11-11 15:10:32 +0000241
242 let cid = self
243 .find_available_cid(first_cid..=GUEST_CID_MAX)
244 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
245
246 if let Some(cid) = cid {
247 let cid_arc = Arc::new(cid);
248 self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
249 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
250 Ok(cid_arc)
251 } else {
252 Err(anyhow!("Could not find an available CID."))
253 }
254 }
255
256 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
257 where
258 I: Iterator<Item = Cid>,
259 {
260 range.find(|cid| !self.held_cids.contains_key(cid))
David Brazdil528e0472022-10-10 15:06:02 +0100261 }
262}
263
264/// Implementation of the AIDL `IGlobalVmContext` interface.
265#[derive(Debug, Default)]
266struct GlobalVmContext {
267 /// The unique CID assigned to the VM for vsock communication.
David Brazdil73988ea2022-11-11 15:10:32 +0000268 cid: Arc<Cid>,
269 /// Keeps our service process running as long as this VM context exists.
David Brazdil528e0472022-10-10 15:06:02 +0100270 #[allow(dead_code)]
271 lazy_service_guard: LazyServiceGuard,
272}
273
274impl GlobalVmContext {
David Brazdil73988ea2022-11-11 15:10:32 +0000275 fn create(cid: Arc<Cid>) -> Strong<dyn IGlobalVmContext> {
David Brazdil528e0472022-10-10 15:06:02 +0100276 let binder = GlobalVmContext { cid, ..Default::default() };
277 BnGlobalVmContext::new_binder(binder, BinderFeatures::default())
278 }
279}
280
281impl Interface for GlobalVmContext {}
282
283impl IGlobalVmContext for GlobalVmContext {
284 fn getCid(&self) -> binder::Result<i32> {
David Brazdil73988ea2022-11-11 15:10:32 +0000285 Ok(*self.cid as i32)
David Brazdil528e0472022-10-10 15:06:02 +0100286 }
287}
288
289/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000290#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000291pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900292 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000293}
294
Shikha Panward8e35422021-10-11 13:51:27 +0000295impl Interface for VirtualizationService {
296 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
297 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
298 let state = &mut *self.state.lock().unwrap();
299 let vms = state.vms();
300 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
301 for vm in vms {
302 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
303 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
304 .or(Err(StatusCode::UNKNOWN_ERROR))?;
305 writeln!(file, "\tPayload state {:?}", vm.payload_state())
306 .or(Err(StatusCode::UNKNOWN_ERROR))?;
307 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
308 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
309 .or(Err(StatusCode::UNKNOWN_ERROR))?;
310 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
311 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000312 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
313 .or(Err(StatusCode::UNKNOWN_ERROR))?;
314 }
315 Ok(())
316 }
317}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000318
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000319impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000320 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
321 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000322 ///
323 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000324 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000325 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000326 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900327 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000328 log_fd: Option<&ParcelFileDescriptor>,
329 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000330 let mut is_protected = false;
331 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000332 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000333 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000334 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000335
Andrew Walbrandff3b942021-06-09 15:20:36 +0000336 /// Initialise an empty partition image of the given size to be used as a writable partition.
337 fn initializeWritablePartition(
338 &self,
339 image_fd: &ParcelFileDescriptor,
340 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900341 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000342 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900343 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000344 let size = size.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000345 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000346 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100347 Some(format!("Invalid size {}: {:?}", size, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000348 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000349 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000350 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900351 // initialize the file. Any data in the file will be erased.
352 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000353 Status::new_service_specific_error_str(
354 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100355 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900356 )
357 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900358 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000359 Status::new_service_specific_error_str(
360 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100361 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000362 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000363 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000364
Jiyong Park9dd389e2021-08-23 20:42:59 +0900365 match partition_type {
366 PartitionType::RAW => Ok(()),
367 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000368 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900369 _ => Err(Error::new(
370 ErrorKind::Unsupported,
371 format!("Unsupported partition type {:?}", partition_type),
372 )),
373 }
374 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000375 Status::new_service_specific_error_str(
376 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100377 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900378 )
379 })?;
380
Andrew Walbrandff3b942021-06-09 15:20:36 +0000381 Ok(())
382 }
383
Jiyong Park0a248432021-08-20 23:32:39 +0900384 /// Creates or update the idsig file by digesting the input APK file.
385 fn createOrUpdateIdsigFile(
386 &self,
387 input_fd: &ParcelFileDescriptor,
388 idsig_fd: &ParcelFileDescriptor,
389 ) -> binder::Result<()> {
390 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
391 // idsig_fd is different from APK digest in input_fd
392
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900393 check_manage_access()?;
394
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000395 create_or_update_idsig_file(input_fd, idsig_fd)
396 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900397 Ok(())
398 }
399
Andrew Walbran320b5602021-03-04 16:11:12 +0000400 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
401 /// and as such is only permitted from the shell user.
402 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000403 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000404
405 let state = &mut *self.state.lock().unwrap();
406 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000407 let cids = vms
408 .into_iter()
409 .map(|vm| VirtualMachineDebugInfo {
410 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000411 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000412 requesterUid: vm.requester_uid as i32,
Andrew Walbran02034492021-04-13 15:05:07 +0000413 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000414 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000415 })
416 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000417 Ok(cids)
418 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000419
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000420 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
421 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000422 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000423 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000424
David Brazdil3c2ddef2021-03-18 13:09:57 +0000425 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000426 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000427 Ok(())
428 }
429
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000430 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
431 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
432 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000433 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000434 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000435
436 let state = &mut *self.state.lock().unwrap();
437 Ok(state.debug_drop_vm(cid))
438 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000439}
440
Shikha Panwar7afc1392022-03-24 08:54:43 +0000441fn handle_stream_connection_tombstoned() -> Result<()> {
David Brazdil73988ea2022-11-11 15:10:32 +0000442 // Should not listen for tombstones on a guest VM's port.
443 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
Shikha Panwar7afc1392022-03-24 08:54:43 +0000444 let listener =
David Brazdil73988ea2022-11-11 15:10:32 +0000445 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
Shikha Panwar7afc1392022-03-24 08:54:43 +0000446 for incoming_stream in listener.incoming() {
447 let mut incoming_stream = match incoming_stream {
448 Err(e) => {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100449 warn!("invalid incoming connection: {:?}", e);
Shikha Panwar7afc1392022-03-24 08:54:43 +0000450 continue;
451 }
452 Ok(s) => s,
453 };
454 std::thread::spawn(move || {
455 if let Err(e) = handle_tombstone(&mut incoming_stream) {
456 error!("Failed to write tombstone- {:?}", e);
457 }
458 });
459 }
460 Ok(())
461}
462
463fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
Andrew Walbranadd38cb2022-10-06 17:01:03 +0000464 if let Ok(addr) = stream.peer_addr() {
Shikha Panwar7afc1392022-03-24 08:54:43 +0000465 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
466 }
467 let tb_connection =
468 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
469 .context("Failed to connect to tombstoned")?;
470 let mut text_output = tb_connection
471 .text_output
472 .as_ref()
473 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
474 let mut num_bytes_read = 0;
475 loop {
476 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
477 let n = stream
478 .read(&mut chunk_recv)
479 .context("Failed to read tombstone data from Vsock stream")?;
480 if n == 0 {
481 break;
482 }
483 num_bytes_read += n;
484 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
485 }
486 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
487 tb_connection.notify_completion()?;
488 Ok(())
489}
490
Jiyong Park8611a6c2021-07-09 18:17:44 +0900491impl VirtualizationService {
492 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000493 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900494 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000495
David Brazdil8cf8f482022-11-23 14:21:26 +0000496 fn create_vm_context(&self) -> Result<(VmContext, Cid)> {
497 const NUM_ATTEMPTS: usize = 5;
498
499 for _ in 0..NUM_ATTEMPTS {
David Brazdil49f96f52022-12-16 21:29:13 +0000500 let global_context = GLOBAL_SERVICE.allocateGlobalVmContext()?;
David Brazdil8cf8f482022-11-23 14:21:26 +0000501 let cid = global_context.getCid()? as Cid;
502 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
503
504 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000505 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000506 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000507 Ok(vm_server) => {
508 vm_server.start();
509 return Ok((VmContext::new(global_context, vm_server), cid));
510 }
511 Err(err) => {
512 warn!("Could not start RpcServer on port {}: {}", port, err);
513 }
514 }
515 }
516 bail!("Too many attempts to create VM context failed.");
517 }
518
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000519 fn create_vm_internal(
520 &self,
521 config: &VirtualMachineConfig,
522 console_fd: Option<&ParcelFileDescriptor>,
523 log_fd: Option<&ParcelFileDescriptor>,
524 is_protected: &mut bool,
525 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
526 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900527
Alan Stokes7bc146c2022-10-20 17:10:32 +0100528 let is_custom = match config {
529 VirtualMachineConfig::RawConfig(_) => true,
530 VirtualMachineConfig::AppConfig(config) => {
531 // Some features are reserved for platform apps only, even when using
532 // VirtualMachineAppConfig:
533 // - controlling CPUs;
534 // - specifying a config file in the APK.
535 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900536 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100537 };
538 if is_custom {
539 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900540 }
541
David Brazdil8cf8f482022-11-23 14:21:26 +0000542 let (vm_context, cid) = self.create_vm_context().map_err(|e| {
543 error!("Failed to create VmContext: {:?}", e);
544 Status::new_service_specific_error_str(
545 -1,
546 Some(format!("Failed to create VmContext: {:?}", e)),
547 )
548 })?;
David Brazdil528e0472022-10-10 15:06:02 +0100549
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000550 let state = &mut *self.state.lock().unwrap();
551 let console_fd = console_fd.map(clone_file).transpose()?;
552 let log_fd = log_fd.map(clone_file).transpose()?;
553 let requester_uid = ThreadState::get_calling_uid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000554 let requester_debug_pid = ThreadState::get_calling_pid();
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000555
556 // Counter to generate unique IDs for temporary image files.
557 let mut next_temporary_image_id = 0;
558 // Files which are referred to from composite images. These must be mapped to the crosvm
559 // child process, and not closed before it is started.
560 let mut indirect_files = vec![];
561
562 // Make directory for temporary files.
563 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
564 create_dir(&temporary_directory).map_err(|e| {
565 // At this point, we do not know the protected status of Vm
566 // setting it to false, though this may not be correct.
567 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100568 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000569 temporary_directory, e
570 );
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000571 Status::new_service_specific_error_str(
572 -1,
573 Some(format!(
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100574 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000575 temporary_directory, e
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000576 )),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000577 )
578 })?;
579
Alan Stokes7bc146c2022-10-20 17:10:32 +0100580 let (is_app_config, config) = match config {
581 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
582 VirtualMachineConfig::AppConfig(config) => {
583 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000584 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100585 let message = format!("Failed to load app config: {:?}", e);
586 error!("{}", message);
587 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100588 })?;
589 (true, BorrowedOrOwned::Owned(config))
590 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000591 };
592 let config = config.as_ref();
593 *is_protected = config.protectedVm;
594
595 // Check if partition images are labeled incorrectly. This is to prevent random images
596 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100597 // being loaded in a pVM. This applies to everything in the raw config, and everything but
598 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000599 config
600 .disks
601 .iter()
602 .flat_map(|disk| disk.partitions.iter())
603 .filter(|partition| {
604 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100605 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000606 } else {
607 true // all partitions are checked
608 }
609 })
610 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100611 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000612
613 let zero_filler_path = temporary_directory.join("zero.img");
614 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100615 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000616 Status::new_service_specific_error_str(
617 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100618 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000619 )
620 })?;
621
622 // Assemble disk images if needed.
623 let disks = config
624 .disks
625 .iter()
626 .map(|disk| {
627 assemble_disk_image(
628 disk,
629 &zero_filler_path,
630 &temporary_directory,
631 &mut next_temporary_image_id,
632 &mut indirect_files,
633 )
634 })
635 .collect::<Result<Vec<DiskFile>, _>>()?;
636
Jiyong Parke558ab12022-07-07 20:18:55 +0900637 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
638 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900639 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900640 // will be sent back to the client (i.e. the VM owner) for readout.
641 let ramdump_path = temporary_directory.join("ramdump");
642 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100643 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000644 Status::new_service_specific_error_str(
645 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100646 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900647 )
648 })?;
649
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000650 // Actually start the VM.
651 let crosvm_config = CrosvmConfig {
652 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000653 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000654 bootloader: maybe_clone_file(&config.bootloader)?,
655 kernel: maybe_clone_file(&config.kernel)?,
656 initrd: maybe_clone_file(&config.initrd)?,
657 disks,
658 params: config.params.to_owned(),
659 protected: *is_protected,
660 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
661 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900662 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000663 console_fd,
664 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900665 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000666 indirect_files,
667 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900668 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000669 };
670 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100671 VmInstance::new(
672 crosvm_config,
673 temporary_directory,
674 requester_uid,
675 requester_debug_pid,
676 vm_context,
677 )
678 .map_err(|e| {
679 error!("Failed to create VM with config {:?}: {:?}", config, e);
680 Status::new_service_specific_error_str(
681 -1,
682 Some(format!("Failed to create VM: {:?}", e)),
683 )
684 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000685 );
686 state.add_vm(Arc::downgrade(&instance));
687 Ok(VirtualMachine::create(instance))
688 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900689}
690
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000691fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900692 let file = OpenOptions::new()
693 .create_new(true)
694 .read(true)
695 .write(true)
696 .open(zero_filler_path)
697 .with_context(|| "Failed to create zero.img")?;
698 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000699 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900700}
701
Jiyong Park9dd389e2021-08-23 20:42:59 +0900702fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
703 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
704 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
705 part.flush()
706}
707
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000708fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
709 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
710 part.flush()
711}
712
Jiyong Parke558ab12022-07-07 20:18:55 +0900713fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800714 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900715}
716
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000717/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
718///
719/// This may involve assembling a composite disk from a set of partition images.
720fn assemble_disk_image(
721 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900722 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000723 temporary_directory: &Path,
724 next_temporary_image_id: &mut u64,
725 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000726) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000727 let image = if !disk.partitions.is_empty() {
728 if disk.image.is_some() {
729 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000730 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000731 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000732 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000733 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000734 }
735
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000736 let composite_image_filenames =
737 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
738 let (image, partition_files) = make_composite_image(
739 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900740 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000741 &composite_image_filenames.composite,
742 &composite_image_filenames.header,
743 &composite_image_filenames.footer,
744 )
745 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100746 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000747 Status::new_service_specific_error_str(
748 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100749 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000750 )
751 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000752
753 // Pass the file descriptors for the various partition files to crosvm when it
754 // is run.
755 indirect_files.extend(partition_files);
756
757 image
758 } else if let Some(image) = &disk.image {
759 clone_file(image)?
760 } else {
761 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000762 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000763 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000764 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000765 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000766 };
767
768 Ok(DiskFile { image, writable: disk.writable })
769}
770
Jooyung Han21e9b922021-06-26 04:14:16 +0900771fn load_app_config(
772 config: &VirtualMachineAppConfig,
773 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900774) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000775 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
776 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900777 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900778
Shikha Panwar22e70452022-10-10 18:32:55 +0000779 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
780 Some(clone_file(file)?)
781 } else {
782 None
783 };
784
Alan Stokes0d1ef782022-09-27 13:46:35 +0100785 let vm_payload_config = match &config.payload {
786 Payload::ConfigPath(config_path) => {
787 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
788 .with_context(|| format!("Couldn't read config from {}", config_path))?
789 }
790 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
791 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900792
Alan Stokes0d1ef782022-09-27 13:46:35 +0100793 // For now, the only supported OS is Microdroid
794 let os_name = vm_payload_config.os.name.as_str();
795 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000796 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900797 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000798
799 // It is safe to construct a filename based on the os_name because we've already checked that it
800 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900801 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
802 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000803 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900804
Andrew Walbrancc045902021-07-27 16:06:17 +0000805 if config.memoryMib > 0 {
806 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000807 }
808
Seungjae Yoo62085c02022-08-12 04:44:52 +0000809 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000810 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900811 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900812 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900813
Shikha Panwar22e70452022-10-10 18:32:55 +0000814 // Microdroid takes additional init ramdisk & (optionally) storage image
815 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
816
817 // Include Microdroid payload disk (contains apks, idsigs) in vm config
818 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100819 config,
820 temporary_directory,
821 apk_file,
822 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100823 &vm_payload_config,
824 &mut vm_config,
825 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900826
Andrew Walbrancc0db522021-07-12 17:03:42 +0000827 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900828}
829
Alan Stokes0d1ef782022-09-27 13:46:35 +0100830fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
831 let mut apk_zip = ZipArchive::new(apk_file)?;
832 let config_file = apk_zip.by_name(config_path)?;
833 Ok(serde_json::from_reader(config_file)?)
834}
835
836fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
837 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
838 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
839 // payload config that we send it via the metadata file.
Alan Stokes52d3c722022-10-04 17:27:13 +0100840 let task =
841 Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
Alan Stokes0d1ef782022-09-27 13:46:35 +0100842 VmPayloadConfig {
843 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
844 task: Some(task),
845 apexes: vec![],
846 extra_apks: vec![],
847 prefer_staged: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100848 export_tombstones: false,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100849 enable_authfs: false,
850 }
851}
852
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000853/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000854fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000855 temporary_directory: &Path,
856 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000857) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000858 let id = *next_temporary_image_id;
859 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000860 CompositeImageFilenames {
861 composite: temporary_directory.join(format!("composite-{}.img", id)),
862 header: temporary_directory.join(format!("composite-{}-header.img", id)),
863 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
864 }
865}
866
867/// Filenames for a composite disk image, including header and footer partitions.
868#[derive(Clone, Debug, Eq, PartialEq)]
869struct CompositeImageFilenames {
870 /// The composite disk image itself.
871 composite: PathBuf,
872 /// The header partition image.
873 header: PathBuf,
874 /// The footer partition image.
875 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000876}
877
Jiyong Park753553b2021-07-12 21:21:09 +0900878/// Checks whether the caller has a specific permission
879fn check_permission(perm: &str) -> binder::Result<()> {
880 let calling_pid = ThreadState::get_calling_pid();
881 let calling_uid = ThreadState::get_calling_uid();
882 // Root can do anything
883 if calling_uid == 0 {
884 return Ok(());
885 }
886 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
887 binder::get_interface("permission")?;
888 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000889 Ok(())
890 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000891 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900892 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000893 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900894 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000895 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000896}
897
Jiyong Park753553b2021-07-12 21:21:09 +0900898/// Check whether the caller of the current Binder method is allowed to call debug methods.
899fn check_debug_access() -> binder::Result<()> {
900 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
901}
902
903/// Check whether the caller of the current Binder method is allowed to manage VMs
904fn check_manage_access() -> binder::Result<()> {
905 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
906}
907
Inseob Kim1119d702022-05-02 18:01:58 +0900908/// Check whether the caller of the current Binder method is allowed to create custom VMs
909fn check_use_custom_virtual_machine() -> binder::Result<()> {
910 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
911}
912
Jiyong Park029977d2021-11-24 21:56:49 +0900913/// Check if a partition has selinux labels that are not allowed
914fn check_label_for_partition(partition: &Partition) -> Result<()> {
915 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100916 check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
917}
918
919// Return whether a partition is exempt from selinux label checks, because we know that it does
920// not contain code and is likely to be generated in an app-writable directory.
921fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000922 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100923 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000924 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100925 || label == "microdroid-apk-idsig"
926 || label == "payload-metadata"
927 || label.starts_with("extra-idsig-")
928}
929
930fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
931 // We only want to allow code in a VM payload to be sourced from places that apps, and the
932 // system, do not have write access to.
933 // (Note that sepolicy must also grant read access for these types to both virtualization
934 // service and crosvm.)
935 // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
936 // user devices (W^X).
937 match ctx.selinux_type()? {
938 | "system_file" // immutable dm-verity protected partition
939 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000940 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100941 | "shell_data_file" // test files created via adb shell
942 => Ok(()),
943 _ => bail!("Label {} is not allowed", ctx),
Jiyong Park029977d2021-11-24 21:56:49 +0900944 }
945}
946
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000947/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
948#[derive(Debug)]
949struct VirtualMachine {
950 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100951 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800952 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100953 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000954}
955
956impl VirtualMachine {
957 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100958 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000959 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000960 }
961}
962
963impl Interface for VirtualMachine {}
964
965impl IVirtualMachine for VirtualMachine {
966 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900967 // Don't check permission. The owner of the VM might have passed this binder object to
968 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000969 Ok(self.instance.cid as i32)
970 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000971
Andrew Walbran6b650662021-09-07 13:13:23 +0000972 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900973 // Don't check permission. The owner of the VM might have passed this binder object to
974 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000975 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000976 }
977
978 fn registerCallback(
979 &self,
980 callback: &Strong<dyn IVirtualMachineCallback>,
981 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900982 // Don't check permission. The owner of the VM might have passed this binder object to
983 // others.
984 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000985 // TODO: Should this give an error if the VM is already dead?
986 self.instance.callbacks.add(callback.clone());
987 Ok(())
988 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000989
Andrew Walbranf8d94112021-09-07 11:45:36 +0000990 fn start(&self) -> binder::Result<()> {
991 self.instance.start().map_err(|e| {
992 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000993 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000994 })
995 }
996
Inseob Kima446f802022-07-11 19:46:37 +0900997 fn stop(&self) -> binder::Result<()> {
998 self.instance.kill().map_err(|e| {
999 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001000 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +09001001 })
1002 }
1003
Keir Frasercdd4b112022-11-24 14:02:25 +00001004 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
1005 self.instance.trim_memory(level).map_err(|e| {
1006 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
1007 Status::new_service_specific_error_str(-1, Some(e.to_string()))
1008 })
1009 }
1010
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001011 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001012 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001013 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001014 }
Alan Stokes10c47672022-12-13 17:17:08 +00001015 let port = port as u32;
1016 if port < 1024 {
1017 return Err(Status::new_service_specific_error_str(
1018 -1,
1019 Some(format!("Can't connect to privileged port {port}")),
1020 ));
1021 }
1022 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
1023 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
1024 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001025 Ok(vsock_stream_to_pfd(stream))
1026 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001027}
1028
1029impl Drop for VirtualMachine {
1030 fn drop(&mut self) {
1031 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001032 if let Err(e) = self.instance.kill() {
1033 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1034 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001035 }
1036}
1037
1038/// A set of Binders to be called back in response to various events on the VM, such as when it
1039/// dies.
1040#[derive(Debug, Default)]
1041pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1042
1043impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001044 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001045 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001046 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001047 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001048 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001049 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001050 }
1051 }
1052 }
1053
Inseob Kim14cb8692021-08-31 21:50:39 +09001054 /// Call all registered callbacks to notify that the payload is ready to serve.
1055 pub fn notify_payload_ready(&self, cid: Cid) {
1056 let callbacks = &*self.0.lock().unwrap();
1057 for callback in callbacks {
1058 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001059 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001060 }
1061 }
1062 }
1063
Inseob Kim2444af92021-08-31 01:22:50 +09001064 /// Call all registered callbacks to notify that the payload has finished.
1065 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1066 let callbacks = &*self.0.lock().unwrap();
1067 for callback in callbacks {
1068 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001069 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001070 }
1071 }
1072 }
1073
Jooyung Handd0a1732021-11-23 15:26:20 +09001074 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001075 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001076 let callbacks = &*self.0.lock().unwrap();
1077 for callback in callbacks {
1078 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001079 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001080 }
1081 }
1082 }
1083
Andrew Walbrandae07162021-03-12 17:05:20 +00001084 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001085 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001086 let callbacks = &*self.0.lock().unwrap();
1087 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001088 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001089 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001090 }
1091 }
1092 }
1093
1094 /// Add a new callback to the set.
1095 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1096 self.0.lock().unwrap().push(callback);
1097 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001098}
1099
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001100/// The mutable state of the VirtualizationService. There should only be one instance of this
1101/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001102#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001103struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001104 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1105 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1106 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1107 /// from the list opportunistically the next time `add_vm` is called.
1108 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +00001109
1110 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
1111 /// This is only used for debugging purposes.
1112 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +00001113}
1114
1115impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001116 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001117 fn vms(&self) -> Vec<Arc<VmInstance>> {
1118 // Attempt to upgrade the weak pointers to strong pointers.
1119 self.vms.iter().filter_map(Weak::upgrade).collect()
1120 }
1121
1122 /// Add a new VM to the list.
1123 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1124 // Garbage collect any entries from the stored list which no longer exist.
1125 self.vms.retain(|vm| vm.strong_count() > 0);
1126
1127 // Actually add the new VM.
1128 self.vms.push(vm);
1129 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001130
Jiyong Park8611a6c2021-07-09 18:17:44 +09001131 /// Get a VM that corresponds to the given cid
1132 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1133 self.vms().into_iter().find(|vm| vm.cid == cid)
1134 }
1135
David Brazdil3c2ddef2021-03-18 13:09:57 +00001136 /// Store a strong VM reference.
1137 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
1138 self.debug_held_vms.push(vm);
1139 }
1140
1141 /// Retrieve and remove a strong VM reference.
1142 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
1143 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +01001144 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +01001145 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +00001146 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001147}
1148
Andrew Walbran6b650662021-09-07 13:13:23 +00001149/// Gets the `VirtualMachineState` of the given `VmInstance`.
1150fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001151 match &*instance.vm_state.lock().unwrap() {
1152 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1153 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001154 PayloadState::Starting => VirtualMachineState::STARTING,
1155 PayloadState::Started => VirtualMachineState::STARTED,
1156 PayloadState::Ready => VirtualMachineState::READY,
1157 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001158 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001159 },
1160 VmState::Dead => VirtualMachineState::DEAD,
1161 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001162 }
1163}
1164
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001165/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +00001166pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +00001167 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001168 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +00001169 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001170 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +00001171 )
1172 })
1173}
1174
Andrew Walbrand3a84182021-09-07 14:48:52 +00001175/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1176fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1177 file.as_ref().map(clone_file).transpose()
1178}
1179
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001180/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1181fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1182 // SAFETY: ownership is transferred from stream to f
1183 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1184 ParcelFileDescriptor::new(f)
1185}
1186
Jiyong Parkdcf17412022-02-08 15:07:23 +09001187/// Parses the platform version requirement string.
1188fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1189 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001190 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001191 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001192 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001193 )
1194 })
1195}
1196
Jooyung Han35edb8f2021-07-01 16:17:16 +09001197/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1198/// it doesn't require that T implements Clone.
1199enum BorrowedOrOwned<'a, T> {
1200 Borrowed(&'a T),
1201 Owned(T),
1202}
1203
1204impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1205 fn as_ref(&self) -> &T {
1206 match self {
1207 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001208 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001209 }
1210 }
1211}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001212
1213/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1214#[derive(Debug, Default)]
1215struct VirtualMachineService {
1216 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001217 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001218}
1219
1220impl Interface for VirtualMachineService {}
1221
1222impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001223 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1224 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001225 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001226 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001227 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1228 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1229 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001230 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001231
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001232 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1233 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001234 Ok(())
1235 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001236 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001237 Err(Status::new_service_specific_error_str(
1238 -1,
1239 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001240 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001241 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001242 }
Inseob Kim2444af92021-08-31 01:22:50 +09001243
Inseob Kimc7d28c72021-10-25 14:28:10 +00001244 fn notifyPayloadReady(&self) -> binder::Result<()> {
1245 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001246 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001247 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001248 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1249 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1250 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001251 vm.callbacks.notify_payload_ready(cid);
1252 Ok(())
1253 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001254 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001255 Err(Status::new_service_specific_error_str(
1256 -1,
1257 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001258 ))
1259 }
1260 }
1261
Inseob Kimc7d28c72021-10-25 14:28:10 +00001262 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1263 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001264 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001265 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001266 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1267 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1268 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001269 vm.callbacks.notify_payload_finished(cid, exit_code);
1270 Ok(())
1271 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001272 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001273 Err(Status::new_service_specific_error_str(
1274 -1,
1275 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001276 ))
1277 }
1278 }
1279
Alan Stokes2bead0d2022-09-05 16:58:34 +01001280 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001281 let cid = self.cid;
1282 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001283 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001284 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1285 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1286 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001287 vm.callbacks.notify_error(cid, error_code, message);
1288 Ok(())
1289 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001290 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001291 Err(Status::new_service_specific_error_str(
1292 -1,
1293 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001294 ))
1295 }
1296 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001297}
1298
1299impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001300 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001301 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001302 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001303 BinderFeatures::default(),
1304 )
1305 }
1306}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001307
1308#[cfg(test)]
1309mod tests {
1310 use super::*;
1311
1312 #[test]
1313 fn test_is_allowed_label_for_partition() -> Result<()> {
1314 let expected_results = vec![
1315 ("u:object_r:system_file:s0", true),
1316 ("u:object_r:apk_data_file:s0", true),
1317 ("u:object_r:app_data_file:s0", false),
1318 ("u:object_r:app_data_file:s0:c512,c768", false),
1319 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1320 ("invalid", false),
1321 ("user:role:apk_data_file:severity:categories", true),
1322 ("user:role:apk_data_file:severity:categories:extraneous", false),
1323 ];
1324
1325 for (label, expected_valid) in expected_results {
1326 let context = SeContext::new(label)?;
1327 let result = check_label_is_allowed(&context);
1328 if expected_valid {
1329 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1330 } else if result.is_ok() {
1331 bail!("Expected label {} to be disallowed", label);
1332 }
1333 }
1334 Ok(())
1335 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001336
1337 #[test]
1338 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1339 let apk = tempfile::tempfile().unwrap();
1340 let idsig = tempfile::tempfile().unwrap();
1341
1342 let ret = create_or_update_idsig_file(
1343 &ParcelFileDescriptor::new(apk),
1344 &ParcelFileDescriptor::new(idsig),
1345 );
1346 assert!(ret.is_err(), "should fail");
1347 Ok(())
1348 }
1349
1350 #[test]
1351 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1352 let tmp_dir = tempfile::TempDir::new().unwrap();
1353 let apk = File::open(tmp_dir.path()).unwrap();
1354 let idsig = tempfile::tempfile().unwrap();
1355
1356 let ret = create_or_update_idsig_file(
1357 &ParcelFileDescriptor::new(apk),
1358 &ParcelFileDescriptor::new(idsig),
1359 );
1360 assert!(ret.is_err(), "should fail");
1361 Ok(())
1362 }
1363
1364 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1365 /// on ext4 filesystem is passed.
1366 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1367 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1368 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1369 #[test]
1370 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1371 // APEXes are backed by the ext4.
1372 let apk = File::open("/apex/com.android.virt/").unwrap();
1373 let idsig = tempfile::tempfile().unwrap();
1374
1375 let ret = create_or_update_idsig_file(
1376 &ParcelFileDescriptor::new(apk),
1377 &ParcelFileDescriptor::new(idsig),
1378 );
1379 assert!(ret.is_err(), "should fail");
1380 Ok(())
1381 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001382}