blob: 505eb0cf29c0b26aad10709edd15282de93fc067 [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,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090032 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineAppConfig::VirtualMachineAppConfig,
34 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090036 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090038};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000039use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000040 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010041 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000042};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
44 IVirtualMachineService::{
45 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
46 VM_STREAM_SERVICE_PORT,
47 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090048};
Jiyong Parkd50a0242021-09-16 21:00:14 +090049use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010050use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000051use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010052use idsig::{HashAlgorithm, V4Signature};
Andrew Walbranf6d600f2022-02-03 14:42:39 +000053use log::{debug, error, info, warn, trace};
Andrew Walbrancc0db522021-07-12 17:03:42 +000054use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090055use rustutils::system_properties;
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};
Jiyong Park9dd389e2021-08-23 20:42:59 +090060use std::io::{Error, ErrorKind, Write};
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};
Andrew Walbrancc0db522021-07-12 17:03:42 +000067use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090068use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090069use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000070
Andrew Walbranf6bf6862021-05-21 12:41:13 +000071pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000072
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000074pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075
Jiyong Park8611a6c2021-07-09 18:17:44 +090076/// The CID representing the host VM
77const VMADDR_CID_HOST: u32 = 2;
78
Jooyung Han95884632021-07-06 22:27:54 +090079/// The size of zero.img.
80/// Gaps in composite disk images are filled with a shared zero.img.
81const ZERO_FILLER_SIZE: u64 = 4096;
82
Jiyong Park9dd389e2021-08-23 20:42:59 +090083/// Magic string for the instance image
84const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
85
86/// Version of the instance image format
87const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
88
Andrew Walbranf6bf6862021-05-21 12:41:13 +000089/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090090#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000091pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090092 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000093}
94
Shikha Panward8e35422021-10-11 13:51:27 +000095impl Interface for VirtualizationService {
96 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
97 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
98 let state = &mut *self.state.lock().unwrap();
99 let vms = state.vms();
100 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
101 for vm in vms {
102 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
104 .or(Err(StatusCode::UNKNOWN_ERROR))?;
105 writeln!(file, "\tPayload state {:?}", vm.payload_state())
106 .or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
113 .or(Err(StatusCode::UNKNOWN_ERROR))?;
114 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
115 .or(Err(StatusCode::UNKNOWN_ERROR))?;
116 }
117 Ok(())
118 }
119}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000121impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
123 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000124 ///
125 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000127 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000128 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900129 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000130 log_fd: Option<&ParcelFileDescriptor>,
131 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900132 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000133 let state = &mut *self.state.lock().unwrap();
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900134 let mut console_fd = console_fd.map(clone_file).transpose()?;
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900135 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000136 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000137 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000138 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900139 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000140
141 // Counter to generate unique IDs for temporary image files.
142 let mut next_temporary_image_id = 0;
143 // Files which are referred to from composite images. These must be mapped to the crosvm
144 // child process, and not closed before it is started.
145 let mut indirect_files = vec![];
146
147 // Make directory for temporary files.
148 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
149 create_dir(&temporary_directory).map_err(|e| {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000150 // At this point, we do not know the protected status of Vm
151 // setting it to false, though this may not be correct.
152 write_vm_creation_stats(false, false);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000153 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000154 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000155 temporary_directory, e
156 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000157 new_binder_exception(
158 ExceptionCode::SERVICE_SPECIFIC,
159 format!(
160 "Failed to create temporary directory {:?} for VM files: {}",
161 temporary_directory, e
162 ),
163 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 })?;
165
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900166 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
167 // console output when debug level != full. So, users won't be able to see the kernel
168 // output even without this overriding. This is to silence output from the bootloader which
169 // doesn't understand the bootconfig parameters.
170 if let VirtualMachineConfig::AppConfig(config) = config {
171 if config.debugLevel != DebugLevel::FULL {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900172 console_fd = None;
173 }
174 if config.debugLevel == DebugLevel::NONE {
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900175 log_fd = None;
176 }
177 }
178
Jiyong Park029977d2021-11-24 21:56:49 +0900179 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
180
Jooyung Han21e9b922021-06-26 04:14:16 +0900181 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900182 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900183 load_app_config(config, &temporary_directory).map_err(|e| {
184 error!("Failed to load app config from {}: {}", &config.configPath, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000185 write_vm_creation_stats(config.protectedVm, false);
Jooyung Han9900f3d2021-07-06 10:27:54 +0900186 new_binder_exception(
187 ExceptionCode::SERVICE_SPECIFIC,
188 format!("Failed to load app config from {}: {}", &config.configPath, e),
189 )
190 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900191 ),
192 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900193 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900194 let config = config.as_ref();
Andrew Walbran3994f002022-01-27 17:33:45 +0000195 let protected = config.protectedVm;
196
Jiyong Park029977d2021-11-24 21:56:49 +0900197 // Check if partition images are labeled incorrectly. This is to prevent random images
198 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
199 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
200 // to be labeled as app_data_file. For images in the app config, nothing but the instance
201 // partition is allowed to be labeled as such.
202 config
203 .disks
204 .iter()
205 .flat_map(|disk| disk.partitions.iter())
206 .filter(|partition| {
207 if is_app_config {
208 partition.label != "vm-instance"
209 } else {
210 true // all partitions are checked
211 }
212 })
213 .try_for_each(check_label_for_partition)
214 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
215
Jooyung Han95884632021-07-06 22:27:54 +0900216 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000217 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900218 error!("Failed to make composite image: {}", e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000219 write_vm_creation_stats(protected, false);
Jooyung Han95884632021-07-06 22:27:54 +0900220 new_binder_exception(
221 ExceptionCode::SERVICE_SPECIFIC,
222 format!("Failed to make composite image: {}", e),
223 )
224 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900225
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000226 // Assemble disk images if needed.
227 let disks = config
228 .disks
229 .iter()
230 .map(|disk| {
231 assemble_disk_image(
232 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900233 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 &temporary_directory,
235 &mut next_temporary_image_id,
236 &mut indirect_files,
237 )
238 })
239 .collect::<Result<Vec<DiskFile>, _>>()?;
240
241 // Actually start the VM.
242 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000243 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000244 bootloader: maybe_clone_file(&config.bootloader)?,
245 kernel: maybe_clone_file(&config.kernel)?,
246 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000247 disks,
248 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900249 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000250 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900251 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
252 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900253 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000254 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000255 indirect_files,
256 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000257 let instance = Arc::new(
258 VmInstance::new(
259 crosvm_config,
260 temporary_directory,
261 requester_uid,
262 requester_sid,
263 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000264 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000265 .map_err(|e| {
266 error!("Failed to create VM with config {:?}: {}", config, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000267 write_vm_creation_stats(protected, false);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000268 new_binder_exception(
269 ExceptionCode::SERVICE_SPECIFIC,
270 format!("Failed to create VM: {}", e),
271 )
272 })?,
273 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000274 state.add_vm(Arc::downgrade(&instance));
Andrew Walbran3994f002022-01-27 17:33:45 +0000275 write_vm_creation_stats(protected, true);
Andrew Walbran320b5602021-03-04 16:11:12 +0000276 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000277 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000278
Andrew Walbrandff3b942021-06-09 15:20:36 +0000279 /// Initialise an empty partition image of the given size to be used as a writable partition.
280 fn initializeWritablePartition(
281 &self,
282 image_fd: &ParcelFileDescriptor,
283 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900284 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000285 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900286 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000287 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000288 new_binder_exception(
289 ExceptionCode::ILLEGAL_ARGUMENT,
290 format!("Invalid size {}: {}", size, e),
291 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000292 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000293 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900294 // initialize the file. Any data in the file will be erased.
295 image.set_len(0).map_err(|e| {
296 new_binder_exception(
297 ExceptionCode::SERVICE_SPECIFIC,
298 format!("Failed to reset a file: {}", e),
299 )
300 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900301 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000302 new_binder_exception(
303 ExceptionCode::SERVICE_SPECIFIC,
304 format!("Failed to create QCOW2 image: {}", e),
305 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000306 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000307
Jiyong Park9dd389e2021-08-23 20:42:59 +0900308 match partition_type {
309 PartitionType::RAW => Ok(()),
310 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
311 _ => Err(Error::new(
312 ErrorKind::Unsupported,
313 format!("Unsupported partition type {:?}", partition_type),
314 )),
315 }
316 .map_err(|e| {
317 new_binder_exception(
318 ExceptionCode::SERVICE_SPECIFIC,
319 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
320 )
321 })?;
322
Andrew Walbrandff3b942021-06-09 15:20:36 +0000323 Ok(())
324 }
325
Jiyong Park0a248432021-08-20 23:32:39 +0900326 /// Creates or update the idsig file by digesting the input APK file.
327 fn createOrUpdateIdsigFile(
328 &self,
329 input_fd: &ParcelFileDescriptor,
330 idsig_fd: &ParcelFileDescriptor,
331 ) -> binder::Result<()> {
332 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
333 // idsig_fd is different from APK digest in input_fd
334
335 let mut input = clone_file(input_fd)?;
336 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
337
338 let mut output = clone_file(idsig_fd)?;
339 output.set_len(0).unwrap();
340 sig.write_into(&mut output).unwrap();
341 Ok(())
342 }
343
Andrew Walbran320b5602021-03-04 16:11:12 +0000344 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
345 /// and as such is only permitted from the shell user.
346 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000347 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000348
349 let state = &mut *self.state.lock().unwrap();
350 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000351 let cids = vms
352 .into_iter()
353 .map(|vm| VirtualMachineDebugInfo {
354 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000355 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000356 requesterUid: vm.requester_uid as i32,
357 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000358 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000359 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000360 })
361 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000362 Ok(cids)
363 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000364
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000365 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
366 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000367 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000368 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000369
David Brazdil3c2ddef2021-03-18 13:09:57 +0000370 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000371 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000372 Ok(())
373 }
374
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000375 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
376 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
377 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000378 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000379 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000380
381 let state = &mut *self.state.lock().unwrap();
382 Ok(state.debug_drop_vm(cid))
383 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000384}
385
Jiyong Park8611a6c2021-07-09 18:17:44 +0900386impl VirtualizationService {
387 pub fn init() -> VirtualizationService {
388 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900389
390 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900391 let state = service.state.clone(); // reference to state (not the state itself) is copied
392 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900393 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900394 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900395
396 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000397 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900398 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000399 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
400
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900401 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000402 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
403 // lifetime of the state, with context taking the pointer value above (so a properly
404 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900405 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000406 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
407 Some(VirtualMachineService::factory),
408 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900409 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900410 )
411 };
412 if retval {
413 debug!("RPC server has shut down gracefully");
414 } else {
415 bail!("Premature termination of RPC server");
416 }
417
418 Ok(retval)
419 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900420 service
421 }
422}
423
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000424/// Write the stats of VMCreation to statsd
425fn write_vm_creation_stats(protected: bool, success: bool) {
426 match stats_write(Hypervisor::Pkvm, protected, success) {
427 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000428 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000429 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000430 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000431 }
432}
433
Andrew Walbran6b650662021-09-07 13:13:23 +0000434/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
435/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900436fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900437 let listener =
438 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900439 for stream in listener.incoming() {
440 let stream = match stream {
441 Err(e) => {
442 warn!("invalid incoming connection: {}", e);
443 continue;
444 }
445 Ok(s) => s,
446 };
447 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
448 let cid = addr.cid();
449 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900450 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900451 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700452 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900453 } else {
454 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900455 }
456 }
457 }
458 Ok(())
459}
460
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000461fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900462 let file = OpenOptions::new()
463 .create_new(true)
464 .read(true)
465 .write(true)
466 .open(zero_filler_path)
467 .with_context(|| "Failed to create zero.img")?;
468 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000469 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900470}
471
Jiyong Park9dd389e2021-08-23 20:42:59 +0900472fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
473 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
474 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
475 part.flush()
476}
477
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000478/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
479///
480/// This may involve assembling a composite disk from a set of partition images.
481fn assemble_disk_image(
482 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900483 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000484 temporary_directory: &Path,
485 next_temporary_image_id: &mut u64,
486 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000487) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000488 let image = if !disk.partitions.is_empty() {
489 if disk.image.is_some() {
490 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000491 return Err(new_binder_exception(
492 ExceptionCode::ILLEGAL_ARGUMENT,
493 "DiskImage contains both image and partitions.",
494 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000495 }
496
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000497 let composite_image_filenames =
498 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
499 let (image, partition_files) = make_composite_image(
500 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900501 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000502 &composite_image_filenames.composite,
503 &composite_image_filenames.header,
504 &composite_image_filenames.footer,
505 )
506 .map_err(|e| {
507 error!("Failed to make composite image with config {:?}: {}", disk, e);
508 new_binder_exception(
509 ExceptionCode::SERVICE_SPECIFIC,
510 format!("Failed to make composite image: {}", e),
511 )
512 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000513
514 // Pass the file descriptors for the various partition files to crosvm when it
515 // is run.
516 indirect_files.extend(partition_files);
517
518 image
519 } else if let Some(image) = &disk.image {
520 clone_file(image)?
521 } else {
522 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000523 return Err(new_binder_exception(
524 ExceptionCode::ILLEGAL_ARGUMENT,
525 "DiskImage didn't contain image or partitions.",
526 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000527 };
528
529 Ok(DiskFile { image, writable: disk.writable })
530}
531
Jooyung Han21e9b922021-06-26 04:14:16 +0900532fn load_app_config(
533 config: &VirtualMachineAppConfig,
534 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900535) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000536 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
537 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900538 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900539 let config_path = &config.configPath;
540
Andrew Walbrancc0db522021-07-12 17:03:42 +0000541 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900542 let config_file = apk_zip.by_name(config_path)?;
543 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
544
545 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000546
Jooyung Han35edb8f2021-07-01 16:17:16 +0900547 // For now, the only supported "os" value is "microdroid"
548 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000549 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900550 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000551
552 // It is safe to construct a filename based on the os_name because we've already checked that it
553 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900554 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
555 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000556 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900557
Andrew Walbrancc045902021-07-27 16:06:17 +0000558 if config.memoryMib > 0 {
559 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000560 }
561
Andrew Walbran3994f002022-01-27 17:33:45 +0000562 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900563 vm_config.numCpus = config.numCpus;
564 vm_config.cpuAffinity = config.cpuAffinity.clone();
565
Andrew Walbrancc0db522021-07-12 17:03:42 +0000566 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900567 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000568 add_microdroid_images(
569 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900570 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000571 apk_file,
572 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900573 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900574 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000575 &mut vm_config,
576 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900577 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900578
Andrew Walbrancc0db522021-07-12 17:03:42 +0000579 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900580}
581
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000582/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000583fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000584 temporary_directory: &Path,
585 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000586) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000587 let id = *next_temporary_image_id;
588 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000589 CompositeImageFilenames {
590 composite: temporary_directory.join(format!("composite-{}.img", id)),
591 header: temporary_directory.join(format!("composite-{}-header.img", id)),
592 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
593 }
594}
595
596/// Filenames for a composite disk image, including header and footer partitions.
597#[derive(Clone, Debug, Eq, PartialEq)]
598struct CompositeImageFilenames {
599 /// The composite disk image itself.
600 composite: PathBuf,
601 /// The header partition image.
602 header: PathBuf,
603 /// The footer partition image.
604 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000605}
606
607/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000608fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000609 ThreadState::with_calling_sid(|sid| {
610 if let Some(sid) = sid {
611 match sid.to_str() {
612 Ok(sid) => Ok(sid.to_owned()),
613 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000614 error!("SID was not valid UTF-8: {}", e);
615 Err(new_binder_exception(
616 ExceptionCode::ILLEGAL_ARGUMENT,
617 format!("SID was not valid UTF-8: {}", e),
618 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000619 }
620 }
621 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000622 error!("Missing SID on createVm");
623 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000624 }
625 })
626}
627
Jiyong Park753553b2021-07-12 21:21:09 +0900628/// Checks whether the caller has a specific permission
629fn check_permission(perm: &str) -> binder::Result<()> {
630 let calling_pid = ThreadState::get_calling_pid();
631 let calling_uid = ThreadState::get_calling_uid();
632 // Root can do anything
633 if calling_uid == 0 {
634 return Ok(());
635 }
636 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
637 binder::get_interface("permission")?;
638 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000639 Ok(())
640 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900641 Err(new_binder_exception(
642 ExceptionCode::SECURITY,
643 format!("does not have the {} permission", perm),
644 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000645 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000646}
647
Jiyong Park753553b2021-07-12 21:21:09 +0900648/// Check whether the caller of the current Binder method is allowed to call debug methods.
649fn check_debug_access() -> binder::Result<()> {
650 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
651}
652
653/// Check whether the caller of the current Binder method is allowed to manage VMs
654fn check_manage_access() -> binder::Result<()> {
655 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
656}
657
Jiyong Park029977d2021-11-24 21:56:49 +0900658/// Check if a partition has selinux labels that are not allowed
659fn check_label_for_partition(partition: &Partition) -> Result<()> {
660 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
661 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
662 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
663 } else {
664 Ok(())
665 }
666}
667
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000668/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
669#[derive(Debug)]
670struct VirtualMachine {
671 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100672 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800673 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100674 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000675}
676
677impl VirtualMachine {
678 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100679 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000680 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000681 }
682}
683
684impl Interface for VirtualMachine {}
685
686impl IVirtualMachine for VirtualMachine {
687 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900688 // Don't check permission. The owner of the VM might have passed this binder object to
689 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000690 Ok(self.instance.cid as i32)
691 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000692
Andrew Walbran6b650662021-09-07 13:13:23 +0000693 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900694 // Don't check permission. The owner of the VM might have passed this binder object to
695 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000696 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000697 }
698
699 fn registerCallback(
700 &self,
701 callback: &Strong<dyn IVirtualMachineCallback>,
702 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900703 // Don't check permission. The owner of the VM might have passed this binder object to
704 // others.
705 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000706 // TODO: Should this give an error if the VM is already dead?
707 self.instance.callbacks.add(callback.clone());
708 Ok(())
709 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000710
Andrew Walbranf8d94112021-09-07 11:45:36 +0000711 fn start(&self) -> binder::Result<()> {
712 self.instance.start().map_err(|e| {
713 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
714 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
715 })
716 }
717
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000718 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000719 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
720 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000721 }
722 let stream =
723 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
724 new_binder_exception(
725 ExceptionCode::SERVICE_SPECIFIC,
726 format!("Failed to connect: {}", e),
727 )
728 })?;
729 Ok(vsock_stream_to_pfd(stream))
730 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000731}
732
733impl Drop for VirtualMachine {
734 fn drop(&mut self) {
735 debug!("Dropping {:?}", self);
736 self.instance.kill();
737 }
738}
739
740/// A set of Binders to be called back in response to various events on the VM, such as when it
741/// dies.
742#[derive(Debug, Default)]
743pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
744
745impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900746 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900747 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900748 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900749 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900750 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900751 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900752 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
753 }
754 }
755 }
756
Inseob Kim14cb8692021-08-31 21:50:39 +0900757 /// Call all registered callbacks to notify that the payload is ready to serve.
758 pub fn notify_payload_ready(&self, cid: Cid) {
759 let callbacks = &*self.0.lock().unwrap();
760 for callback in callbacks {
761 if let Err(e) = callback.onPayloadReady(cid as i32) {
762 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
763 }
764 }
765 }
766
Inseob Kim2444af92021-08-31 01:22:50 +0900767 /// Call all registered callbacks to notify that the payload has finished.
768 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
769 let callbacks = &*self.0.lock().unwrap();
770 for callback in callbacks {
771 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
772 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
773 }
774 }
775 }
776
Jooyung Handd0a1732021-11-23 15:26:20 +0900777 /// Call all registered callbacks to say that the VM encountered an error.
778 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
779 let callbacks = &*self.0.lock().unwrap();
780 for callback in callbacks {
781 if let Err(e) = callback.onError(cid as i32, error_code, message) {
782 error!("Error notifying error event from VM CID {}: {}", cid, e);
783 }
784 }
785 }
786
Andrew Walbrandae07162021-03-12 17:05:20 +0000787 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000788 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000789 let callbacks = &*self.0.lock().unwrap();
790 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000791 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900792 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000793 }
794 }
795 }
796
797 /// Add a new callback to the set.
798 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
799 self.0.lock().unwrap().push(callback);
800 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000801}
802
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000803/// The mutable state of the VirtualizationService. There should only be one instance of this
804/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800805#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000806struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000807 /// The VMs which have been started. When VMs are started a weak reference is added to this list
808 /// while a strong reference is returned to the caller over Binder. Once all copies of the
809 /// Binder client are dropped the weak reference here will become invalid, and will be removed
810 /// from the list opportunistically the next time `add_vm` is called.
811 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000812
813 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
814 /// This is only used for debugging purposes.
815 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000816}
817
818impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000819 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000820 fn vms(&self) -> Vec<Arc<VmInstance>> {
821 // Attempt to upgrade the weak pointers to strong pointers.
822 self.vms.iter().filter_map(Weak::upgrade).collect()
823 }
824
825 /// Add a new VM to the list.
826 fn add_vm(&mut self, vm: Weak<VmInstance>) {
827 // Garbage collect any entries from the stored list which no longer exist.
828 self.vms.retain(|vm| vm.strong_count() > 0);
829
830 // Actually add the new VM.
831 self.vms.push(vm);
832 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000833
Jiyong Park8611a6c2021-07-09 18:17:44 +0900834 /// Get a VM that corresponds to the given cid
835 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
836 self.vms().into_iter().find(|vm| vm.cid == cid)
837 }
838
David Brazdil3c2ddef2021-03-18 13:09:57 +0000839 /// Store a strong VM reference.
840 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
841 self.debug_held_vms.push(vm);
842 }
843
844 /// Retrieve and remove a strong VM reference.
845 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
846 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100847 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100848 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000849 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000850}
851
Jiyong Parkd50a0242021-09-16 21:00:14 +0900852/// Get the next available CID, or an error if we have run out. The last CID used is stored in
853/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
854/// Android is up.
855fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000856 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900857 if let Ok(num) = val.parse::<u32>() {
858 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
859 } else {
860 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
861 FIRST_GUEST_CID
862 }
863 } else {
864 // First VM since the boot
865 FIRST_GUEST_CID
866 };
867 // Persist the last value for next use
868 let str_val = format!("{}", next);
869 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
870 Ok(next)
871}
872
Andrew Walbran6b650662021-09-07 13:13:23 +0000873/// Gets the `VirtualMachineState` of the given `VmInstance`.
874fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000875 match &*instance.vm_state.lock().unwrap() {
876 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
877 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000878 PayloadState::Starting => VirtualMachineState::STARTING,
879 PayloadState::Started => VirtualMachineState::STARTED,
880 PayloadState::Ready => VirtualMachineState::READY,
881 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000882 },
883 VmState::Dead => VirtualMachineState::DEAD,
884 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000885 }
886}
887
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000888/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000889fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
890 file.as_ref().try_clone().map_err(|e| {
891 new_binder_exception(
892 ExceptionCode::BAD_PARCELABLE,
893 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
894 )
895 })
896}
897
Andrew Walbrand3a84182021-09-07 14:48:52 +0000898/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
899fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
900 file.as_ref().map(clone_file).transpose()
901}
902
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000903/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
904fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
905 // SAFETY: ownership is transferred from stream to f
906 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
907 ParcelFileDescriptor::new(f)
908}
909
Jooyung Han35edb8f2021-07-01 16:17:16 +0900910/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
911/// it doesn't require that T implements Clone.
912enum BorrowedOrOwned<'a, T> {
913 Borrowed(&'a T),
914 Owned(T),
915}
916
917impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
918 fn as_ref(&self) -> &T {
919 match self {
920 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700921 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900922 }
923 }
924}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900925
926/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
927#[derive(Debug, Default)]
928struct VirtualMachineService {
929 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000930 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900931}
932
933impl Interface for VirtualMachineService {}
934
935impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000936 fn notifyPayloadStarted(&self) -> binder::Result<()> {
937 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900938 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
939 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000940 vm.update_payload_state(PayloadState::Started)
941 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900942 let stream = vm.stream.lock().unwrap().take();
943 vm.callbacks.notify_payload_started(cid, stream);
944 Ok(())
945 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900946 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900947 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900948 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900949 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900950 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900951 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900952 }
Inseob Kim2444af92021-08-31 01:22:50 +0900953
Inseob Kimc7d28c72021-10-25 14:28:10 +0000954 fn notifyPayloadReady(&self) -> binder::Result<()> {
955 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900956 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
957 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000958 vm.update_payload_state(PayloadState::Ready)
959 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900960 vm.callbacks.notify_payload_ready(cid);
961 Ok(())
962 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900963 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900964 Err(new_binder_exception(
965 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900966 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900967 ))
968 }
969 }
970
Inseob Kimc7d28c72021-10-25 14:28:10 +0000971 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
972 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900973 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
974 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000975 vm.update_payload_state(PayloadState::Finished)
976 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900977 vm.callbacks.notify_payload_finished(cid, exit_code);
978 Ok(())
979 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900980 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900981 Err(new_binder_exception(
982 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900983 format!("cannot find a VM with CID {}", cid),
984 ))
985 }
986 }
987
988 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
989 let cid = self.cid;
990 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
991 info!("VM having CID {} encountered an error", cid);
992 vm.update_payload_state(PayloadState::Finished)
993 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
994 vm.callbacks.notify_error(cid, error_code, message);
995 Ok(())
996 } else {
997 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
998 Err(new_binder_exception(
999 ExceptionCode::SERVICE_SPECIFIC,
1000 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001001 ))
1002 }
1003 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001004}
1005
1006impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001007 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1008 pub unsafe extern "C" fn factory(
1009 cid: Cid,
1010 context: *mut raw::c_void,
1011 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1012 let state_ptr = context as *mut Arc<Mutex<State>>;
1013 let state = state_ptr.as_ref().unwrap();
1014 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1015 let mut vm_service = vm.vm_service.lock().unwrap();
1016 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1017 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1018 } else {
1019 error!("connection from cid={} is not from a guest VM", cid);
1020 null_mut()
1021 }
1022 }
1023
1024 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001025 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001026 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001027 BinderFeatures::default(),
1028 )
1029 }
1030}