blob: a2e856cdc59880b82a072e07612f1513d1a16a97 [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
213 let mut input = clone_file(input_fd)?;
214 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
215
216 let mut output = clone_file(idsig_fd)?;
217 output.set_len(0).unwrap();
218 sig.write_into(&mut output).unwrap();
219 Ok(())
220 }
221
Andrew Walbran320b5602021-03-04 16:11:12 +0000222 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
223 /// and as such is only permitted from the shell user.
224 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000225 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000226
227 let state = &mut *self.state.lock().unwrap();
228 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000229 let cids = vms
230 .into_iter()
231 .map(|vm| VirtualMachineDebugInfo {
232 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000233 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000234 requesterUid: vm.requester_uid as i32,
235 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000236 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000237 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000238 })
239 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000240 Ok(cids)
241 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000243 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
244 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000245 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000246 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000247
David Brazdil3c2ddef2021-03-18 13:09:57 +0000248 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000249 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000250 Ok(())
251 }
252
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000253 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
254 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
255 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000256 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000257 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000258
259 let state = &mut *self.state.lock().unwrap();
260 Ok(state.debug_drop_vm(cid))
261 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000262}
263
Shikha Panwar7afc1392022-03-24 08:54:43 +0000264fn handle_stream_connection_tombstoned() -> Result<()> {
265 let listener =
266 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
267 info!("Listening to tombstones from guests ...");
268 for incoming_stream in listener.incoming() {
269 let mut incoming_stream = match incoming_stream {
270 Err(e) => {
271 warn!("invalid incoming connection: {}", e);
272 continue;
273 }
274 Ok(s) => s,
275 };
276 std::thread::spawn(move || {
277 if let Err(e) = handle_tombstone(&mut incoming_stream) {
278 error!("Failed to write tombstone- {:?}", e);
279 }
280 });
281 }
282 Ok(())
283}
284
285fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
286 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
287 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
288 }
289 let tb_connection =
290 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
291 .context("Failed to connect to tombstoned")?;
292 let mut text_output = tb_connection
293 .text_output
294 .as_ref()
295 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
296 let mut num_bytes_read = 0;
297 loop {
298 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
299 let n = stream
300 .read(&mut chunk_recv)
301 .context("Failed to read tombstone data from Vsock stream")?;
302 if n == 0 {
303 break;
304 }
305 num_bytes_read += n;
306 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
307 }
308 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
309 tb_connection.notify_completion()?;
310 Ok(())
311}
312
Jiyong Park8611a6c2021-07-09 18:17:44 +0900313impl VirtualizationService {
314 pub fn init() -> VirtualizationService {
315 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900316
317 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900318 let state = service.state.clone(); // reference to state (not the state itself) is copied
319 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900320 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900321 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900322
Shikha Panwar7afc1392022-03-24 08:54:43 +0000323 std::thread::spawn(|| {
324 if let Err(e) = handle_stream_connection_tombstoned() {
325 warn!("Error receiving tombstone from guest or writing them. Error: {}", e);
326 }
327 });
328
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900329 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000330 // reference to state (not the state itself) is copied
331 let mut state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900332 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000333 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
334
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900335 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000336 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
337 // lifetime of the state, with context taking the pointer value above (so a properly
338 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900339 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000340 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
341 Some(VirtualMachineService::factory),
342 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900343 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900344 )
345 };
346 if retval {
347 debug!("RPC server has shut down gracefully");
348 } else {
349 bail!("Premature termination of RPC server");
350 }
351
352 Ok(retval)
353 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900354 service
355 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000356
357 fn create_vm_internal(
358 &self,
359 config: &VirtualMachineConfig,
360 console_fd: Option<&ParcelFileDescriptor>,
361 log_fd: Option<&ParcelFileDescriptor>,
362 is_protected: &mut bool,
363 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
364 check_manage_access()?;
365 let state = &mut *self.state.lock().unwrap();
366 let console_fd = console_fd.map(clone_file).transpose()?;
367 let log_fd = log_fd.map(clone_file).transpose()?;
368 let requester_uid = ThreadState::get_calling_uid();
369 let requester_sid = get_calling_sid()?;
370 let requester_debug_pid = ThreadState::get_calling_pid();
371 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
372
373 // Counter to generate unique IDs for temporary image files.
374 let mut next_temporary_image_id = 0;
375 // Files which are referred to from composite images. These must be mapped to the crosvm
376 // child process, and not closed before it is started.
377 let mut indirect_files = vec![];
378
379 // Make directory for temporary files.
380 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
381 create_dir(&temporary_directory).map_err(|e| {
382 // At this point, we do not know the protected status of Vm
383 // setting it to false, though this may not be correct.
384 error!(
385 "Failed to create temporary directory {:?} for VM files: {}",
386 temporary_directory, e
387 );
388 new_binder_exception(
389 ExceptionCode::SERVICE_SPECIFIC,
390 format!(
391 "Failed to create temporary directory {:?} for VM files: {}",
392 temporary_directory, e
393 ),
394 )
395 })?;
396
397 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
398
399 let config = match config {
400 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
401 load_app_config(config, &temporary_directory).map_err(|e| {
402 error!("Failed to load app config from {}: {}", &config.configPath, e);
403 *is_protected = config.protectedVm;
404 new_binder_exception(
405 ExceptionCode::SERVICE_SPECIFIC,
406 format!("Failed to load app config from {}: {}", &config.configPath, e),
407 )
408 })?,
409 ),
410 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
411 };
412 let config = config.as_ref();
413 *is_protected = config.protectedVm;
414
415 // Check if partition images are labeled incorrectly. This is to prevent random images
416 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
417 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
418 // to be labeled as app_data_file. For images in the app config, nothing but the instance
419 // partition is allowed to be labeled as such.
420 config
421 .disks
422 .iter()
423 .flat_map(|disk| disk.partitions.iter())
424 .filter(|partition| {
425 if is_app_config {
426 partition.label != "vm-instance"
427 } else {
428 true // all partitions are checked
429 }
430 })
431 .try_for_each(check_label_for_partition)
432 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
433
434 let zero_filler_path = temporary_directory.join("zero.img");
435 write_zero_filler(&zero_filler_path).map_err(|e| {
436 error!("Failed to make composite image: {}", e);
437 new_binder_exception(
438 ExceptionCode::SERVICE_SPECIFIC,
439 format!("Failed to make composite image: {}", e),
440 )
441 })?;
442
443 // Assemble disk images if needed.
444 let disks = config
445 .disks
446 .iter()
447 .map(|disk| {
448 assemble_disk_image(
449 disk,
450 &zero_filler_path,
451 &temporary_directory,
452 &mut next_temporary_image_id,
453 &mut indirect_files,
454 )
455 })
456 .collect::<Result<Vec<DiskFile>, _>>()?;
457
458 // Actually start the VM.
459 let crosvm_config = CrosvmConfig {
460 cid,
461 bootloader: maybe_clone_file(&config.bootloader)?,
462 kernel: maybe_clone_file(&config.kernel)?,
463 initrd: maybe_clone_file(&config.initrd)?,
464 disks,
465 params: config.params.to_owned(),
466 protected: *is_protected,
467 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
468 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
469 cpu_affinity: config.cpuAffinity.clone(),
470 console_fd,
471 log_fd,
472 indirect_files,
473 platform_version: parse_platform_version_req(&config.platformVersion)?,
474 };
475 let instance = Arc::new(
476 VmInstance::new(
477 crosvm_config,
478 temporary_directory,
479 requester_uid,
480 requester_sid,
481 requester_debug_pid,
482 )
483 .map_err(|e| {
484 error!("Failed to create VM with config {:?}: {}", config, e);
485 new_binder_exception(
486 ExceptionCode::SERVICE_SPECIFIC,
487 format!("Failed to create VM: {}", e),
488 )
489 })?,
490 );
491 state.add_vm(Arc::downgrade(&instance));
492 Ok(VirtualMachine::create(instance))
493 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900494}
495
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000496/// Write the stats of VMCreation to statsd
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000497fn write_vm_creation_stats(is_protected: bool, creation_succeeded: bool, exception_code: i32) {
498 match stats_write(Hypervisor::Pkvm, is_protected, creation_succeeded, exception_code) {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000499 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000500 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000501 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000502 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000503 }
504}
505
Andrew Walbran6b650662021-09-07 13:13:23 +0000506/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
507/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900508fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900509 let listener =
510 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900511 for stream in listener.incoming() {
512 let stream = match stream {
513 Err(e) => {
514 warn!("invalid incoming connection: {}", e);
515 continue;
516 }
517 Ok(s) => s,
518 };
519 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
520 let cid = addr.cid();
521 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900522 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900523 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700524 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900525 } else {
526 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900527 }
528 }
529 }
530 Ok(())
531}
532
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000533fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900534 let file = OpenOptions::new()
535 .create_new(true)
536 .read(true)
537 .write(true)
538 .open(zero_filler_path)
539 .with_context(|| "Failed to create zero.img")?;
540 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000541 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900542}
543
Jiyong Park9dd389e2021-08-23 20:42:59 +0900544fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
545 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
546 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
547 part.flush()
548}
549
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000550/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
551///
552/// This may involve assembling a composite disk from a set of partition images.
553fn assemble_disk_image(
554 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900555 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000556 temporary_directory: &Path,
557 next_temporary_image_id: &mut u64,
558 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000559) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000560 let image = if !disk.partitions.is_empty() {
561 if disk.image.is_some() {
562 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000563 return Err(new_binder_exception(
564 ExceptionCode::ILLEGAL_ARGUMENT,
565 "DiskImage contains both image and partitions.",
566 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000567 }
568
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000569 let composite_image_filenames =
570 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
571 let (image, partition_files) = make_composite_image(
572 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900573 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000574 &composite_image_filenames.composite,
575 &composite_image_filenames.header,
576 &composite_image_filenames.footer,
577 )
578 .map_err(|e| {
579 error!("Failed to make composite image with config {:?}: {}", disk, e);
580 new_binder_exception(
581 ExceptionCode::SERVICE_SPECIFIC,
582 format!("Failed to make composite image: {}", e),
583 )
584 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000585
586 // Pass the file descriptors for the various partition files to crosvm when it
587 // is run.
588 indirect_files.extend(partition_files);
589
590 image
591 } else if let Some(image) = &disk.image {
592 clone_file(image)?
593 } else {
594 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000595 return Err(new_binder_exception(
596 ExceptionCode::ILLEGAL_ARGUMENT,
597 "DiskImage didn't contain image or partitions.",
598 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000599 };
600
601 Ok(DiskFile { image, writable: disk.writable })
602}
603
Jooyung Han21e9b922021-06-26 04:14:16 +0900604fn load_app_config(
605 config: &VirtualMachineAppConfig,
606 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900607) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000608 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
609 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900610 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900611 let config_path = &config.configPath;
612
Andrew Walbrancc0db522021-07-12 17:03:42 +0000613 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900614 let config_file = apk_zip.by_name(config_path)?;
615 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
616
617 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000618
Jooyung Han35edb8f2021-07-01 16:17:16 +0900619 // For now, the only supported "os" value is "microdroid"
620 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000621 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900622 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000623
624 // It is safe to construct a filename based on the os_name because we've already checked that it
625 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900626 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
627 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000628 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900629
Andrew Walbrancc045902021-07-27 16:06:17 +0000630 if config.memoryMib > 0 {
631 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000632 }
633
Andrew Walbran3994f002022-01-27 17:33:45 +0000634 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900635 vm_config.numCpus = config.numCpus;
636 vm_config.cpuAffinity = config.cpuAffinity.clone();
637
Andrew Walbrancc0db522021-07-12 17:03:42 +0000638 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900639 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000640 add_microdroid_images(
641 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900642 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000643 apk_file,
644 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900645 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900646 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000647 &mut vm_config,
648 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900649 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900650
Andrew Walbrancc0db522021-07-12 17:03:42 +0000651 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900652}
653
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000654/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000655fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000656 temporary_directory: &Path,
657 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000658) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000659 let id = *next_temporary_image_id;
660 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000661 CompositeImageFilenames {
662 composite: temporary_directory.join(format!("composite-{}.img", id)),
663 header: temporary_directory.join(format!("composite-{}-header.img", id)),
664 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
665 }
666}
667
668/// Filenames for a composite disk image, including header and footer partitions.
669#[derive(Clone, Debug, Eq, PartialEq)]
670struct CompositeImageFilenames {
671 /// The composite disk image itself.
672 composite: PathBuf,
673 /// The header partition image.
674 header: PathBuf,
675 /// The footer partition image.
676 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000677}
678
679/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000680fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000681 ThreadState::with_calling_sid(|sid| {
682 if let Some(sid) = sid {
683 match sid.to_str() {
684 Ok(sid) => Ok(sid.to_owned()),
685 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000686 error!("SID was not valid UTF-8: {}", e);
687 Err(new_binder_exception(
688 ExceptionCode::ILLEGAL_ARGUMENT,
689 format!("SID was not valid UTF-8: {}", e),
690 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000691 }
692 }
693 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000694 error!("Missing SID on createVm");
695 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696 }
697 })
698}
699
Jiyong Park753553b2021-07-12 21:21:09 +0900700/// Checks whether the caller has a specific permission
701fn check_permission(perm: &str) -> binder::Result<()> {
702 let calling_pid = ThreadState::get_calling_pid();
703 let calling_uid = ThreadState::get_calling_uid();
704 // Root can do anything
705 if calling_uid == 0 {
706 return Ok(());
707 }
708 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
709 binder::get_interface("permission")?;
710 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000711 Ok(())
712 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900713 Err(new_binder_exception(
714 ExceptionCode::SECURITY,
715 format!("does not have the {} permission", perm),
716 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000717 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000718}
719
Jiyong Park753553b2021-07-12 21:21:09 +0900720/// Check whether the caller of the current Binder method is allowed to call debug methods.
721fn check_debug_access() -> binder::Result<()> {
722 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
723}
724
725/// Check whether the caller of the current Binder method is allowed to manage VMs
726fn check_manage_access() -> binder::Result<()> {
727 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
728}
729
Jiyong Park029977d2021-11-24 21:56:49 +0900730/// Check if a partition has selinux labels that are not allowed
731fn check_label_for_partition(partition: &Partition) -> Result<()> {
732 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
733 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
734 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
735 } else {
736 Ok(())
737 }
738}
739
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000740/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
741#[derive(Debug)]
742struct VirtualMachine {
743 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100744 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800745 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100746 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000747}
748
749impl VirtualMachine {
750 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100751 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000752 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000753 }
754}
755
756impl Interface for VirtualMachine {}
757
758impl IVirtualMachine for VirtualMachine {
759 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900760 // Don't check permission. The owner of the VM might have passed this binder object to
761 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000762 Ok(self.instance.cid as i32)
763 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000764
Andrew Walbran6b650662021-09-07 13:13:23 +0000765 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900766 // Don't check permission. The owner of the VM might have passed this binder object to
767 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000768 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000769 }
770
771 fn registerCallback(
772 &self,
773 callback: &Strong<dyn IVirtualMachineCallback>,
774 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900775 // Don't check permission. The owner of the VM might have passed this binder object to
776 // others.
777 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000778 // TODO: Should this give an error if the VM is already dead?
779 self.instance.callbacks.add(callback.clone());
780 Ok(())
781 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000782
Andrew Walbranf8d94112021-09-07 11:45:36 +0000783 fn start(&self) -> binder::Result<()> {
784 self.instance.start().map_err(|e| {
785 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
786 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
787 })
788 }
789
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000790 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000791 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
792 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000793 }
794 let stream =
795 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
796 new_binder_exception(
797 ExceptionCode::SERVICE_SPECIFIC,
798 format!("Failed to connect: {}", e),
799 )
800 })?;
801 Ok(vsock_stream_to_pfd(stream))
802 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000803}
804
805impl Drop for VirtualMachine {
806 fn drop(&mut self) {
807 debug!("Dropping {:?}", self);
808 self.instance.kill();
809 }
810}
811
812/// A set of Binders to be called back in response to various events on the VM, such as when it
813/// dies.
814#[derive(Debug, Default)]
815pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
816
817impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900818 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900819 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900820 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900821 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900822 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900823 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900824 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
825 }
826 }
827 }
828
Inseob Kim14cb8692021-08-31 21:50:39 +0900829 /// Call all registered callbacks to notify that the payload is ready to serve.
830 pub fn notify_payload_ready(&self, cid: Cid) {
831 let callbacks = &*self.0.lock().unwrap();
832 for callback in callbacks {
833 if let Err(e) = callback.onPayloadReady(cid as i32) {
834 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
835 }
836 }
837 }
838
Inseob Kim2444af92021-08-31 01:22:50 +0900839 /// Call all registered callbacks to notify that the payload has finished.
840 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
841 let callbacks = &*self.0.lock().unwrap();
842 for callback in callbacks {
843 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
844 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
845 }
846 }
847 }
848
Jooyung Handd0a1732021-11-23 15:26:20 +0900849 /// Call all registered callbacks to say that the VM encountered an error.
850 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
851 let callbacks = &*self.0.lock().unwrap();
852 for callback in callbacks {
853 if let Err(e) = callback.onError(cid as i32, error_code, message) {
854 error!("Error notifying error event from VM CID {}: {}", cid, e);
855 }
856 }
857 }
858
Andrew Walbrandae07162021-03-12 17:05:20 +0000859 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000860 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000861 let callbacks = &*self.0.lock().unwrap();
862 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000863 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900864 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000865 }
866 }
867 }
868
869 /// Add a new callback to the set.
870 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
871 self.0.lock().unwrap().push(callback);
872 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000873}
874
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000875/// The mutable state of the VirtualizationService. There should only be one instance of this
876/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800877#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000878struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000879 /// The VMs which have been started. When VMs are started a weak reference is added to this list
880 /// while a strong reference is returned to the caller over Binder. Once all copies of the
881 /// Binder client are dropped the weak reference here will become invalid, and will be removed
882 /// from the list opportunistically the next time `add_vm` is called.
883 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000884
885 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
886 /// This is only used for debugging purposes.
887 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000888}
889
890impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000891 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000892 fn vms(&self) -> Vec<Arc<VmInstance>> {
893 // Attempt to upgrade the weak pointers to strong pointers.
894 self.vms.iter().filter_map(Weak::upgrade).collect()
895 }
896
897 /// Add a new VM to the list.
898 fn add_vm(&mut self, vm: Weak<VmInstance>) {
899 // Garbage collect any entries from the stored list which no longer exist.
900 self.vms.retain(|vm| vm.strong_count() > 0);
901
902 // Actually add the new VM.
903 self.vms.push(vm);
904 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000905
Jiyong Park8611a6c2021-07-09 18:17:44 +0900906 /// Get a VM that corresponds to the given cid
907 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
908 self.vms().into_iter().find(|vm| vm.cid == cid)
909 }
910
David Brazdil3c2ddef2021-03-18 13:09:57 +0000911 /// Store a strong VM reference.
912 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
913 self.debug_held_vms.push(vm);
914 }
915
916 /// Retrieve and remove a strong VM reference.
917 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
918 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100919 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100920 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000921 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000922}
923
Jiyong Parkd50a0242021-09-16 21:00:14 +0900924/// Get the next available CID, or an error if we have run out. The last CID used is stored in
925/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
926/// Android is up.
927fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000928 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900929 if let Ok(num) = val.parse::<u32>() {
930 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
931 } else {
932 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
933 FIRST_GUEST_CID
934 }
935 } else {
936 // First VM since the boot
937 FIRST_GUEST_CID
938 };
939 // Persist the last value for next use
940 let str_val = format!("{}", next);
941 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
942 Ok(next)
943}
944
Andrew Walbran6b650662021-09-07 13:13:23 +0000945/// Gets the `VirtualMachineState` of the given `VmInstance`.
946fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000947 match &*instance.vm_state.lock().unwrap() {
948 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
949 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000950 PayloadState::Starting => VirtualMachineState::STARTING,
951 PayloadState::Started => VirtualMachineState::STARTED,
952 PayloadState::Ready => VirtualMachineState::READY,
953 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000954 },
955 VmState::Dead => VirtualMachineState::DEAD,
956 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000957 }
958}
959
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000960/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000961fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
962 file.as_ref().try_clone().map_err(|e| {
963 new_binder_exception(
964 ExceptionCode::BAD_PARCELABLE,
965 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
966 )
967 })
968}
969
Andrew Walbrand3a84182021-09-07 14:48:52 +0000970/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
971fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
972 file.as_ref().map(clone_file).transpose()
973}
974
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000975/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
976fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
977 // SAFETY: ownership is transferred from stream to f
978 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
979 ParcelFileDescriptor::new(f)
980}
981
Jiyong Parkdcf17412022-02-08 15:07:23 +0900982/// Parses the platform version requirement string.
983fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
984 VersionReq::parse(s).map_err(|e| {
985 new_binder_exception(
986 ExceptionCode::BAD_PARCELABLE,
987 format!("Invalid platform version requirement {}: {}", s, e),
988 )
989 })
990}
991
Jooyung Han35edb8f2021-07-01 16:17:16 +0900992/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
993/// it doesn't require that T implements Clone.
994enum BorrowedOrOwned<'a, T> {
995 Borrowed(&'a T),
996 Owned(T),
997}
998
999impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1000 fn as_ref(&self) -> &T {
1001 match self {
1002 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001003 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001004 }
1005 }
1006}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001007
1008/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1009#[derive(Debug, Default)]
1010struct VirtualMachineService {
1011 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001012 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001013}
1014
1015impl Interface for VirtualMachineService {}
1016
1017impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001018 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1019 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001020 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1021 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001022 vm.update_payload_state(PayloadState::Started)
1023 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001024 let stream = vm.stream.lock().unwrap().take();
1025 vm.callbacks.notify_payload_started(cid, stream);
1026 Ok(())
1027 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001028 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001029 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001030 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001031 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001032 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001033 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001034 }
Inseob Kim2444af92021-08-31 01:22:50 +09001035
Inseob Kimc7d28c72021-10-25 14:28:10 +00001036 fn notifyPayloadReady(&self) -> binder::Result<()> {
1037 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001038 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1039 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001040 vm.update_payload_state(PayloadState::Ready)
1041 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001042 vm.callbacks.notify_payload_ready(cid);
1043 Ok(())
1044 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001045 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +09001046 Err(new_binder_exception(
1047 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001048 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +09001049 ))
1050 }
1051 }
1052
Inseob Kimc7d28c72021-10-25 14:28:10 +00001053 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1054 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001055 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1056 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001057 vm.update_payload_state(PayloadState::Finished)
1058 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +09001059 vm.callbacks.notify_payload_finished(cid, exit_code);
1060 Ok(())
1061 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001062 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +09001063 Err(new_binder_exception(
1064 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001065 format!("cannot find a VM with CID {}", cid),
1066 ))
1067 }
1068 }
1069
1070 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
1071 let cid = self.cid;
1072 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1073 info!("VM having CID {} encountered an error", cid);
1074 vm.update_payload_state(PayloadState::Finished)
1075 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1076 vm.callbacks.notify_error(cid, error_code, message);
1077 Ok(())
1078 } else {
1079 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
1080 Err(new_binder_exception(
1081 ExceptionCode::SERVICE_SPECIFIC,
1082 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001083 ))
1084 }
1085 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001086}
1087
1088impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001089 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1090 pub unsafe extern "C" fn factory(
1091 cid: Cid,
1092 context: *mut raw::c_void,
1093 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1094 let state_ptr = context as *mut Arc<Mutex<State>>;
1095 let state = state_ptr.as_ref().unwrap();
1096 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1097 let mut vm_service = vm.vm_service.lock().unwrap();
1098 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1099 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1100 } else {
1101 error!("connection from cid={} is not from a guest VM", cid);
1102 null_mut()
1103 }
1104 }
1105
1106 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001107 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001108 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001109 BinderFeatures::default(),
1110 )
1111 }
1112}