blob: 413525331e27df1a5d9a6ba4725a64e4fdb9075a [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
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000017use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000018use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Andrew Walbrancc0db522021-07-12 17:03:42 +000019use crate::payload::add_microdroid_images;
Jiyong Parkd50a0242021-09-16 21:00:14 +090020use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID};
Jiyong Park029977d2021-11-24 21:56:49 +090021use crate::selinux::{SeContext, getfilecon};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010022use ::binder::unstable_api::AsNative;
Jiyong Park753553b2021-07-12 21:21:09 +090023use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000025 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000026 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010027 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000028 IVirtualMachineCallback::IVirtualMachineCallback,
29 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090030 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 PartitionType::PartitionType,
Jooyung Han21e9b922021-06-26 04:14:16 +090032 VirtualMachineAppConfig::VirtualMachineAppConfig,
33 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090035 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090037};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000038use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000039 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010040 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000041};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
43 IVirtualMachineService::{
44 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
Shikha Panwar7afc1392022-03-24 08:54:43 +000045 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010046 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090047};
Jiyong Parkd50a0242021-09-16 21:00:14 +090048use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010049use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000050use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010051use idsig::{HashAlgorithm, V4Signature};
Andrew Walbranf6d600f2022-02-03 14:42:39 +000052use log::{debug, error, info, warn, trace};
Andrew Walbrancc0db522021-07-12 17:03:42 +000053use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090054use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090055use semver::VersionReq;
Treehugger Robot3ffa8322021-11-22 12:06:47 +000056use statslog_virtualization_rust::vm_creation_requested::{stats_write, Hypervisor};
Andrew Walbrandff3b942021-06-09 15:20:36 +000057use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000058use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010059use std::fs::{create_dir, File, OpenOptions};
Shikha Panwar7afc1392022-03-24 08:54:43 +000060use std::io::{Error, ErrorKind, Write, Read};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000061use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000062use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000063use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000064use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000065use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000066use std::sync::{Arc, Mutex, Weak};
Shikha Panwar7afc1392022-03-24 08:54:43 +000067use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrancc0db522021-07-12 17:03:42 +000068use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090069use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090070use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071
Andrew Walbranf6bf6862021-05-21 12:41:13 +000072pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000075pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076
Jiyong Park8611a6c2021-07-09 18:17:44 +090077/// The CID representing the host VM
78const VMADDR_CID_HOST: u32 = 2;
79
Jooyung Han95884632021-07-06 22:27:54 +090080/// The size of zero.img.
81/// Gaps in composite disk images are filled with a shared zero.img.
82const ZERO_FILLER_SIZE: u64 = 4096;
83
Jiyong Park9dd389e2021-08-23 20:42:59 +090084/// Magic string for the instance image
85const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
86
87/// Version of the instance image format
88const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
89
Shikha Panwar7afc1392022-03-24 08:54:43 +000090const CHUNK_RECV_MAX_LEN: usize = 1024;
91
Andrew Walbranf6bf6862021-05-21 12:41:13 +000092/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090093#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000094pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090095 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096}
97
Shikha Panward8e35422021-10-11 13:51:27 +000098impl Interface for VirtualizationService {
99 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
100 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
101 let state = &mut *self.state.lock().unwrap();
102 let vms = state.vms();
103 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
104 for vm in vms {
105 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
107 .or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\tPayload state {:?}", vm.payload_state())
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
116 .or(Err(StatusCode::UNKNOWN_ERROR))?;
117 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
118 .or(Err(StatusCode::UNKNOWN_ERROR))?;
119 }
120 Ok(())
121 }
122}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000124impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000125 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
126 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000127 ///
128 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000129 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000130 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000131 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900132 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000133 log_fd: Option<&ParcelFileDescriptor>,
134 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000135 let mut is_protected = false;
136 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
137 match ret {
138 Ok(_) => {
139 let ok_status = Status::ok();
140 write_vm_creation_stats(
141 is_protected,
142 /*creation_succeeded*/ true,
143 ok_status.exception_code() as i32,
144 );
145 }
146 Err(ref e) => {
147 write_vm_creation_stats(
148 is_protected,
149 /*creation_succeeded*/ false,
150 e.exception_code() as i32,
151 );
152 }
153 }
154 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000155 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000156
Andrew Walbrandff3b942021-06-09 15:20:36 +0000157 /// Initialise an empty partition image of the given size to be used as a writable partition.
158 fn initializeWritablePartition(
159 &self,
160 image_fd: &ParcelFileDescriptor,
161 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900162 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000163 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900164 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000165 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000166 new_binder_exception(
167 ExceptionCode::ILLEGAL_ARGUMENT,
168 format!("Invalid size {}: {}", size, e),
169 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000170 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000171 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900172 // initialize the file. Any data in the file will be erased.
173 image.set_len(0).map_err(|e| {
174 new_binder_exception(
175 ExceptionCode::SERVICE_SPECIFIC,
176 format!("Failed to reset a file: {}", e),
177 )
178 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900179 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000180 new_binder_exception(
181 ExceptionCode::SERVICE_SPECIFIC,
182 format!("Failed to create QCOW2 image: {}", e),
183 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000184 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000185
Jiyong Park9dd389e2021-08-23 20:42:59 +0900186 match partition_type {
187 PartitionType::RAW => Ok(()),
188 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
189 _ => Err(Error::new(
190 ErrorKind::Unsupported,
191 format!("Unsupported partition type {:?}", partition_type),
192 )),
193 }
194 .map_err(|e| {
195 new_binder_exception(
196 ExceptionCode::SERVICE_SPECIFIC,
197 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
198 )
199 })?;
200
Andrew Walbrandff3b942021-06-09 15:20:36 +0000201 Ok(())
202 }
203
Jiyong Park0a248432021-08-20 23:32:39 +0900204 /// Creates or update the idsig file by digesting the input APK file.
205 fn createOrUpdateIdsigFile(
206 &self,
207 input_fd: &ParcelFileDescriptor,
208 idsig_fd: &ParcelFileDescriptor,
209 ) -> binder::Result<()> {
210 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
211 // idsig_fd is different from APK digest in input_fd
212
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900213 check_manage_access()?;
214
Jiyong Park0a248432021-08-20 23:32:39 +0900215 let mut input = clone_file(input_fd)?;
216 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
217
218 let mut output = clone_file(idsig_fd)?;
219 output.set_len(0).unwrap();
220 sig.write_into(&mut output).unwrap();
221 Ok(())
222 }
223
Andrew Walbran320b5602021-03-04 16:11:12 +0000224 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
225 /// and as such is only permitted from the shell user.
226 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000227 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000228
229 let state = &mut *self.state.lock().unwrap();
230 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000231 let cids = vms
232 .into_iter()
233 .map(|vm| VirtualMachineDebugInfo {
234 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000235 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000236 requesterUid: vm.requester_uid as i32,
237 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000238 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000239 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000240 })
241 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000242 Ok(cids)
243 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000244
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000245 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
246 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000247 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000248 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000249
David Brazdil3c2ddef2021-03-18 13:09:57 +0000250 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000251 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000252 Ok(())
253 }
254
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000255 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
256 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
257 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000258 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000259 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000260
261 let state = &mut *self.state.lock().unwrap();
262 Ok(state.debug_drop_vm(cid))
263 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000264}
265
Shikha Panwar7afc1392022-03-24 08:54:43 +0000266fn handle_stream_connection_tombstoned() -> Result<()> {
267 let listener =
268 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
269 info!("Listening to tombstones from guests ...");
270 for incoming_stream in listener.incoming() {
271 let mut incoming_stream = match incoming_stream {
272 Err(e) => {
273 warn!("invalid incoming connection: {}", e);
274 continue;
275 }
276 Ok(s) => s,
277 };
278 std::thread::spawn(move || {
279 if let Err(e) = handle_tombstone(&mut incoming_stream) {
280 error!("Failed to write tombstone- {:?}", e);
281 }
282 });
283 }
284 Ok(())
285}
286
287fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
288 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
289 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
290 }
291 let tb_connection =
292 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
293 .context("Failed to connect to tombstoned")?;
294 let mut text_output = tb_connection
295 .text_output
296 .as_ref()
297 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
298 let mut num_bytes_read = 0;
299 loop {
300 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
301 let n = stream
302 .read(&mut chunk_recv)
303 .context("Failed to read tombstone data from Vsock stream")?;
304 if n == 0 {
305 break;
306 }
307 num_bytes_read += n;
308 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
309 }
310 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
311 tb_connection.notify_completion()?;
312 Ok(())
313}
314
Jiyong Park8611a6c2021-07-09 18:17:44 +0900315impl VirtualizationService {
316 pub fn init() -> VirtualizationService {
317 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900318
319 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900320 let state = service.state.clone(); // reference to state (not the state itself) is copied
321 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900322 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900323 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900324
Shikha Panwar7afc1392022-03-24 08:54:43 +0000325 std::thread::spawn(|| {
326 if let Err(e) = handle_stream_connection_tombstoned() {
327 warn!("Error receiving tombstone from guest or writing them. Error: {}", e);
328 }
329 });
330
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900331 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000332 // reference to state (not the state itself) is copied
333 let mut state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900334 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000335 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
336
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900337 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000338 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
339 // lifetime of the state, with context taking the pointer value above (so a properly
340 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900341 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000342 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
343 Some(VirtualMachineService::factory),
344 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900345 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900346 )
347 };
348 if retval {
349 debug!("RPC server has shut down gracefully");
350 } else {
351 bail!("Premature termination of RPC server");
352 }
353
354 Ok(retval)
355 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900356 service
357 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000358
359 fn create_vm_internal(
360 &self,
361 config: &VirtualMachineConfig,
362 console_fd: Option<&ParcelFileDescriptor>,
363 log_fd: Option<&ParcelFileDescriptor>,
364 is_protected: &mut bool,
365 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
366 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900367
368 if let VirtualMachineConfig::RawConfig(config) = config {
369 if config.protectedVm {
370 check_use_custom_virtual_machine()?;
371 }
372 }
373
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000374 let state = &mut *self.state.lock().unwrap();
375 let console_fd = console_fd.map(clone_file).transpose()?;
376 let log_fd = log_fd.map(clone_file).transpose()?;
377 let requester_uid = ThreadState::get_calling_uid();
378 let requester_sid = get_calling_sid()?;
379 let requester_debug_pid = ThreadState::get_calling_pid();
380 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
381
382 // Counter to generate unique IDs for temporary image files.
383 let mut next_temporary_image_id = 0;
384 // Files which are referred to from composite images. These must be mapped to the crosvm
385 // child process, and not closed before it is started.
386 let mut indirect_files = vec![];
387
388 // Make directory for temporary files.
389 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
390 create_dir(&temporary_directory).map_err(|e| {
391 // At this point, we do not know the protected status of Vm
392 // setting it to false, though this may not be correct.
393 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100394 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000395 temporary_directory, e
396 );
397 new_binder_exception(
398 ExceptionCode::SERVICE_SPECIFIC,
399 format!(
400 "Failed to create temporary directory {:?} for VM files: {}",
401 temporary_directory, e
402 ),
403 )
404 })?;
405
406 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
407
408 let config = match config {
409 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
410 load_app_config(config, &temporary_directory).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100411 error!("Failed to load app config from {}: {:?}", &config.configPath, e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000412 *is_protected = config.protectedVm;
413 new_binder_exception(
414 ExceptionCode::SERVICE_SPECIFIC,
415 format!("Failed to load app config from {}: {}", &config.configPath, e),
416 )
417 })?,
418 ),
419 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
420 };
421 let config = config.as_ref();
422 *is_protected = config.protectedVm;
423
424 // Check if partition images are labeled incorrectly. This is to prevent random images
425 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
426 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
427 // to be labeled as app_data_file. For images in the app config, nothing but the instance
428 // partition is allowed to be labeled as such.
429 config
430 .disks
431 .iter()
432 .flat_map(|disk| disk.partitions.iter())
433 .filter(|partition| {
434 if is_app_config {
435 partition.label != "vm-instance"
436 } else {
437 true // all partitions are checked
438 }
439 })
440 .try_for_each(check_label_for_partition)
441 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
442
443 let zero_filler_path = temporary_directory.join("zero.img");
444 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100445 error!("Failed to make composite image: {:?}", e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000446 new_binder_exception(
447 ExceptionCode::SERVICE_SPECIFIC,
448 format!("Failed to make composite image: {}", e),
449 )
450 })?;
451
452 // Assemble disk images if needed.
453 let disks = config
454 .disks
455 .iter()
456 .map(|disk| {
457 assemble_disk_image(
458 disk,
459 &zero_filler_path,
460 &temporary_directory,
461 &mut next_temporary_image_id,
462 &mut indirect_files,
463 )
464 })
465 .collect::<Result<Vec<DiskFile>, _>>()?;
466
Jiyong Parke558ab12022-07-07 20:18:55 +0900467 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
468 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900469 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900470 // will be sent back to the client (i.e. the VM owner) for readout.
471 let ramdump_path = temporary_directory.join("ramdump");
472 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
473 error!("Failed to prepare ramdump file: {}", e);
474 new_binder_exception(
475 ExceptionCode::SERVICE_SPECIFIC,
476 format!("Failed to prepare ramdump file: {}", e),
477 )
478 })?;
479
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000480 // Actually start the VM.
481 let crosvm_config = CrosvmConfig {
482 cid,
483 bootloader: maybe_clone_file(&config.bootloader)?,
484 kernel: maybe_clone_file(&config.kernel)?,
485 initrd: maybe_clone_file(&config.initrd)?,
486 disks,
487 params: config.params.to_owned(),
488 protected: *is_protected,
489 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
490 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
491 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900492 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000493 console_fd,
494 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900495 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000496 indirect_files,
497 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900498 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000499 };
500 let instance = Arc::new(
501 VmInstance::new(
502 crosvm_config,
503 temporary_directory,
504 requester_uid,
505 requester_sid,
506 requester_debug_pid,
507 )
508 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100509 error!("Failed to create VM with config {:?}: {:?}", config, e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000510 new_binder_exception(
511 ExceptionCode::SERVICE_SPECIFIC,
512 format!("Failed to create VM: {}", e),
513 )
514 })?,
515 );
516 state.add_vm(Arc::downgrade(&instance));
517 Ok(VirtualMachine::create(instance))
518 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900519}
520
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000521/// Write the stats of VMCreation to statsd
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000522fn write_vm_creation_stats(is_protected: bool, creation_succeeded: bool, exception_code: i32) {
523 match stats_write(Hypervisor::Pkvm, is_protected, creation_succeeded, exception_code) {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000524 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000525 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000526 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000527 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000528 }
529}
530
Andrew Walbran6b650662021-09-07 13:13:23 +0000531/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
532/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900533fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900534 let listener =
535 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900536 for stream in listener.incoming() {
537 let stream = match stream {
538 Err(e) => {
539 warn!("invalid incoming connection: {}", e);
540 continue;
541 }
542 Ok(s) => s,
543 };
544 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
545 let cid = addr.cid();
546 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900547 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900548 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700549 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900550 } else {
551 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900552 }
553 }
554 }
555 Ok(())
556}
557
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000558fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900559 let file = OpenOptions::new()
560 .create_new(true)
561 .read(true)
562 .write(true)
563 .open(zero_filler_path)
564 .with_context(|| "Failed to create zero.img")?;
565 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000566 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900567}
568
Jiyong Park9dd389e2021-08-23 20:42:59 +0900569fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
570 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
571 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
572 part.flush()
573}
574
Jiyong Parke558ab12022-07-07 20:18:55 +0900575fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
576 File::create(&ramdump_path)
577 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
578}
579
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000580/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
581///
582/// This may involve assembling a composite disk from a set of partition images.
583fn assemble_disk_image(
584 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900585 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000586 temporary_directory: &Path,
587 next_temporary_image_id: &mut u64,
588 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000589) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590 let image = if !disk.partitions.is_empty() {
591 if disk.image.is_some() {
592 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000593 return Err(new_binder_exception(
594 ExceptionCode::ILLEGAL_ARGUMENT,
595 "DiskImage contains both image and partitions.",
596 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000597 }
598
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000599 let composite_image_filenames =
600 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
601 let (image, partition_files) = make_composite_image(
602 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900603 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000604 &composite_image_filenames.composite,
605 &composite_image_filenames.header,
606 &composite_image_filenames.footer,
607 )
608 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100609 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000610 new_binder_exception(
611 ExceptionCode::SERVICE_SPECIFIC,
612 format!("Failed to make composite image: {}", e),
613 )
614 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000615
616 // Pass the file descriptors for the various partition files to crosvm when it
617 // is run.
618 indirect_files.extend(partition_files);
619
620 image
621 } else if let Some(image) = &disk.image {
622 clone_file(image)?
623 } else {
624 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000625 return Err(new_binder_exception(
626 ExceptionCode::ILLEGAL_ARGUMENT,
627 "DiskImage didn't contain image or partitions.",
628 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629 };
630
631 Ok(DiskFile { image, writable: disk.writable })
632}
633
Jooyung Han21e9b922021-06-26 04:14:16 +0900634fn load_app_config(
635 config: &VirtualMachineAppConfig,
636 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900637) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000638 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
639 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900640 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900641 let config_path = &config.configPath;
642
Andrew Walbrancc0db522021-07-12 17:03:42 +0000643 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900644 let config_file = apk_zip.by_name(config_path)?;
645 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
646
647 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000648
Jooyung Han35edb8f2021-07-01 16:17:16 +0900649 // For now, the only supported "os" value is "microdroid"
650 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000651 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900652 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000653
654 // It is safe to construct a filename based on the os_name because we've already checked that it
655 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900656 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
657 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000658 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900659
Andrew Walbrancc045902021-07-27 16:06:17 +0000660 if config.memoryMib > 0 {
661 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000662 }
663
Andrew Walbran3994f002022-01-27 17:33:45 +0000664 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900665 vm_config.numCpus = config.numCpus;
666 vm_config.cpuAffinity = config.cpuAffinity.clone();
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900667 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900668
Andrew Walbrancc0db522021-07-12 17:03:42 +0000669 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900670 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000671 add_microdroid_images(
672 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900673 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000674 apk_file,
675 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900676 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900677 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000678 &mut vm_config,
679 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900680 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900681
Andrew Walbrancc0db522021-07-12 17:03:42 +0000682 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900683}
684
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000685/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000686fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000687 temporary_directory: &Path,
688 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000689) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000690 let id = *next_temporary_image_id;
691 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000692 CompositeImageFilenames {
693 composite: temporary_directory.join(format!("composite-{}.img", id)),
694 header: temporary_directory.join(format!("composite-{}-header.img", id)),
695 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
696 }
697}
698
699/// Filenames for a composite disk image, including header and footer partitions.
700#[derive(Clone, Debug, Eq, PartialEq)]
701struct CompositeImageFilenames {
702 /// The composite disk image itself.
703 composite: PathBuf,
704 /// The header partition image.
705 header: PathBuf,
706 /// The footer partition image.
707 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000708}
709
710/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000711fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000712 ThreadState::with_calling_sid(|sid| {
713 if let Some(sid) = sid {
714 match sid.to_str() {
715 Ok(sid) => Ok(sid.to_owned()),
716 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000717 error!("SID was not valid UTF-8: {}", e);
718 Err(new_binder_exception(
719 ExceptionCode::ILLEGAL_ARGUMENT,
720 format!("SID was not valid UTF-8: {}", e),
721 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000722 }
723 }
724 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000725 error!("Missing SID on createVm");
726 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000727 }
728 })
729}
730
Jiyong Park753553b2021-07-12 21:21:09 +0900731/// Checks whether the caller has a specific permission
732fn check_permission(perm: &str) -> binder::Result<()> {
733 let calling_pid = ThreadState::get_calling_pid();
734 let calling_uid = ThreadState::get_calling_uid();
735 // Root can do anything
736 if calling_uid == 0 {
737 return Ok(());
738 }
739 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
740 binder::get_interface("permission")?;
741 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000742 Ok(())
743 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900744 Err(new_binder_exception(
745 ExceptionCode::SECURITY,
746 format!("does not have the {} permission", perm),
747 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000748 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000749}
750
Jiyong Park753553b2021-07-12 21:21:09 +0900751/// Check whether the caller of the current Binder method is allowed to call debug methods.
752fn check_debug_access() -> binder::Result<()> {
753 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
754}
755
756/// Check whether the caller of the current Binder method is allowed to manage VMs
757fn check_manage_access() -> binder::Result<()> {
758 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
759}
760
Inseob Kim1119d702022-05-02 18:01:58 +0900761/// Check whether the caller of the current Binder method is allowed to create custom VMs
762fn check_use_custom_virtual_machine() -> binder::Result<()> {
763 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
764}
765
Jiyong Park029977d2021-11-24 21:56:49 +0900766/// Check if a partition has selinux labels that are not allowed
767fn check_label_for_partition(partition: &Partition) -> Result<()> {
768 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
769 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
770 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
771 } else {
772 Ok(())
773 }
774}
775
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000776/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
777#[derive(Debug)]
778struct VirtualMachine {
779 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100780 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800781 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100782 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000783}
784
785impl VirtualMachine {
786 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100787 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000788 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000789 }
790}
791
792impl Interface for VirtualMachine {}
793
794impl IVirtualMachine for VirtualMachine {
795 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900796 // Don't check permission. The owner of the VM might have passed this binder object to
797 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000798 Ok(self.instance.cid as i32)
799 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000800
Andrew Walbran6b650662021-09-07 13:13:23 +0000801 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900802 // Don't check permission. The owner of the VM might have passed this binder object to
803 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000804 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000805 }
806
807 fn registerCallback(
808 &self,
809 callback: &Strong<dyn IVirtualMachineCallback>,
810 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900811 // Don't check permission. The owner of the VM might have passed this binder object to
812 // others.
813 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000814 // TODO: Should this give an error if the VM is already dead?
815 self.instance.callbacks.add(callback.clone());
816 Ok(())
817 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000818
Andrew Walbranf8d94112021-09-07 11:45:36 +0000819 fn start(&self) -> binder::Result<()> {
820 self.instance.start().map_err(|e| {
821 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
822 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
823 })
824 }
825
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000826 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000827 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
828 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000829 }
830 let stream =
831 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
832 new_binder_exception(
833 ExceptionCode::SERVICE_SPECIFIC,
834 format!("Failed to connect: {}", e),
835 )
836 })?;
837 Ok(vsock_stream_to_pfd(stream))
838 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000839}
840
841impl Drop for VirtualMachine {
842 fn drop(&mut self) {
843 debug!("Dropping {:?}", self);
844 self.instance.kill();
845 }
846}
847
848/// A set of Binders to be called back in response to various events on the VM, such as when it
849/// dies.
850#[derive(Debug, Default)]
851pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
852
853impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900854 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900855 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900856 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900857 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900858 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900859 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100860 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900861 }
862 }
863 }
864
Inseob Kim14cb8692021-08-31 21:50:39 +0900865 /// Call all registered callbacks to notify that the payload is ready to serve.
866 pub fn notify_payload_ready(&self, cid: Cid) {
867 let callbacks = &*self.0.lock().unwrap();
868 for callback in callbacks {
869 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100870 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900871 }
872 }
873 }
874
Inseob Kim2444af92021-08-31 01:22:50 +0900875 /// Call all registered callbacks to notify that the payload has finished.
876 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
877 let callbacks = &*self.0.lock().unwrap();
878 for callback in callbacks {
879 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100880 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900881 }
882 }
883 }
884
Jooyung Handd0a1732021-11-23 15:26:20 +0900885 /// Call all registered callbacks to say that the VM encountered an error.
886 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
887 let callbacks = &*self.0.lock().unwrap();
888 for callback in callbacks {
889 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100890 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900891 }
892 }
893 }
894
Andrew Walbrandae07162021-03-12 17:05:20 +0000895 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000896 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000897 let callbacks = &*self.0.lock().unwrap();
898 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000899 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100900 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000901 }
902 }
903 }
904
Jiyong Parke558ab12022-07-07 20:18:55 +0900905 /// Call all registered callbacks to say that there was a ramdump to download.
906 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
907 let callbacks = &*self.0.lock().unwrap();
908 let pfd = ParcelFileDescriptor::new(ramdump);
909 for callback in callbacks {
910 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
911 error!("Error notifying ramdump of VM CID {}: {}", cid, e);
912 }
913 }
914 }
915
Andrew Walbrandae07162021-03-12 17:05:20 +0000916 /// Add a new callback to the set.
917 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
918 self.0.lock().unwrap().push(callback);
919 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000920}
921
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000922/// The mutable state of the VirtualizationService. There should only be one instance of this
923/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800924#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000925struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000926 /// The VMs which have been started. When VMs are started a weak reference is added to this list
927 /// while a strong reference is returned to the caller over Binder. Once all copies of the
928 /// Binder client are dropped the weak reference here will become invalid, and will be removed
929 /// from the list opportunistically the next time `add_vm` is called.
930 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000931
932 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
933 /// This is only used for debugging purposes.
934 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000935}
936
937impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000938 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000939 fn vms(&self) -> Vec<Arc<VmInstance>> {
940 // Attempt to upgrade the weak pointers to strong pointers.
941 self.vms.iter().filter_map(Weak::upgrade).collect()
942 }
943
944 /// Add a new VM to the list.
945 fn add_vm(&mut self, vm: Weak<VmInstance>) {
946 // Garbage collect any entries from the stored list which no longer exist.
947 self.vms.retain(|vm| vm.strong_count() > 0);
948
949 // Actually add the new VM.
950 self.vms.push(vm);
951 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000952
Jiyong Park8611a6c2021-07-09 18:17:44 +0900953 /// Get a VM that corresponds to the given cid
954 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
955 self.vms().into_iter().find(|vm| vm.cid == cid)
956 }
957
David Brazdil3c2ddef2021-03-18 13:09:57 +0000958 /// Store a strong VM reference.
959 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
960 self.debug_held_vms.push(vm);
961 }
962
963 /// Retrieve and remove a strong VM reference.
964 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
965 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100966 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100967 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000968 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000969}
970
Jiyong Parkd50a0242021-09-16 21:00:14 +0900971/// Get the next available CID, or an error if we have run out. The last CID used is stored in
972/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
973/// Android is up.
974fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000975 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900976 if let Ok(num) = val.parse::<u32>() {
977 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
978 } else {
979 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
980 FIRST_GUEST_CID
981 }
982 } else {
983 // First VM since the boot
984 FIRST_GUEST_CID
985 };
986 // Persist the last value for next use
987 let str_val = format!("{}", next);
988 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
989 Ok(next)
990}
991
Andrew Walbran6b650662021-09-07 13:13:23 +0000992/// Gets the `VirtualMachineState` of the given `VmInstance`.
993fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000994 match &*instance.vm_state.lock().unwrap() {
995 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
996 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000997 PayloadState::Starting => VirtualMachineState::STARTING,
998 PayloadState::Started => VirtualMachineState::STARTED,
999 PayloadState::Ready => VirtualMachineState::READY,
1000 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001001 },
1002 VmState::Dead => VirtualMachineState::DEAD,
1003 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001004 }
1005}
1006
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001007/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +00001008fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
1009 file.as_ref().try_clone().map_err(|e| {
1010 new_binder_exception(
1011 ExceptionCode::BAD_PARCELABLE,
1012 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
1013 )
1014 })
1015}
1016
Andrew Walbrand3a84182021-09-07 14:48:52 +00001017/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1018fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1019 file.as_ref().map(clone_file).transpose()
1020}
1021
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001022/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1023fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1024 // SAFETY: ownership is transferred from stream to f
1025 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1026 ParcelFileDescriptor::new(f)
1027}
1028
Jiyong Parkdcf17412022-02-08 15:07:23 +09001029/// Parses the platform version requirement string.
1030fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1031 VersionReq::parse(s).map_err(|e| {
1032 new_binder_exception(
1033 ExceptionCode::BAD_PARCELABLE,
1034 format!("Invalid platform version requirement {}: {}", s, e),
1035 )
1036 })
1037}
1038
Jooyung Han35edb8f2021-07-01 16:17:16 +09001039/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1040/// it doesn't require that T implements Clone.
1041enum BorrowedOrOwned<'a, T> {
1042 Borrowed(&'a T),
1043 Owned(T),
1044}
1045
1046impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1047 fn as_ref(&self) -> &T {
1048 match self {
1049 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001050 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001051 }
1052 }
1053}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001054
1055/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1056#[derive(Debug, Default)]
1057struct VirtualMachineService {
1058 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001059 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001060}
1061
1062impl Interface for VirtualMachineService {}
1063
1064impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001065 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1066 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001067 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1068 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001069 vm.update_payload_state(PayloadState::Started)
1070 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001071 let stream = vm.stream.lock().unwrap().take();
1072 vm.callbacks.notify_payload_started(cid, stream);
1073 Ok(())
1074 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001075 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001076 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001077 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001078 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001079 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001080 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001081 }
Inseob Kim2444af92021-08-31 01:22:50 +09001082
Inseob Kimc7d28c72021-10-25 14:28:10 +00001083 fn notifyPayloadReady(&self) -> binder::Result<()> {
1084 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001085 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1086 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001087 vm.update_payload_state(PayloadState::Ready)
1088 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001089 vm.callbacks.notify_payload_ready(cid);
1090 Ok(())
1091 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001092 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +09001093 Err(new_binder_exception(
1094 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001095 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +09001096 ))
1097 }
1098 }
1099
Inseob Kimc7d28c72021-10-25 14:28:10 +00001100 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1101 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001102 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1103 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001104 vm.update_payload_state(PayloadState::Finished)
1105 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +09001106 vm.callbacks.notify_payload_finished(cid, exit_code);
1107 Ok(())
1108 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001109 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +09001110 Err(new_binder_exception(
1111 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001112 format!("cannot find a VM with CID {}", cid),
1113 ))
1114 }
1115 }
1116
1117 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
1118 let cid = self.cid;
1119 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1120 info!("VM having CID {} encountered an error", cid);
1121 vm.update_payload_state(PayloadState::Finished)
1122 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1123 vm.callbacks.notify_error(cid, error_code, message);
1124 Ok(())
1125 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001126 error!("notifyError is called from an unknown CID {}", cid);
Jooyung Handd0a1732021-11-23 15:26:20 +09001127 Err(new_binder_exception(
1128 ExceptionCode::SERVICE_SPECIFIC,
1129 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001130 ))
1131 }
1132 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001133}
1134
1135impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001136 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1137 pub unsafe extern "C" fn factory(
1138 cid: Cid,
1139 context: *mut raw::c_void,
1140 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1141 let state_ptr = context as *mut Arc<Mutex<State>>;
1142 let state = state_ptr.as_ref().unwrap();
1143 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1144 let mut vm_service = vm.vm_service.lock().unwrap();
1145 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1146 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1147 } else {
1148 error!("connection from cid={} is not from a guest VM", cid);
1149 null_mut()
1150 }
1151 }
1152
1153 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001154 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001155 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001156 BinderFeatures::default(),
1157 )
1158 }
1159}